1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.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/Builtins.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 #include "llvm/Support/SaveAndRestore.h" 50 using namespace clang; 51 using namespace sema; 52 using llvm::RoundingMode; 53 54 /// Determine whether the use of this declaration is valid, without 55 /// emitting diagnostics. 56 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 57 // See if this is an auto-typed variable whose initializer we are parsing. 58 if (ParsingInitForAutoVars.count(D)) 59 return false; 60 61 // See if this is a deleted function. 62 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 63 if (FD->isDeleted()) 64 return false; 65 66 // If the function has a deduced return type, and we can't deduce it, 67 // then we can't use it either. 68 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 69 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 70 return false; 71 72 // See if this is an aligned allocation/deallocation function that is 73 // unavailable. 74 if (TreatUnavailableAsInvalid && 75 isUnavailableAlignedAllocationFunction(*FD)) 76 return false; 77 } 78 79 // See if this function is unavailable. 80 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 81 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 82 return false; 83 84 return true; 85 } 86 87 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 88 // Warn if this is used but marked unused. 89 if (const auto *A = D->getAttr<UnusedAttr>()) { 90 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 91 // should diagnose them. 92 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 93 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 94 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 95 if (DC && !DC->hasAttr<UnusedAttr>()) 96 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 97 } 98 } 99 } 100 101 /// Emit a note explaining that this function is deleted. 102 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 103 assert(Decl && Decl->isDeleted()); 104 105 if (Decl->isDefaulted()) { 106 // If the method was explicitly defaulted, point at that declaration. 107 if (!Decl->isImplicit()) 108 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 109 110 // Try to diagnose why this special member function was implicitly 111 // deleted. This might fail, if that reason no longer applies. 112 DiagnoseDeletedDefaultedFunction(Decl); 113 return; 114 } 115 116 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 117 if (Ctor && Ctor->isInheritingConstructor()) 118 return NoteDeletedInheritingConstructor(Ctor); 119 120 Diag(Decl->getLocation(), diag::note_availability_specified_here) 121 << Decl << 1; 122 } 123 124 /// Determine whether a FunctionDecl was ever declared with an 125 /// explicit storage class. 126 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 127 for (auto I : D->redecls()) { 128 if (I->getStorageClass() != SC_None) 129 return true; 130 } 131 return false; 132 } 133 134 /// Check whether we're in an extern inline function and referring to a 135 /// variable or function with internal linkage (C11 6.7.4p3). 136 /// 137 /// This is only a warning because we used to silently accept this code, but 138 /// in many cases it will not behave correctly. This is not enabled in C++ mode 139 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 140 /// and so while there may still be user mistakes, most of the time we can't 141 /// prove that there are errors. 142 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 143 const NamedDecl *D, 144 SourceLocation Loc) { 145 // This is disabled under C++; there are too many ways for this to fire in 146 // contexts where the warning is a false positive, or where it is technically 147 // correct but benign. 148 if (S.getLangOpts().CPlusPlus) 149 return; 150 151 // Check if this is an inlined function or method. 152 FunctionDecl *Current = S.getCurFunctionDecl(); 153 if (!Current) 154 return; 155 if (!Current->isInlined()) 156 return; 157 if (!Current->isExternallyVisible()) 158 return; 159 160 // Check if the decl has internal linkage. 161 if (D->getFormalLinkage() != InternalLinkage) 162 return; 163 164 // Downgrade from ExtWarn to Extension if 165 // (1) the supposedly external inline function is in the main file, 166 // and probably won't be included anywhere else. 167 // (2) the thing we're referencing is a pure function. 168 // (3) the thing we're referencing is another inline function. 169 // This last can give us false negatives, but it's better than warning on 170 // wrappers for simple C library functions. 171 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 172 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 173 if (!DowngradeWarning && UsedFn) 174 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 175 176 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 177 : diag::ext_internal_in_extern_inline) 178 << /*IsVar=*/!UsedFn << D; 179 180 S.MaybeSuggestAddingStaticToDecl(Current); 181 182 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 183 << D; 184 } 185 186 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 187 const FunctionDecl *First = Cur->getFirstDecl(); 188 189 // Suggest "static" on the function, if possible. 190 if (!hasAnyExplicitStorageClass(First)) { 191 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 192 Diag(DeclBegin, diag::note_convert_inline_to_static) 193 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 194 } 195 } 196 197 /// Determine whether the use of this declaration is valid, and 198 /// emit any corresponding diagnostics. 199 /// 200 /// This routine diagnoses various problems with referencing 201 /// declarations that can occur when using a declaration. For example, 202 /// it might warn if a deprecated or unavailable declaration is being 203 /// used, or produce an error (and return true) if a C++0x deleted 204 /// function is being used. 205 /// 206 /// \returns true if there was an error (this declaration cannot be 207 /// referenced), false otherwise. 208 /// 209 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 210 const ObjCInterfaceDecl *UnknownObjCClass, 211 bool ObjCPropertyAccess, 212 bool AvoidPartialAvailabilityChecks, 213 ObjCInterfaceDecl *ClassReceiver) { 214 SourceLocation Loc = Locs.front(); 215 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 216 // If there were any diagnostics suppressed by template argument deduction, 217 // emit them now. 218 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 219 if (Pos != SuppressedDiagnostics.end()) { 220 for (const PartialDiagnosticAt &Suppressed : Pos->second) 221 Diag(Suppressed.first, Suppressed.second); 222 223 // Clear out the list of suppressed diagnostics, so that we don't emit 224 // them again for this specialization. However, we don't obsolete this 225 // entry from the table, because we want to avoid ever emitting these 226 // diagnostics again. 227 Pos->second.clear(); 228 } 229 230 // C++ [basic.start.main]p3: 231 // The function 'main' shall not be used within a program. 232 if (cast<FunctionDecl>(D)->isMain()) 233 Diag(Loc, diag::ext_main_used); 234 235 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 236 } 237 238 // See if this is an auto-typed variable whose initializer we are parsing. 239 if (ParsingInitForAutoVars.count(D)) { 240 if (isa<BindingDecl>(D)) { 241 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 242 << D->getDeclName(); 243 } else { 244 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 245 << D->getDeclName() << cast<VarDecl>(D)->getType(); 246 } 247 return true; 248 } 249 250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 251 // See if this is a deleted function. 252 if (FD->isDeleted()) { 253 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 254 if (Ctor && Ctor->isInheritingConstructor()) 255 Diag(Loc, diag::err_deleted_inherited_ctor_use) 256 << Ctor->getParent() 257 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 258 else 259 Diag(Loc, diag::err_deleted_function_use); 260 NoteDeletedFunction(FD); 261 return true; 262 } 263 264 // [expr.prim.id]p4 265 // A program that refers explicitly or implicitly to a function with a 266 // trailing requires-clause whose constraint-expression is not satisfied, 267 // other than to declare it, is ill-formed. [...] 268 // 269 // See if this is a function with constraints that need to be satisfied. 270 // Check this before deducing the return type, as it might instantiate the 271 // definition. 272 if (FD->getTrailingRequiresClause()) { 273 ConstraintSatisfaction Satisfaction; 274 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 275 // A diagnostic will have already been generated (non-constant 276 // constraint expression, for example) 277 return true; 278 if (!Satisfaction.IsSatisfied) { 279 Diag(Loc, 280 diag::err_reference_to_function_with_unsatisfied_constraints) 281 << D; 282 DiagnoseUnsatisfiedConstraint(Satisfaction); 283 return true; 284 } 285 } 286 287 // If the function has a deduced return type, and we can't deduce it, 288 // then we can't use it either. 289 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 290 DeduceReturnType(FD, Loc)) 291 return true; 292 293 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 294 return true; 295 296 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 297 return true; 298 } 299 300 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 301 // Lambdas are only default-constructible or assignable in C++2a onwards. 302 if (MD->getParent()->isLambda() && 303 ((isa<CXXConstructorDecl>(MD) && 304 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 305 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 306 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 307 << !isa<CXXConstructorDecl>(MD); 308 } 309 } 310 311 auto getReferencedObjCProp = [](const NamedDecl *D) -> 312 const ObjCPropertyDecl * { 313 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 314 return MD->findPropertyDecl(); 315 return nullptr; 316 }; 317 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 318 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 319 return true; 320 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 321 return true; 322 } 323 324 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 325 // Only the variables omp_in and omp_out are allowed in the combiner. 326 // Only the variables omp_priv and omp_orig are allowed in the 327 // initializer-clause. 328 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 329 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 330 isa<VarDecl>(D)) { 331 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 332 << getCurFunction()->HasOMPDeclareReductionCombiner; 333 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 334 return true; 335 } 336 337 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 338 // List-items in map clauses on this construct may only refer to the declared 339 // variable var and entities that could be referenced by a procedure defined 340 // at the same location 341 if (LangOpts.OpenMP && isa<VarDecl>(D) && 342 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 343 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 344 << getOpenMPDeclareMapperVarName(); 345 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 346 return true; 347 } 348 349 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 350 AvoidPartialAvailabilityChecks, ClassReceiver); 351 352 DiagnoseUnusedOfDecl(*this, D, Loc); 353 354 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 355 356 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 357 if (const auto *VD = dyn_cast<ValueDecl>(D)) 358 checkDeviceDecl(VD, Loc); 359 360 if (!Context.getTargetInfo().isTLSSupported()) 361 if (const auto *VD = dyn_cast<VarDecl>(D)) 362 if (VD->getTLSKind() != VarDecl::TLS_None) 363 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 364 } 365 366 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 367 !isUnevaluatedContext()) { 368 // C++ [expr.prim.req.nested] p3 369 // A local parameter shall only appear as an unevaluated operand 370 // (Clause 8) within the constraint-expression. 371 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 372 << D; 373 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 374 return true; 375 } 376 377 return false; 378 } 379 380 /// DiagnoseSentinelCalls - This routine checks whether a call or 381 /// message-send is to a declaration with the sentinel attribute, and 382 /// if so, it checks that the requirements of the sentinel are 383 /// satisfied. 384 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 385 ArrayRef<Expr *> Args) { 386 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 387 if (!attr) 388 return; 389 390 // The number of formal parameters of the declaration. 391 unsigned numFormalParams; 392 393 // The kind of declaration. This is also an index into a %select in 394 // the diagnostic. 395 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 396 397 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 398 numFormalParams = MD->param_size(); 399 calleeType = CT_Method; 400 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 401 numFormalParams = FD->param_size(); 402 calleeType = CT_Function; 403 } else if (isa<VarDecl>(D)) { 404 QualType type = cast<ValueDecl>(D)->getType(); 405 const FunctionType *fn = nullptr; 406 if (const PointerType *ptr = type->getAs<PointerType>()) { 407 fn = ptr->getPointeeType()->getAs<FunctionType>(); 408 if (!fn) return; 409 calleeType = CT_Function; 410 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 411 fn = ptr->getPointeeType()->castAs<FunctionType>(); 412 calleeType = CT_Block; 413 } else { 414 return; 415 } 416 417 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 418 numFormalParams = proto->getNumParams(); 419 } else { 420 numFormalParams = 0; 421 } 422 } else { 423 return; 424 } 425 426 // "nullPos" is the number of formal parameters at the end which 427 // effectively count as part of the variadic arguments. This is 428 // useful if you would prefer to not have *any* formal parameters, 429 // but the language forces you to have at least one. 430 unsigned nullPos = attr->getNullPos(); 431 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 432 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 433 434 // The number of arguments which should follow the sentinel. 435 unsigned numArgsAfterSentinel = attr->getSentinel(); 436 437 // If there aren't enough arguments for all the formal parameters, 438 // the sentinel, and the args after the sentinel, complain. 439 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 440 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 441 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 442 return; 443 } 444 445 // Otherwise, find the sentinel expression. 446 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 447 if (!sentinelExpr) return; 448 if (sentinelExpr->isValueDependent()) return; 449 if (Context.isSentinelNullExpr(sentinelExpr)) return; 450 451 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 452 // or 'NULL' if those are actually defined in the context. Only use 453 // 'nil' for ObjC methods, where it's much more likely that the 454 // variadic arguments form a list of object pointers. 455 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 456 std::string NullValue; 457 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 458 NullValue = "nil"; 459 else if (getLangOpts().CPlusPlus11) 460 NullValue = "nullptr"; 461 else if (PP.isMacroDefined("NULL")) 462 NullValue = "NULL"; 463 else 464 NullValue = "(void*) 0"; 465 466 if (MissingNilLoc.isInvalid()) 467 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 468 else 469 Diag(MissingNilLoc, diag::warn_missing_sentinel) 470 << int(calleeType) 471 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 472 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 473 } 474 475 SourceRange Sema::getExprRange(Expr *E) const { 476 return E ? E->getSourceRange() : SourceRange(); 477 } 478 479 //===----------------------------------------------------------------------===// 480 // Standard Promotions and Conversions 481 //===----------------------------------------------------------------------===// 482 483 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 484 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 485 // Handle any placeholder expressions which made it here. 486 if (E->getType()->isPlaceholderType()) { 487 ExprResult result = CheckPlaceholderExpr(E); 488 if (result.isInvalid()) return ExprError(); 489 E = result.get(); 490 } 491 492 QualType Ty = E->getType(); 493 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 494 495 if (Ty->isFunctionType()) { 496 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 497 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 498 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 499 return ExprError(); 500 501 E = ImpCastExprToType(E, Context.getPointerType(Ty), 502 CK_FunctionToPointerDecay).get(); 503 } else if (Ty->isArrayType()) { 504 // In C90 mode, arrays only promote to pointers if the array expression is 505 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 506 // type 'array of type' is converted to an expression that has type 'pointer 507 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 508 // that has type 'array of type' ...". The relevant change is "an lvalue" 509 // (C90) to "an expression" (C99). 510 // 511 // C++ 4.2p1: 512 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 513 // T" can be converted to an rvalue of type "pointer to T". 514 // 515 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 516 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 517 CK_ArrayToPointerDecay).get(); 518 } 519 return E; 520 } 521 522 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 523 // Check to see if we are dereferencing a null pointer. If so, 524 // and if not volatile-qualified, this is undefined behavior that the 525 // optimizer will delete, so warn about it. People sometimes try to use this 526 // to get a deterministic trap and are surprised by clang's behavior. This 527 // only handles the pattern "*null", which is a very syntactic check. 528 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 529 if (UO && UO->getOpcode() == UO_Deref && 530 UO->getSubExpr()->getType()->isPointerType()) { 531 const LangAS AS = 532 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 533 if ((!isTargetAddressSpace(AS) || 534 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 535 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 536 S.Context, Expr::NPC_ValueDependentIsNotNull) && 537 !UO->getType().isVolatileQualified()) { 538 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 539 S.PDiag(diag::warn_indirection_through_null) 540 << UO->getSubExpr()->getSourceRange()); 541 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 542 S.PDiag(diag::note_indirection_through_null)); 543 } 544 } 545 } 546 547 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 548 SourceLocation AssignLoc, 549 const Expr* RHS) { 550 const ObjCIvarDecl *IV = OIRE->getDecl(); 551 if (!IV) 552 return; 553 554 DeclarationName MemberName = IV->getDeclName(); 555 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 556 if (!Member || !Member->isStr("isa")) 557 return; 558 559 const Expr *Base = OIRE->getBase(); 560 QualType BaseType = Base->getType(); 561 if (OIRE->isArrow()) 562 BaseType = BaseType->getPointeeType(); 563 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 564 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 565 ObjCInterfaceDecl *ClassDeclared = nullptr; 566 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 567 if (!ClassDeclared->getSuperClass() 568 && (*ClassDeclared->ivar_begin()) == IV) { 569 if (RHS) { 570 NamedDecl *ObjectSetClass = 571 S.LookupSingleName(S.TUScope, 572 &S.Context.Idents.get("object_setClass"), 573 SourceLocation(), S.LookupOrdinaryName); 574 if (ObjectSetClass) { 575 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 576 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 577 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 578 "object_setClass(") 579 << FixItHint::CreateReplacement( 580 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 581 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 582 } 583 else 584 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 585 } else { 586 NamedDecl *ObjectGetClass = 587 S.LookupSingleName(S.TUScope, 588 &S.Context.Idents.get("object_getClass"), 589 SourceLocation(), S.LookupOrdinaryName); 590 if (ObjectGetClass) 591 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 592 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 593 "object_getClass(") 594 << FixItHint::CreateReplacement( 595 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 596 else 597 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 598 } 599 S.Diag(IV->getLocation(), diag::note_ivar_decl); 600 } 601 } 602 } 603 604 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 605 // Handle any placeholder expressions which made it here. 606 if (E->getType()->isPlaceholderType()) { 607 ExprResult result = CheckPlaceholderExpr(E); 608 if (result.isInvalid()) return ExprError(); 609 E = result.get(); 610 } 611 612 // C++ [conv.lval]p1: 613 // A glvalue of a non-function, non-array type T can be 614 // converted to a prvalue. 615 if (!E->isGLValue()) return E; 616 617 QualType T = E->getType(); 618 assert(!T.isNull() && "r-value conversion on typeless expression?"); 619 620 // lvalue-to-rvalue conversion cannot be applied to function or array types. 621 if (T->isFunctionType() || T->isArrayType()) 622 return E; 623 624 // We don't want to throw lvalue-to-rvalue casts on top of 625 // expressions of certain types in C++. 626 if (getLangOpts().CPlusPlus && 627 (E->getType() == Context.OverloadTy || 628 T->isDependentType() || 629 T->isRecordType())) 630 return E; 631 632 // The C standard is actually really unclear on this point, and 633 // DR106 tells us what the result should be but not why. It's 634 // generally best to say that void types just doesn't undergo 635 // lvalue-to-rvalue at all. Note that expressions of unqualified 636 // 'void' type are never l-values, but qualified void can be. 637 if (T->isVoidType()) 638 return E; 639 640 // OpenCL usually rejects direct accesses to values of 'half' type. 641 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 642 T->isHalfType()) { 643 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 644 << 0 << T; 645 return ExprError(); 646 } 647 648 CheckForNullPointerDereference(*this, E); 649 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 650 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 651 &Context.Idents.get("object_getClass"), 652 SourceLocation(), LookupOrdinaryName); 653 if (ObjectGetClass) 654 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 655 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 656 << FixItHint::CreateReplacement( 657 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 658 else 659 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 660 } 661 else if (const ObjCIvarRefExpr *OIRE = 662 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 663 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 664 665 // C++ [conv.lval]p1: 666 // [...] If T is a non-class type, the type of the prvalue is the 667 // cv-unqualified version of T. Otherwise, the type of the 668 // rvalue is T. 669 // 670 // C99 6.3.2.1p2: 671 // If the lvalue has qualified type, the value has the unqualified 672 // version of the type of the lvalue; otherwise, the value has the 673 // type of the lvalue. 674 if (T.hasQualifiers()) 675 T = T.getUnqualifiedType(); 676 677 // Under the MS ABI, lock down the inheritance model now. 678 if (T->isMemberPointerType() && 679 Context.getTargetInfo().getCXXABI().isMicrosoft()) 680 (void)isCompleteType(E->getExprLoc(), T); 681 682 ExprResult Res = CheckLValueToRValueConversionOperand(E); 683 if (Res.isInvalid()) 684 return Res; 685 E = Res.get(); 686 687 // Loading a __weak object implicitly retains the value, so we need a cleanup to 688 // balance that. 689 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 690 Cleanup.setExprNeedsCleanups(true); 691 692 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 693 Cleanup.setExprNeedsCleanups(true); 694 695 // C++ [conv.lval]p3: 696 // If T is cv std::nullptr_t, the result is a null pointer constant. 697 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 698 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 699 FPOptionsOverride()); 700 701 // C11 6.3.2.1p2: 702 // ... if the lvalue has atomic type, the value has the non-atomic version 703 // of the type of the lvalue ... 704 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 705 T = Atomic->getValueType().getUnqualifiedType(); 706 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 707 nullptr, VK_RValue, FPOptionsOverride()); 708 } 709 710 return Res; 711 } 712 713 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 714 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 715 if (Res.isInvalid()) 716 return ExprError(); 717 Res = DefaultLvalueConversion(Res.get()); 718 if (Res.isInvalid()) 719 return ExprError(); 720 return Res; 721 } 722 723 /// CallExprUnaryConversions - a special case of an unary conversion 724 /// performed on a function designator of a call expression. 725 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 726 QualType Ty = E->getType(); 727 ExprResult Res = E; 728 // Only do implicit cast for a function type, but not for a pointer 729 // to function type. 730 if (Ty->isFunctionType()) { 731 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 732 CK_FunctionToPointerDecay); 733 if (Res.isInvalid()) 734 return ExprError(); 735 } 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res.get(); 740 } 741 742 /// UsualUnaryConversions - Performs various conversions that are common to most 743 /// operators (C99 6.3). The conversions of array and function types are 744 /// sometimes suppressed. For example, the array->pointer conversion doesn't 745 /// apply if the array is an argument to the sizeof or address (&) operators. 746 /// In these instances, this routine should *not* be called. 747 ExprResult Sema::UsualUnaryConversions(Expr *E) { 748 // First, convert to an r-value. 749 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 750 if (Res.isInvalid()) 751 return ExprError(); 752 E = Res.get(); 753 754 QualType Ty = E->getType(); 755 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 756 757 // Half FP have to be promoted to float unless it is natively supported 758 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 759 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 760 761 // Try to perform integral promotions if the object has a theoretically 762 // promotable type. 763 if (Ty->isIntegralOrUnscopedEnumerationType()) { 764 // C99 6.3.1.1p2: 765 // 766 // The following may be used in an expression wherever an int or 767 // unsigned int may be used: 768 // - an object or expression with an integer type whose integer 769 // conversion rank is less than or equal to the rank of int 770 // and unsigned int. 771 // - A bit-field of type _Bool, int, signed int, or unsigned int. 772 // 773 // If an int can represent all values of the original type, the 774 // value is converted to an int; otherwise, it is converted to an 775 // unsigned int. These are called the integer promotions. All 776 // other types are unchanged by the integer promotions. 777 778 QualType PTy = Context.isPromotableBitField(E); 779 if (!PTy.isNull()) { 780 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 781 return E; 782 } 783 if (Ty->isPromotableIntegerType()) { 784 QualType PT = Context.getPromotedIntegerType(Ty); 785 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 786 return E; 787 } 788 } 789 return E; 790 } 791 792 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 793 /// do not have a prototype. Arguments that have type float or __fp16 794 /// are promoted to double. All other argument types are converted by 795 /// UsualUnaryConversions(). 796 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 797 QualType Ty = E->getType(); 798 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 799 800 ExprResult Res = UsualUnaryConversions(E); 801 if (Res.isInvalid()) 802 return ExprError(); 803 E = Res.get(); 804 805 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 806 // promote to double. 807 // Note that default argument promotion applies only to float (and 808 // half/fp16); it does not apply to _Float16. 809 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 810 if (BTy && (BTy->getKind() == BuiltinType::Half || 811 BTy->getKind() == BuiltinType::Float)) { 812 if (getLangOpts().OpenCL && 813 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 814 if (BTy->getKind() == BuiltinType::Half) { 815 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 816 } 817 } else { 818 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 819 } 820 } 821 822 // C++ performs lvalue-to-rvalue conversion as a default argument 823 // promotion, even on class types, but note: 824 // C++11 [conv.lval]p2: 825 // When an lvalue-to-rvalue conversion occurs in an unevaluated 826 // operand or a subexpression thereof the value contained in the 827 // referenced object is not accessed. Otherwise, if the glvalue 828 // has a class type, the conversion copy-initializes a temporary 829 // of type T from the glvalue and the result of the conversion 830 // is a prvalue for the temporary. 831 // FIXME: add some way to gate this entire thing for correctness in 832 // potentially potentially evaluated contexts. 833 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 834 ExprResult Temp = PerformCopyInitialization( 835 InitializedEntity::InitializeTemporary(E->getType()), 836 E->getExprLoc(), E); 837 if (Temp.isInvalid()) 838 return ExprError(); 839 E = Temp.get(); 840 } 841 842 return E; 843 } 844 845 /// Determine the degree of POD-ness for an expression. 846 /// Incomplete types are considered POD, since this check can be performed 847 /// when we're in an unevaluated context. 848 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 849 if (Ty->isIncompleteType()) { 850 // C++11 [expr.call]p7: 851 // After these conversions, if the argument does not have arithmetic, 852 // enumeration, pointer, pointer to member, or class type, the program 853 // is ill-formed. 854 // 855 // Since we've already performed array-to-pointer and function-to-pointer 856 // decay, the only such type in C++ is cv void. This also handles 857 // initializer lists as variadic arguments. 858 if (Ty->isVoidType()) 859 return VAK_Invalid; 860 861 if (Ty->isObjCObjectType()) 862 return VAK_Invalid; 863 return VAK_Valid; 864 } 865 866 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 867 return VAK_Invalid; 868 869 if (Ty.isCXX98PODType(Context)) 870 return VAK_Valid; 871 872 // C++11 [expr.call]p7: 873 // Passing a potentially-evaluated argument of class type (Clause 9) 874 // having a non-trivial copy constructor, a non-trivial move constructor, 875 // or a non-trivial destructor, with no corresponding parameter, 876 // is conditionally-supported with implementation-defined semantics. 877 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 878 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 879 if (!Record->hasNonTrivialCopyConstructor() && 880 !Record->hasNonTrivialMoveConstructor() && 881 !Record->hasNonTrivialDestructor()) 882 return VAK_ValidInCXX11; 883 884 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 885 return VAK_Valid; 886 887 if (Ty->isObjCObjectType()) 888 return VAK_Invalid; 889 890 if (getLangOpts().MSVCCompat) 891 return VAK_MSVCUndefined; 892 893 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 894 // permitted to reject them. We should consider doing so. 895 return VAK_Undefined; 896 } 897 898 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 899 // Don't allow one to pass an Objective-C interface to a vararg. 900 const QualType &Ty = E->getType(); 901 VarArgKind VAK = isValidVarArgType(Ty); 902 903 // Complain about passing non-POD types through varargs. 904 switch (VAK) { 905 case VAK_ValidInCXX11: 906 DiagRuntimeBehavior( 907 E->getBeginLoc(), nullptr, 908 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 909 LLVM_FALLTHROUGH; 910 case VAK_Valid: 911 if (Ty->isRecordType()) { 912 // This is unlikely to be what the user intended. If the class has a 913 // 'c_str' member function, the user probably meant to call that. 914 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 915 PDiag(diag::warn_pass_class_arg_to_vararg) 916 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 917 } 918 break; 919 920 case VAK_Undefined: 921 case VAK_MSVCUndefined: 922 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 923 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 924 << getLangOpts().CPlusPlus11 << Ty << CT); 925 break; 926 927 case VAK_Invalid: 928 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 929 Diag(E->getBeginLoc(), 930 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 931 << Ty << CT; 932 else if (Ty->isObjCObjectType()) 933 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 934 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 935 << Ty << CT); 936 else 937 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 938 << isa<InitListExpr>(E) << Ty << CT; 939 break; 940 } 941 } 942 943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 944 /// will create a trap if the resulting type is not a POD type. 945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 946 FunctionDecl *FDecl) { 947 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 948 // Strip the unbridged-cast placeholder expression off, if applicable. 949 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 950 (CT == VariadicMethod || 951 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 952 E = stripARCUnbridgedCast(E); 953 954 // Otherwise, do normal placeholder checking. 955 } else { 956 ExprResult ExprRes = CheckPlaceholderExpr(E); 957 if (ExprRes.isInvalid()) 958 return ExprError(); 959 E = ExprRes.get(); 960 } 961 } 962 963 ExprResult ExprRes = DefaultArgumentPromotion(E); 964 if (ExprRes.isInvalid()) 965 return ExprError(); 966 967 // Copy blocks to the heap. 968 if (ExprRes.get()->getType()->isBlockPointerType()) 969 maybeExtendBlockObject(ExprRes); 970 971 E = ExprRes.get(); 972 973 // Diagnostics regarding non-POD argument types are 974 // emitted along with format string checking in Sema::CheckFunctionCall(). 975 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 976 // Turn this into a trap. 977 CXXScopeSpec SS; 978 SourceLocation TemplateKWLoc; 979 UnqualifiedId Name; 980 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 981 E->getBeginLoc()); 982 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 983 /*HasTrailingLParen=*/true, 984 /*IsAddressOfOperand=*/false); 985 if (TrapFn.isInvalid()) 986 return ExprError(); 987 988 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 989 None, E->getEndLoc()); 990 if (Call.isInvalid()) 991 return ExprError(); 992 993 ExprResult Comma = 994 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 995 if (Comma.isInvalid()) 996 return ExprError(); 997 return Comma.get(); 998 } 999 1000 if (!getLangOpts().CPlusPlus && 1001 RequireCompleteType(E->getExprLoc(), E->getType(), 1002 diag::err_call_incomplete_argument)) 1003 return ExprError(); 1004 1005 return E; 1006 } 1007 1008 /// Converts an integer to complex float type. Helper function of 1009 /// UsualArithmeticConversions() 1010 /// 1011 /// \return false if the integer expression is an integer type and is 1012 /// successfully converted to the complex type. 1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1014 ExprResult &ComplexExpr, 1015 QualType IntTy, 1016 QualType ComplexTy, 1017 bool SkipCast) { 1018 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1019 if (SkipCast) return false; 1020 if (IntTy->isIntegerType()) { 1021 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1024 CK_FloatingRealToComplex); 1025 } else { 1026 assert(IntTy->isComplexIntegerType()); 1027 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1028 CK_IntegralComplexToFloatingComplex); 1029 } 1030 return false; 1031 } 1032 1033 /// Handle arithmetic conversion with complex types. Helper function of 1034 /// UsualArithmeticConversions() 1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1036 ExprResult &RHS, QualType LHSType, 1037 QualType RHSType, 1038 bool IsCompAssign) { 1039 // if we have an integer operand, the result is the complex type. 1040 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1041 /*skipCast*/false)) 1042 return LHSType; 1043 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1044 /*skipCast*/IsCompAssign)) 1045 return RHSType; 1046 1047 // This handles complex/complex, complex/float, or float/complex. 1048 // When both operands are complex, the shorter operand is converted to the 1049 // type of the longer, and that is the type of the result. This corresponds 1050 // to what is done when combining two real floating-point operands. 1051 // The fun begins when size promotion occur across type domains. 1052 // From H&S 6.3.4: When one operand is complex and the other is a real 1053 // floating-point type, the less precise type is converted, within it's 1054 // real or complex domain, to the precision of the other type. For example, 1055 // when combining a "long double" with a "double _Complex", the 1056 // "double _Complex" is promoted to "long double _Complex". 1057 1058 // Compute the rank of the two types, regardless of whether they are complex. 1059 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1060 1061 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1062 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1063 QualType LHSElementType = 1064 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1065 QualType RHSElementType = 1066 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1067 1068 QualType ResultType = S.Context.getComplexType(LHSElementType); 1069 if (Order < 0) { 1070 // Promote the precision of the LHS if not an assignment. 1071 ResultType = S.Context.getComplexType(RHSElementType); 1072 if (!IsCompAssign) { 1073 if (LHSComplexType) 1074 LHS = 1075 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1076 else 1077 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1078 } 1079 } else if (Order > 0) { 1080 // Promote the precision of the RHS. 1081 if (RHSComplexType) 1082 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1083 else 1084 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1085 } 1086 return ResultType; 1087 } 1088 1089 /// Handle arithmetic conversion from integer to float. Helper function 1090 /// of UsualArithmeticConversions() 1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1092 ExprResult &IntExpr, 1093 QualType FloatTy, QualType IntTy, 1094 bool ConvertFloat, bool ConvertInt) { 1095 if (IntTy->isIntegerType()) { 1096 if (ConvertInt) 1097 // Convert intExpr to the lhs floating point type. 1098 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1099 CK_IntegralToFloating); 1100 return FloatTy; 1101 } 1102 1103 // Convert both sides to the appropriate complex float. 1104 assert(IntTy->isComplexIntegerType()); 1105 QualType result = S.Context.getComplexType(FloatTy); 1106 1107 // _Complex int -> _Complex float 1108 if (ConvertInt) 1109 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1110 CK_IntegralComplexToFloatingComplex); 1111 1112 // float -> _Complex float 1113 if (ConvertFloat) 1114 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1115 CK_FloatingRealToComplex); 1116 1117 return result; 1118 } 1119 1120 /// Handle arithmethic conversion with floating point types. Helper 1121 /// function of UsualArithmeticConversions() 1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1123 ExprResult &RHS, QualType LHSType, 1124 QualType RHSType, bool IsCompAssign) { 1125 bool LHSFloat = LHSType->isRealFloatingType(); 1126 bool RHSFloat = RHSType->isRealFloatingType(); 1127 1128 // FIXME: Implement floating to fixed point conversion.(Bug 46268) 1129 // Reference N1169 4.1.4 (Type conversion, usual arithmetic conversions). 1130 if ((LHSType->isFixedPointType() && RHSFloat) || 1131 (LHSFloat && RHSType->isFixedPointType())) 1132 return QualType(); 1133 // If we have two real floating types, convert the smaller operand 1134 // to the bigger result. 1135 if (LHSFloat && RHSFloat) { 1136 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1137 if (order > 0) { 1138 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1139 return LHSType; 1140 } 1141 1142 assert(order < 0 && "illegal float comparison"); 1143 if (!IsCompAssign) 1144 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1145 return RHSType; 1146 } 1147 1148 if (LHSFloat) { 1149 // Half FP has to be promoted to float unless it is natively supported 1150 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1151 LHSType = S.Context.FloatTy; 1152 1153 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1154 /*ConvertFloat=*/!IsCompAssign, 1155 /*ConvertInt=*/ true); 1156 } 1157 assert(RHSFloat); 1158 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1159 /*ConvertFloat=*/ true, 1160 /*ConvertInt=*/!IsCompAssign); 1161 } 1162 1163 /// Diagnose attempts to convert between __float128 and long double if 1164 /// there is no support for such conversion. Helper function of 1165 /// UsualArithmeticConversions(). 1166 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1167 QualType RHSType) { 1168 /* No issue converting if at least one of the types is not a floating point 1169 type or the two types have the same rank. 1170 */ 1171 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1172 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1173 return false; 1174 1175 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1176 "The remaining types must be floating point types."); 1177 1178 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1179 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1180 1181 QualType LHSElemType = LHSComplex ? 1182 LHSComplex->getElementType() : LHSType; 1183 QualType RHSElemType = RHSComplex ? 1184 RHSComplex->getElementType() : RHSType; 1185 1186 // No issue if the two types have the same representation 1187 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1188 &S.Context.getFloatTypeSemantics(RHSElemType)) 1189 return false; 1190 1191 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1192 RHSElemType == S.Context.LongDoubleTy); 1193 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1194 RHSElemType == S.Context.Float128Ty); 1195 1196 // We've handled the situation where __float128 and long double have the same 1197 // representation. We allow all conversions for all possible long double types 1198 // except PPC's double double. 1199 return Float128AndLongDouble && 1200 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1201 &llvm::APFloat::PPCDoubleDouble()); 1202 } 1203 1204 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1205 1206 namespace { 1207 /// These helper callbacks are placed in an anonymous namespace to 1208 /// permit their use as function template parameters. 1209 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1210 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1211 } 1212 1213 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1214 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1215 CK_IntegralComplexCast); 1216 } 1217 } 1218 1219 /// Handle integer arithmetic conversions. Helper function of 1220 /// UsualArithmeticConversions() 1221 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1222 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1223 ExprResult &RHS, QualType LHSType, 1224 QualType RHSType, bool IsCompAssign) { 1225 // The rules for this case are in C99 6.3.1.8 1226 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1227 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1228 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1229 if (LHSSigned == RHSSigned) { 1230 // Same signedness; use the higher-ranked type 1231 if (order >= 0) { 1232 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1233 return LHSType; 1234 } else if (!IsCompAssign) 1235 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1236 return RHSType; 1237 } else if (order != (LHSSigned ? 1 : -1)) { 1238 // The unsigned type has greater than or equal rank to the 1239 // signed type, so use the unsigned type 1240 if (RHSSigned) { 1241 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1242 return LHSType; 1243 } else if (!IsCompAssign) 1244 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1245 return RHSType; 1246 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1247 // The two types are different widths; if we are here, that 1248 // means the signed type is larger than the unsigned type, so 1249 // use the signed type. 1250 if (LHSSigned) { 1251 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1252 return LHSType; 1253 } else if (!IsCompAssign) 1254 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1255 return RHSType; 1256 } else { 1257 // The signed type is higher-ranked than the unsigned type, 1258 // but isn't actually any bigger (like unsigned int and long 1259 // on most 32-bit systems). Use the unsigned type corresponding 1260 // to the signed type. 1261 QualType result = 1262 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1263 RHS = (*doRHSCast)(S, RHS.get(), result); 1264 if (!IsCompAssign) 1265 LHS = (*doLHSCast)(S, LHS.get(), result); 1266 return result; 1267 } 1268 } 1269 1270 /// Handle conversions with GCC complex int extension. Helper function 1271 /// of UsualArithmeticConversions() 1272 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1273 ExprResult &RHS, QualType LHSType, 1274 QualType RHSType, 1275 bool IsCompAssign) { 1276 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1277 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1278 1279 if (LHSComplexInt && RHSComplexInt) { 1280 QualType LHSEltType = LHSComplexInt->getElementType(); 1281 QualType RHSEltType = RHSComplexInt->getElementType(); 1282 QualType ScalarType = 1283 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1284 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1285 1286 return S.Context.getComplexType(ScalarType); 1287 } 1288 1289 if (LHSComplexInt) { 1290 QualType LHSEltType = LHSComplexInt->getElementType(); 1291 QualType ScalarType = 1292 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1293 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1294 QualType ComplexType = S.Context.getComplexType(ScalarType); 1295 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1296 CK_IntegralRealToComplex); 1297 1298 return ComplexType; 1299 } 1300 1301 assert(RHSComplexInt); 1302 1303 QualType RHSEltType = RHSComplexInt->getElementType(); 1304 QualType ScalarType = 1305 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1306 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1307 QualType ComplexType = S.Context.getComplexType(ScalarType); 1308 1309 if (!IsCompAssign) 1310 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1311 CK_IntegralRealToComplex); 1312 return ComplexType; 1313 } 1314 1315 /// Return the rank of a given fixed point or integer type. The value itself 1316 /// doesn't matter, but the values must be increasing with proper increasing 1317 /// rank as described in N1169 4.1.1. 1318 static unsigned GetFixedPointRank(QualType Ty) { 1319 const auto *BTy = Ty->getAs<BuiltinType>(); 1320 assert(BTy && "Expected a builtin type."); 1321 1322 switch (BTy->getKind()) { 1323 case BuiltinType::ShortFract: 1324 case BuiltinType::UShortFract: 1325 case BuiltinType::SatShortFract: 1326 case BuiltinType::SatUShortFract: 1327 return 1; 1328 case BuiltinType::Fract: 1329 case BuiltinType::UFract: 1330 case BuiltinType::SatFract: 1331 case BuiltinType::SatUFract: 1332 return 2; 1333 case BuiltinType::LongFract: 1334 case BuiltinType::ULongFract: 1335 case BuiltinType::SatLongFract: 1336 case BuiltinType::SatULongFract: 1337 return 3; 1338 case BuiltinType::ShortAccum: 1339 case BuiltinType::UShortAccum: 1340 case BuiltinType::SatShortAccum: 1341 case BuiltinType::SatUShortAccum: 1342 return 4; 1343 case BuiltinType::Accum: 1344 case BuiltinType::UAccum: 1345 case BuiltinType::SatAccum: 1346 case BuiltinType::SatUAccum: 1347 return 5; 1348 case BuiltinType::LongAccum: 1349 case BuiltinType::ULongAccum: 1350 case BuiltinType::SatLongAccum: 1351 case BuiltinType::SatULongAccum: 1352 return 6; 1353 default: 1354 if (BTy->isInteger()) 1355 return 0; 1356 llvm_unreachable("Unexpected fixed point or integer type"); 1357 } 1358 } 1359 1360 /// handleFixedPointConversion - Fixed point operations between fixed 1361 /// point types and integers or other fixed point types do not fall under 1362 /// usual arithmetic conversion since these conversions could result in loss 1363 /// of precsision (N1169 4.1.4). These operations should be calculated with 1364 /// the full precision of their result type (N1169 4.1.6.2.1). 1365 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1366 QualType RHSTy) { 1367 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1368 "Expected at least one of the operands to be a fixed point type"); 1369 assert((LHSTy->isFixedPointOrIntegerType() || 1370 RHSTy->isFixedPointOrIntegerType()) && 1371 "Special fixed point arithmetic operation conversions are only " 1372 "applied to ints or other fixed point types"); 1373 1374 // If one operand has signed fixed-point type and the other operand has 1375 // unsigned fixed-point type, then the unsigned fixed-point operand is 1376 // converted to its corresponding signed fixed-point type and the resulting 1377 // type is the type of the converted operand. 1378 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1379 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1380 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1381 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1382 1383 // The result type is the type with the highest rank, whereby a fixed-point 1384 // conversion rank is always greater than an integer conversion rank; if the 1385 // type of either of the operands is a saturating fixedpoint type, the result 1386 // type shall be the saturating fixed-point type corresponding to the type 1387 // with the highest rank; the resulting value is converted (taking into 1388 // account rounding and overflow) to the precision of the resulting type. 1389 // Same ranks between signed and unsigned types are resolved earlier, so both 1390 // types are either signed or both unsigned at this point. 1391 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1392 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1393 1394 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1395 1396 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1397 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1398 1399 return ResultTy; 1400 } 1401 1402 /// Check that the usual arithmetic conversions can be performed on this pair of 1403 /// expressions that might be of enumeration type. 1404 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1405 SourceLocation Loc, 1406 Sema::ArithConvKind ACK) { 1407 // C++2a [expr.arith.conv]p1: 1408 // If one operand is of enumeration type and the other operand is of a 1409 // different enumeration type or a floating-point type, this behavior is 1410 // deprecated ([depr.arith.conv.enum]). 1411 // 1412 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1413 // Eventually we will presumably reject these cases (in C++23 onwards?). 1414 QualType L = LHS->getType(), R = RHS->getType(); 1415 bool LEnum = L->isUnscopedEnumerationType(), 1416 REnum = R->isUnscopedEnumerationType(); 1417 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1418 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1419 (REnum && L->isFloatingType())) { 1420 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1421 ? diag::warn_arith_conv_enum_float_cxx20 1422 : diag::warn_arith_conv_enum_float) 1423 << LHS->getSourceRange() << RHS->getSourceRange() 1424 << (int)ACK << LEnum << L << R; 1425 } else if (!IsCompAssign && LEnum && REnum && 1426 !S.Context.hasSameUnqualifiedType(L, R)) { 1427 unsigned DiagID; 1428 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1429 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1430 // If either enumeration type is unnamed, it's less likely that the 1431 // user cares about this, but this situation is still deprecated in 1432 // C++2a. Use a different warning group. 1433 DiagID = S.getLangOpts().CPlusPlus20 1434 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1435 : diag::warn_arith_conv_mixed_anon_enum_types; 1436 } else if (ACK == Sema::ACK_Conditional) { 1437 // Conditional expressions are separated out because they have 1438 // historically had a different warning flag. 1439 DiagID = S.getLangOpts().CPlusPlus20 1440 ? diag::warn_conditional_mixed_enum_types_cxx20 1441 : diag::warn_conditional_mixed_enum_types; 1442 } else if (ACK == Sema::ACK_Comparison) { 1443 // Comparison expressions are separated out because they have 1444 // historically had a different warning flag. 1445 DiagID = S.getLangOpts().CPlusPlus20 1446 ? diag::warn_comparison_mixed_enum_types_cxx20 1447 : diag::warn_comparison_mixed_enum_types; 1448 } else { 1449 DiagID = S.getLangOpts().CPlusPlus20 1450 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1451 : diag::warn_arith_conv_mixed_enum_types; 1452 } 1453 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1454 << (int)ACK << L << R; 1455 } 1456 } 1457 1458 /// UsualArithmeticConversions - Performs various conversions that are common to 1459 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1460 /// routine returns the first non-arithmetic type found. The client is 1461 /// responsible for emitting appropriate error diagnostics. 1462 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1463 SourceLocation Loc, 1464 ArithConvKind ACK) { 1465 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1466 1467 if (ACK != ACK_CompAssign) { 1468 LHS = UsualUnaryConversions(LHS.get()); 1469 if (LHS.isInvalid()) 1470 return QualType(); 1471 } 1472 1473 RHS = UsualUnaryConversions(RHS.get()); 1474 if (RHS.isInvalid()) 1475 return QualType(); 1476 1477 // For conversion purposes, we ignore any qualifiers. 1478 // For example, "const float" and "float" are equivalent. 1479 QualType LHSType = 1480 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1481 QualType RHSType = 1482 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1483 1484 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1485 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1486 LHSType = AtomicLHS->getValueType(); 1487 1488 // If both types are identical, no conversion is needed. 1489 if (LHSType == RHSType) 1490 return LHSType; 1491 1492 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1493 // The caller can deal with this (e.g. pointer + int). 1494 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1495 return QualType(); 1496 1497 // Apply unary and bitfield promotions to the LHS's type. 1498 QualType LHSUnpromotedType = LHSType; 1499 if (LHSType->isPromotableIntegerType()) 1500 LHSType = Context.getPromotedIntegerType(LHSType); 1501 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1502 if (!LHSBitfieldPromoteTy.isNull()) 1503 LHSType = LHSBitfieldPromoteTy; 1504 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1505 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1506 1507 // If both types are identical, no conversion is needed. 1508 if (LHSType == RHSType) 1509 return LHSType; 1510 1511 // ExtInt types aren't subject to conversions between them or normal integers, 1512 // so this fails. 1513 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1514 return QualType(); 1515 1516 // At this point, we have two different arithmetic types. 1517 1518 // Diagnose attempts to convert between __float128 and long double where 1519 // such conversions currently can't be handled. 1520 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1521 return QualType(); 1522 1523 // Handle complex types first (C99 6.3.1.8p1). 1524 if (LHSType->isComplexType() || RHSType->isComplexType()) 1525 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1526 ACK == ACK_CompAssign); 1527 1528 // Now handle "real" floating types (i.e. float, double, long double). 1529 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1530 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1531 ACK == ACK_CompAssign); 1532 1533 // Handle GCC complex int extension. 1534 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1535 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1536 ACK == ACK_CompAssign); 1537 1538 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1539 return handleFixedPointConversion(*this, LHSType, RHSType); 1540 1541 // Finally, we have two differing integer types. 1542 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1543 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1544 } 1545 1546 //===----------------------------------------------------------------------===// 1547 // Semantic Analysis for various Expression Types 1548 //===----------------------------------------------------------------------===// 1549 1550 1551 ExprResult 1552 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1553 SourceLocation DefaultLoc, 1554 SourceLocation RParenLoc, 1555 Expr *ControllingExpr, 1556 ArrayRef<ParsedType> ArgTypes, 1557 ArrayRef<Expr *> ArgExprs) { 1558 unsigned NumAssocs = ArgTypes.size(); 1559 assert(NumAssocs == ArgExprs.size()); 1560 1561 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1562 for (unsigned i = 0; i < NumAssocs; ++i) { 1563 if (ArgTypes[i]) 1564 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1565 else 1566 Types[i] = nullptr; 1567 } 1568 1569 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1570 ControllingExpr, 1571 llvm::makeArrayRef(Types, NumAssocs), 1572 ArgExprs); 1573 delete [] Types; 1574 return ER; 1575 } 1576 1577 ExprResult 1578 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1579 SourceLocation DefaultLoc, 1580 SourceLocation RParenLoc, 1581 Expr *ControllingExpr, 1582 ArrayRef<TypeSourceInfo *> Types, 1583 ArrayRef<Expr *> Exprs) { 1584 unsigned NumAssocs = Types.size(); 1585 assert(NumAssocs == Exprs.size()); 1586 1587 // Decay and strip qualifiers for the controlling expression type, and handle 1588 // placeholder type replacement. See committee discussion from WG14 DR423. 1589 { 1590 EnterExpressionEvaluationContext Unevaluated( 1591 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1592 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1593 if (R.isInvalid()) 1594 return ExprError(); 1595 ControllingExpr = R.get(); 1596 } 1597 1598 // The controlling expression is an unevaluated operand, so side effects are 1599 // likely unintended. 1600 if (!inTemplateInstantiation() && 1601 ControllingExpr->HasSideEffects(Context, false)) 1602 Diag(ControllingExpr->getExprLoc(), 1603 diag::warn_side_effects_unevaluated_context); 1604 1605 bool TypeErrorFound = false, 1606 IsResultDependent = ControllingExpr->isTypeDependent(), 1607 ContainsUnexpandedParameterPack 1608 = ControllingExpr->containsUnexpandedParameterPack(); 1609 1610 for (unsigned i = 0; i < NumAssocs; ++i) { 1611 if (Exprs[i]->containsUnexpandedParameterPack()) 1612 ContainsUnexpandedParameterPack = true; 1613 1614 if (Types[i]) { 1615 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1616 ContainsUnexpandedParameterPack = true; 1617 1618 if (Types[i]->getType()->isDependentType()) { 1619 IsResultDependent = true; 1620 } else { 1621 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1622 // complete object type other than a variably modified type." 1623 unsigned D = 0; 1624 if (Types[i]->getType()->isIncompleteType()) 1625 D = diag::err_assoc_type_incomplete; 1626 else if (!Types[i]->getType()->isObjectType()) 1627 D = diag::err_assoc_type_nonobject; 1628 else if (Types[i]->getType()->isVariablyModifiedType()) 1629 D = diag::err_assoc_type_variably_modified; 1630 1631 if (D != 0) { 1632 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1633 << Types[i]->getTypeLoc().getSourceRange() 1634 << Types[i]->getType(); 1635 TypeErrorFound = true; 1636 } 1637 1638 // C11 6.5.1.1p2 "No two generic associations in the same generic 1639 // selection shall specify compatible types." 1640 for (unsigned j = i+1; j < NumAssocs; ++j) 1641 if (Types[j] && !Types[j]->getType()->isDependentType() && 1642 Context.typesAreCompatible(Types[i]->getType(), 1643 Types[j]->getType())) { 1644 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1645 diag::err_assoc_compatible_types) 1646 << Types[j]->getTypeLoc().getSourceRange() 1647 << Types[j]->getType() 1648 << Types[i]->getType(); 1649 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1650 diag::note_compat_assoc) 1651 << Types[i]->getTypeLoc().getSourceRange() 1652 << Types[i]->getType(); 1653 TypeErrorFound = true; 1654 } 1655 } 1656 } 1657 } 1658 if (TypeErrorFound) 1659 return ExprError(); 1660 1661 // If we determined that the generic selection is result-dependent, don't 1662 // try to compute the result expression. 1663 if (IsResultDependent) 1664 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1665 Exprs, DefaultLoc, RParenLoc, 1666 ContainsUnexpandedParameterPack); 1667 1668 SmallVector<unsigned, 1> CompatIndices; 1669 unsigned DefaultIndex = -1U; 1670 for (unsigned i = 0; i < NumAssocs; ++i) { 1671 if (!Types[i]) 1672 DefaultIndex = i; 1673 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1674 Types[i]->getType())) 1675 CompatIndices.push_back(i); 1676 } 1677 1678 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1679 // type compatible with at most one of the types named in its generic 1680 // association list." 1681 if (CompatIndices.size() > 1) { 1682 // We strip parens here because the controlling expression is typically 1683 // parenthesized in macro definitions. 1684 ControllingExpr = ControllingExpr->IgnoreParens(); 1685 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1686 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1687 << (unsigned)CompatIndices.size(); 1688 for (unsigned I : CompatIndices) { 1689 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1690 diag::note_compat_assoc) 1691 << Types[I]->getTypeLoc().getSourceRange() 1692 << Types[I]->getType(); 1693 } 1694 return ExprError(); 1695 } 1696 1697 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1698 // its controlling expression shall have type compatible with exactly one of 1699 // the types named in its generic association list." 1700 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1701 // We strip parens here because the controlling expression is typically 1702 // parenthesized in macro definitions. 1703 ControllingExpr = ControllingExpr->IgnoreParens(); 1704 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1705 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1706 return ExprError(); 1707 } 1708 1709 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1710 // type name that is compatible with the type of the controlling expression, 1711 // then the result expression of the generic selection is the expression 1712 // in that generic association. Otherwise, the result expression of the 1713 // generic selection is the expression in the default generic association." 1714 unsigned ResultIndex = 1715 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1716 1717 return GenericSelectionExpr::Create( 1718 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1719 ContainsUnexpandedParameterPack, ResultIndex); 1720 } 1721 1722 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1723 /// location of the token and the offset of the ud-suffix within it. 1724 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1725 unsigned Offset) { 1726 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1727 S.getLangOpts()); 1728 } 1729 1730 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1731 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1732 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1733 IdentifierInfo *UDSuffix, 1734 SourceLocation UDSuffixLoc, 1735 ArrayRef<Expr*> Args, 1736 SourceLocation LitEndLoc) { 1737 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1738 1739 QualType ArgTy[2]; 1740 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1741 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1742 if (ArgTy[ArgIdx]->isArrayType()) 1743 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1744 } 1745 1746 DeclarationName OpName = 1747 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1748 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1749 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1750 1751 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1752 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1753 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1754 /*AllowStringTemplate*/ false, 1755 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1756 return ExprError(); 1757 1758 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1759 } 1760 1761 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1762 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1763 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1764 /// multiple tokens. However, the common case is that StringToks points to one 1765 /// string. 1766 /// 1767 ExprResult 1768 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1769 assert(!StringToks.empty() && "Must have at least one string!"); 1770 1771 StringLiteralParser Literal(StringToks, PP); 1772 if (Literal.hadError) 1773 return ExprError(); 1774 1775 SmallVector<SourceLocation, 4> StringTokLocs; 1776 for (const Token &Tok : StringToks) 1777 StringTokLocs.push_back(Tok.getLocation()); 1778 1779 QualType CharTy = Context.CharTy; 1780 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1781 if (Literal.isWide()) { 1782 CharTy = Context.getWideCharType(); 1783 Kind = StringLiteral::Wide; 1784 } else if (Literal.isUTF8()) { 1785 if (getLangOpts().Char8) 1786 CharTy = Context.Char8Ty; 1787 Kind = StringLiteral::UTF8; 1788 } else if (Literal.isUTF16()) { 1789 CharTy = Context.Char16Ty; 1790 Kind = StringLiteral::UTF16; 1791 } else if (Literal.isUTF32()) { 1792 CharTy = Context.Char32Ty; 1793 Kind = StringLiteral::UTF32; 1794 } else if (Literal.isPascal()) { 1795 CharTy = Context.UnsignedCharTy; 1796 } 1797 1798 // Warn on initializing an array of char from a u8 string literal; this 1799 // becomes ill-formed in C++2a. 1800 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1801 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1802 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1803 1804 // Create removals for all 'u8' prefixes in the string literal(s). This 1805 // ensures C++2a compatibility (but may change the program behavior when 1806 // built by non-Clang compilers for which the execution character set is 1807 // not always UTF-8). 1808 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1809 SourceLocation RemovalDiagLoc; 1810 for (const Token &Tok : StringToks) { 1811 if (Tok.getKind() == tok::utf8_string_literal) { 1812 if (RemovalDiagLoc.isInvalid()) 1813 RemovalDiagLoc = Tok.getLocation(); 1814 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1815 Tok.getLocation(), 1816 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1817 getSourceManager(), getLangOpts()))); 1818 } 1819 } 1820 Diag(RemovalDiagLoc, RemovalDiag); 1821 } 1822 1823 QualType StrTy = 1824 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1825 1826 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1827 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1828 Kind, Literal.Pascal, StrTy, 1829 &StringTokLocs[0], 1830 StringTokLocs.size()); 1831 if (Literal.getUDSuffix().empty()) 1832 return Lit; 1833 1834 // We're building a user-defined literal. 1835 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1836 SourceLocation UDSuffixLoc = 1837 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1838 Literal.getUDSuffixOffset()); 1839 1840 // Make sure we're allowed user-defined literals here. 1841 if (!UDLScope) 1842 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1843 1844 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1845 // operator "" X (str, len) 1846 QualType SizeType = Context.getSizeType(); 1847 1848 DeclarationName OpName = 1849 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1850 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1851 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1852 1853 QualType ArgTy[] = { 1854 Context.getArrayDecayedType(StrTy), SizeType 1855 }; 1856 1857 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1858 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1859 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1860 /*AllowStringTemplate*/ true, 1861 /*DiagnoseMissing*/ true)) { 1862 1863 case LOLR_Cooked: { 1864 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1865 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1866 StringTokLocs[0]); 1867 Expr *Args[] = { Lit, LenArg }; 1868 1869 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1870 } 1871 1872 case LOLR_StringTemplate: { 1873 TemplateArgumentListInfo ExplicitArgs; 1874 1875 unsigned CharBits = Context.getIntWidth(CharTy); 1876 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1877 llvm::APSInt Value(CharBits, CharIsUnsigned); 1878 1879 TemplateArgument TypeArg(CharTy); 1880 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1881 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1882 1883 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1884 Value = Lit->getCodeUnit(I); 1885 TemplateArgument Arg(Context, Value, CharTy); 1886 TemplateArgumentLocInfo ArgInfo; 1887 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1888 } 1889 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1890 &ExplicitArgs); 1891 } 1892 case LOLR_Raw: 1893 case LOLR_Template: 1894 case LOLR_ErrorNoDiagnostic: 1895 llvm_unreachable("unexpected literal operator lookup result"); 1896 case LOLR_Error: 1897 return ExprError(); 1898 } 1899 llvm_unreachable("unexpected literal operator lookup result"); 1900 } 1901 1902 DeclRefExpr * 1903 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1904 SourceLocation Loc, 1905 const CXXScopeSpec *SS) { 1906 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1907 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1908 } 1909 1910 DeclRefExpr * 1911 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1912 const DeclarationNameInfo &NameInfo, 1913 const CXXScopeSpec *SS, NamedDecl *FoundD, 1914 SourceLocation TemplateKWLoc, 1915 const TemplateArgumentListInfo *TemplateArgs) { 1916 NestedNameSpecifierLoc NNS = 1917 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1918 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1919 TemplateArgs); 1920 } 1921 1922 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1923 // A declaration named in an unevaluated operand never constitutes an odr-use. 1924 if (isUnevaluatedContext()) 1925 return NOUR_Unevaluated; 1926 1927 // C++2a [basic.def.odr]p4: 1928 // A variable x whose name appears as a potentially-evaluated expression e 1929 // is odr-used by e unless [...] x is a reference that is usable in 1930 // constant expressions. 1931 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1932 if (VD->getType()->isReferenceType() && 1933 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1934 VD->isUsableInConstantExpressions(Context)) 1935 return NOUR_Constant; 1936 } 1937 1938 // All remaining non-variable cases constitute an odr-use. For variables, we 1939 // need to wait and see how the expression is used. 1940 return NOUR_None; 1941 } 1942 1943 /// BuildDeclRefExpr - Build an expression that references a 1944 /// declaration that does not require a closure capture. 1945 DeclRefExpr * 1946 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1947 const DeclarationNameInfo &NameInfo, 1948 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1949 SourceLocation TemplateKWLoc, 1950 const TemplateArgumentListInfo *TemplateArgs) { 1951 bool RefersToCapturedVariable = 1952 isa<VarDecl>(D) && 1953 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1954 1955 DeclRefExpr *E = DeclRefExpr::Create( 1956 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1957 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1958 MarkDeclRefReferenced(E); 1959 1960 // C++ [except.spec]p17: 1961 // An exception-specification is considered to be needed when: 1962 // - in an expression, the function is the unique lookup result or 1963 // the selected member of a set of overloaded functions. 1964 // 1965 // We delay doing this until after we've built the function reference and 1966 // marked it as used so that: 1967 // a) if the function is defaulted, we get errors from defining it before / 1968 // instead of errors from computing its exception specification, and 1969 // b) if the function is a defaulted comparison, we can use the body we 1970 // build when defining it as input to the exception specification 1971 // computation rather than computing a new body. 1972 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1973 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1974 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1975 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1976 } 1977 } 1978 1979 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1980 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1981 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1982 getCurFunction()->recordUseOfWeak(E); 1983 1984 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1985 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1986 FD = IFD->getAnonField(); 1987 if (FD) { 1988 UnusedPrivateFields.remove(FD); 1989 // Just in case we're building an illegal pointer-to-member. 1990 if (FD->isBitField()) 1991 E->setObjectKind(OK_BitField); 1992 } 1993 1994 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1995 // designates a bit-field. 1996 if (auto *BD = dyn_cast<BindingDecl>(D)) 1997 if (auto *BE = BD->getBinding()) 1998 E->setObjectKind(BE->getObjectKind()); 1999 2000 return E; 2001 } 2002 2003 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2004 /// possibly a list of template arguments. 2005 /// 2006 /// If this produces template arguments, it is permitted to call 2007 /// DecomposeTemplateName. 2008 /// 2009 /// This actually loses a lot of source location information for 2010 /// non-standard name kinds; we should consider preserving that in 2011 /// some way. 2012 void 2013 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2014 TemplateArgumentListInfo &Buffer, 2015 DeclarationNameInfo &NameInfo, 2016 const TemplateArgumentListInfo *&TemplateArgs) { 2017 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2018 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2019 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2020 2021 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2022 Id.TemplateId->NumArgs); 2023 translateTemplateArguments(TemplateArgsPtr, Buffer); 2024 2025 TemplateName TName = Id.TemplateId->Template.get(); 2026 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2027 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2028 TemplateArgs = &Buffer; 2029 } else { 2030 NameInfo = GetNameFromUnqualifiedId(Id); 2031 TemplateArgs = nullptr; 2032 } 2033 } 2034 2035 static void emitEmptyLookupTypoDiagnostic( 2036 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2037 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2038 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2039 DeclContext *Ctx = 2040 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2041 if (!TC) { 2042 // Emit a special diagnostic for failed member lookups. 2043 // FIXME: computing the declaration context might fail here (?) 2044 if (Ctx) 2045 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2046 << SS.getRange(); 2047 else 2048 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2049 return; 2050 } 2051 2052 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2053 bool DroppedSpecifier = 2054 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2055 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2056 ? diag::note_implicit_param_decl 2057 : diag::note_previous_decl; 2058 if (!Ctx) 2059 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2060 SemaRef.PDiag(NoteID)); 2061 else 2062 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2063 << Typo << Ctx << DroppedSpecifier 2064 << SS.getRange(), 2065 SemaRef.PDiag(NoteID)); 2066 } 2067 2068 /// Diagnose an empty lookup. 2069 /// 2070 /// \return false if new lookup candidates were found 2071 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2072 CorrectionCandidateCallback &CCC, 2073 TemplateArgumentListInfo *ExplicitTemplateArgs, 2074 ArrayRef<Expr *> Args, TypoExpr **Out) { 2075 DeclarationName Name = R.getLookupName(); 2076 2077 unsigned diagnostic = diag::err_undeclared_var_use; 2078 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2079 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2080 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2081 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2082 diagnostic = diag::err_undeclared_use; 2083 diagnostic_suggest = diag::err_undeclared_use_suggest; 2084 } 2085 2086 // If the original lookup was an unqualified lookup, fake an 2087 // unqualified lookup. This is useful when (for example) the 2088 // original lookup would not have found something because it was a 2089 // dependent name. 2090 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2091 while (DC) { 2092 if (isa<CXXRecordDecl>(DC)) { 2093 LookupQualifiedName(R, DC); 2094 2095 if (!R.empty()) { 2096 // Don't give errors about ambiguities in this lookup. 2097 R.suppressDiagnostics(); 2098 2099 // During a default argument instantiation the CurContext points 2100 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2101 // function parameter list, hence add an explicit check. 2102 bool isDefaultArgument = 2103 !CodeSynthesisContexts.empty() && 2104 CodeSynthesisContexts.back().Kind == 2105 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2106 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2107 bool isInstance = CurMethod && 2108 CurMethod->isInstance() && 2109 DC == CurMethod->getParent() && !isDefaultArgument; 2110 2111 // Give a code modification hint to insert 'this->'. 2112 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2113 // Actually quite difficult! 2114 if (getLangOpts().MSVCCompat) 2115 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2116 if (isInstance) { 2117 Diag(R.getNameLoc(), diagnostic) << Name 2118 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2119 CheckCXXThisCapture(R.getNameLoc()); 2120 } else { 2121 Diag(R.getNameLoc(), diagnostic) << Name; 2122 } 2123 2124 // Do we really want to note all of these? 2125 for (NamedDecl *D : R) 2126 Diag(D->getLocation(), diag::note_dependent_var_use); 2127 2128 // Return true if we are inside a default argument instantiation 2129 // and the found name refers to an instance member function, otherwise 2130 // the function calling DiagnoseEmptyLookup will try to create an 2131 // implicit member call and this is wrong for default argument. 2132 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2133 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2134 return true; 2135 } 2136 2137 // Tell the callee to try to recover. 2138 return false; 2139 } 2140 2141 R.clear(); 2142 } 2143 2144 DC = DC->getLookupParent(); 2145 } 2146 2147 // We didn't find anything, so try to correct for a typo. 2148 TypoCorrection Corrected; 2149 if (S && Out) { 2150 SourceLocation TypoLoc = R.getNameLoc(); 2151 assert(!ExplicitTemplateArgs && 2152 "Diagnosing an empty lookup with explicit template args!"); 2153 *Out = CorrectTypoDelayed( 2154 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2155 [=](const TypoCorrection &TC) { 2156 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2157 diagnostic, diagnostic_suggest); 2158 }, 2159 nullptr, CTK_ErrorRecovery); 2160 if (*Out) 2161 return true; 2162 } else if (S && 2163 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2164 S, &SS, CCC, CTK_ErrorRecovery))) { 2165 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2166 bool DroppedSpecifier = 2167 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2168 R.setLookupName(Corrected.getCorrection()); 2169 2170 bool AcceptableWithRecovery = false; 2171 bool AcceptableWithoutRecovery = false; 2172 NamedDecl *ND = Corrected.getFoundDecl(); 2173 if (ND) { 2174 if (Corrected.isOverloaded()) { 2175 OverloadCandidateSet OCS(R.getNameLoc(), 2176 OverloadCandidateSet::CSK_Normal); 2177 OverloadCandidateSet::iterator Best; 2178 for (NamedDecl *CD : Corrected) { 2179 if (FunctionTemplateDecl *FTD = 2180 dyn_cast<FunctionTemplateDecl>(CD)) 2181 AddTemplateOverloadCandidate( 2182 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2183 Args, OCS); 2184 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2185 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2186 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2187 Args, OCS); 2188 } 2189 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2190 case OR_Success: 2191 ND = Best->FoundDecl; 2192 Corrected.setCorrectionDecl(ND); 2193 break; 2194 default: 2195 // FIXME: Arbitrarily pick the first declaration for the note. 2196 Corrected.setCorrectionDecl(ND); 2197 break; 2198 } 2199 } 2200 R.addDecl(ND); 2201 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2202 CXXRecordDecl *Record = nullptr; 2203 if (Corrected.getCorrectionSpecifier()) { 2204 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2205 Record = Ty->getAsCXXRecordDecl(); 2206 } 2207 if (!Record) 2208 Record = cast<CXXRecordDecl>( 2209 ND->getDeclContext()->getRedeclContext()); 2210 R.setNamingClass(Record); 2211 } 2212 2213 auto *UnderlyingND = ND->getUnderlyingDecl(); 2214 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2215 isa<FunctionTemplateDecl>(UnderlyingND); 2216 // FIXME: If we ended up with a typo for a type name or 2217 // Objective-C class name, we're in trouble because the parser 2218 // is in the wrong place to recover. Suggest the typo 2219 // correction, but don't make it a fix-it since we're not going 2220 // to recover well anyway. 2221 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2222 getAsTypeTemplateDecl(UnderlyingND) || 2223 isa<ObjCInterfaceDecl>(UnderlyingND); 2224 } else { 2225 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2226 // because we aren't able to recover. 2227 AcceptableWithoutRecovery = true; 2228 } 2229 2230 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2231 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2232 ? diag::note_implicit_param_decl 2233 : diag::note_previous_decl; 2234 if (SS.isEmpty()) 2235 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2236 PDiag(NoteID), AcceptableWithRecovery); 2237 else 2238 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2239 << Name << computeDeclContext(SS, false) 2240 << DroppedSpecifier << SS.getRange(), 2241 PDiag(NoteID), AcceptableWithRecovery); 2242 2243 // Tell the callee whether to try to recover. 2244 return !AcceptableWithRecovery; 2245 } 2246 } 2247 R.clear(); 2248 2249 // Emit a special diagnostic for failed member lookups. 2250 // FIXME: computing the declaration context might fail here (?) 2251 if (!SS.isEmpty()) { 2252 Diag(R.getNameLoc(), diag::err_no_member) 2253 << Name << computeDeclContext(SS, false) 2254 << SS.getRange(); 2255 return true; 2256 } 2257 2258 // Give up, we can't recover. 2259 Diag(R.getNameLoc(), diagnostic) << Name; 2260 return true; 2261 } 2262 2263 /// In Microsoft mode, if we are inside a template class whose parent class has 2264 /// dependent base classes, and we can't resolve an unqualified identifier, then 2265 /// assume the identifier is a member of a dependent base class. We can only 2266 /// recover successfully in static methods, instance methods, and other contexts 2267 /// where 'this' is available. This doesn't precisely match MSVC's 2268 /// instantiation model, but it's close enough. 2269 static Expr * 2270 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2271 DeclarationNameInfo &NameInfo, 2272 SourceLocation TemplateKWLoc, 2273 const TemplateArgumentListInfo *TemplateArgs) { 2274 // Only try to recover from lookup into dependent bases in static methods or 2275 // contexts where 'this' is available. 2276 QualType ThisType = S.getCurrentThisType(); 2277 const CXXRecordDecl *RD = nullptr; 2278 if (!ThisType.isNull()) 2279 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2280 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2281 RD = MD->getParent(); 2282 if (!RD || !RD->hasAnyDependentBases()) 2283 return nullptr; 2284 2285 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2286 // is available, suggest inserting 'this->' as a fixit. 2287 SourceLocation Loc = NameInfo.getLoc(); 2288 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2289 DB << NameInfo.getName() << RD; 2290 2291 if (!ThisType.isNull()) { 2292 DB << FixItHint::CreateInsertion(Loc, "this->"); 2293 return CXXDependentScopeMemberExpr::Create( 2294 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2295 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2296 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2297 } 2298 2299 // Synthesize a fake NNS that points to the derived class. This will 2300 // perform name lookup during template instantiation. 2301 CXXScopeSpec SS; 2302 auto *NNS = 2303 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2304 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2305 return DependentScopeDeclRefExpr::Create( 2306 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2307 TemplateArgs); 2308 } 2309 2310 ExprResult 2311 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2312 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2313 bool HasTrailingLParen, bool IsAddressOfOperand, 2314 CorrectionCandidateCallback *CCC, 2315 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2316 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2317 "cannot be direct & operand and have a trailing lparen"); 2318 if (SS.isInvalid()) 2319 return ExprError(); 2320 2321 TemplateArgumentListInfo TemplateArgsBuffer; 2322 2323 // Decompose the UnqualifiedId into the following data. 2324 DeclarationNameInfo NameInfo; 2325 const TemplateArgumentListInfo *TemplateArgs; 2326 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2327 2328 DeclarationName Name = NameInfo.getName(); 2329 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2330 SourceLocation NameLoc = NameInfo.getLoc(); 2331 2332 if (II && II->isEditorPlaceholder()) { 2333 // FIXME: When typed placeholders are supported we can create a typed 2334 // placeholder expression node. 2335 return ExprError(); 2336 } 2337 2338 // C++ [temp.dep.expr]p3: 2339 // An id-expression is type-dependent if it contains: 2340 // -- an identifier that was declared with a dependent type, 2341 // (note: handled after lookup) 2342 // -- a template-id that is dependent, 2343 // (note: handled in BuildTemplateIdExpr) 2344 // -- a conversion-function-id that specifies a dependent type, 2345 // -- a nested-name-specifier that contains a class-name that 2346 // names a dependent type. 2347 // Determine whether this is a member of an unknown specialization; 2348 // we need to handle these differently. 2349 bool DependentID = false; 2350 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2351 Name.getCXXNameType()->isDependentType()) { 2352 DependentID = true; 2353 } else if (SS.isSet()) { 2354 if (DeclContext *DC = computeDeclContext(SS, false)) { 2355 if (RequireCompleteDeclContext(SS, DC)) 2356 return ExprError(); 2357 } else { 2358 DependentID = true; 2359 } 2360 } 2361 2362 if (DependentID) 2363 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2364 IsAddressOfOperand, TemplateArgs); 2365 2366 // Perform the required lookup. 2367 LookupResult R(*this, NameInfo, 2368 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2369 ? LookupObjCImplicitSelfParam 2370 : LookupOrdinaryName); 2371 if (TemplateKWLoc.isValid() || TemplateArgs) { 2372 // Lookup the template name again to correctly establish the context in 2373 // which it was found. This is really unfortunate as we already did the 2374 // lookup to determine that it was a template name in the first place. If 2375 // this becomes a performance hit, we can work harder to preserve those 2376 // results until we get here but it's likely not worth it. 2377 bool MemberOfUnknownSpecialization; 2378 AssumedTemplateKind AssumedTemplate; 2379 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2380 MemberOfUnknownSpecialization, TemplateKWLoc, 2381 &AssumedTemplate)) 2382 return ExprError(); 2383 2384 if (MemberOfUnknownSpecialization || 2385 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2386 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2387 IsAddressOfOperand, TemplateArgs); 2388 } else { 2389 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2390 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2391 2392 // If the result might be in a dependent base class, this is a dependent 2393 // id-expression. 2394 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2395 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2396 IsAddressOfOperand, TemplateArgs); 2397 2398 // If this reference is in an Objective-C method, then we need to do 2399 // some special Objective-C lookup, too. 2400 if (IvarLookupFollowUp) { 2401 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2402 if (E.isInvalid()) 2403 return ExprError(); 2404 2405 if (Expr *Ex = E.getAs<Expr>()) 2406 return Ex; 2407 } 2408 } 2409 2410 if (R.isAmbiguous()) 2411 return ExprError(); 2412 2413 // This could be an implicitly declared function reference (legal in C90, 2414 // extension in C99, forbidden in C++). 2415 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2416 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2417 if (D) R.addDecl(D); 2418 } 2419 2420 // Determine whether this name might be a candidate for 2421 // argument-dependent lookup. 2422 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2423 2424 if (R.empty() && !ADL) { 2425 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2426 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2427 TemplateKWLoc, TemplateArgs)) 2428 return E; 2429 } 2430 2431 // Don't diagnose an empty lookup for inline assembly. 2432 if (IsInlineAsmIdentifier) 2433 return ExprError(); 2434 2435 // If this name wasn't predeclared and if this is not a function 2436 // call, diagnose the problem. 2437 TypoExpr *TE = nullptr; 2438 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2439 : nullptr); 2440 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2441 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2442 "Typo correction callback misconfigured"); 2443 if (CCC) { 2444 // Make sure the callback knows what the typo being diagnosed is. 2445 CCC->setTypoName(II); 2446 if (SS.isValid()) 2447 CCC->setTypoNNS(SS.getScopeRep()); 2448 } 2449 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2450 // a template name, but we happen to have always already looked up the name 2451 // before we get here if it must be a template name. 2452 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2453 None, &TE)) { 2454 if (TE && KeywordReplacement) { 2455 auto &State = getTypoExprState(TE); 2456 auto BestTC = State.Consumer->getNextCorrection(); 2457 if (BestTC.isKeyword()) { 2458 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2459 if (State.DiagHandler) 2460 State.DiagHandler(BestTC); 2461 KeywordReplacement->startToken(); 2462 KeywordReplacement->setKind(II->getTokenID()); 2463 KeywordReplacement->setIdentifierInfo(II); 2464 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2465 // Clean up the state associated with the TypoExpr, since it has 2466 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2467 clearDelayedTypo(TE); 2468 // Signal that a correction to a keyword was performed by returning a 2469 // valid-but-null ExprResult. 2470 return (Expr*)nullptr; 2471 } 2472 State.Consumer->resetCorrectionStream(); 2473 } 2474 return TE ? TE : ExprError(); 2475 } 2476 2477 assert(!R.empty() && 2478 "DiagnoseEmptyLookup returned false but added no results"); 2479 2480 // If we found an Objective-C instance variable, let 2481 // LookupInObjCMethod build the appropriate expression to 2482 // reference the ivar. 2483 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2484 R.clear(); 2485 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2486 // In a hopelessly buggy code, Objective-C instance variable 2487 // lookup fails and no expression will be built to reference it. 2488 if (!E.isInvalid() && !E.get()) 2489 return ExprError(); 2490 return E; 2491 } 2492 } 2493 2494 // This is guaranteed from this point on. 2495 assert(!R.empty() || ADL); 2496 2497 // Check whether this might be a C++ implicit instance member access. 2498 // C++ [class.mfct.non-static]p3: 2499 // When an id-expression that is not part of a class member access 2500 // syntax and not used to form a pointer to member is used in the 2501 // body of a non-static member function of class X, if name lookup 2502 // resolves the name in the id-expression to a non-static non-type 2503 // member of some class C, the id-expression is transformed into a 2504 // class member access expression using (*this) as the 2505 // postfix-expression to the left of the . operator. 2506 // 2507 // But we don't actually need to do this for '&' operands if R 2508 // resolved to a function or overloaded function set, because the 2509 // expression is ill-formed if it actually works out to be a 2510 // non-static member function: 2511 // 2512 // C++ [expr.ref]p4: 2513 // Otherwise, if E1.E2 refers to a non-static member function. . . 2514 // [t]he expression can be used only as the left-hand operand of a 2515 // member function call. 2516 // 2517 // There are other safeguards against such uses, but it's important 2518 // to get this right here so that we don't end up making a 2519 // spuriously dependent expression if we're inside a dependent 2520 // instance method. 2521 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2522 bool MightBeImplicitMember; 2523 if (!IsAddressOfOperand) 2524 MightBeImplicitMember = true; 2525 else if (!SS.isEmpty()) 2526 MightBeImplicitMember = false; 2527 else if (R.isOverloadedResult()) 2528 MightBeImplicitMember = false; 2529 else if (R.isUnresolvableResult()) 2530 MightBeImplicitMember = true; 2531 else 2532 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2533 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2534 isa<MSPropertyDecl>(R.getFoundDecl()); 2535 2536 if (MightBeImplicitMember) 2537 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2538 R, TemplateArgs, S); 2539 } 2540 2541 if (TemplateArgs || TemplateKWLoc.isValid()) { 2542 2543 // In C++1y, if this is a variable template id, then check it 2544 // in BuildTemplateIdExpr(). 2545 // The single lookup result must be a variable template declaration. 2546 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2547 Id.TemplateId->Kind == TNK_Var_template) { 2548 assert(R.getAsSingle<VarTemplateDecl>() && 2549 "There should only be one declaration found."); 2550 } 2551 2552 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2553 } 2554 2555 return BuildDeclarationNameExpr(SS, R, ADL); 2556 } 2557 2558 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2559 /// declaration name, generally during template instantiation. 2560 /// There's a large number of things which don't need to be done along 2561 /// this path. 2562 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2563 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2564 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2565 DeclContext *DC = computeDeclContext(SS, false); 2566 if (!DC) 2567 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2568 NameInfo, /*TemplateArgs=*/nullptr); 2569 2570 if (RequireCompleteDeclContext(SS, DC)) 2571 return ExprError(); 2572 2573 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2574 LookupQualifiedName(R, DC); 2575 2576 if (R.isAmbiguous()) 2577 return ExprError(); 2578 2579 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2580 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2581 NameInfo, /*TemplateArgs=*/nullptr); 2582 2583 if (R.empty()) { 2584 Diag(NameInfo.getLoc(), diag::err_no_member) 2585 << NameInfo.getName() << DC << SS.getRange(); 2586 return ExprError(); 2587 } 2588 2589 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2590 // Diagnose a missing typename if this resolved unambiguously to a type in 2591 // a dependent context. If we can recover with a type, downgrade this to 2592 // a warning in Microsoft compatibility mode. 2593 unsigned DiagID = diag::err_typename_missing; 2594 if (RecoveryTSI && getLangOpts().MSVCCompat) 2595 DiagID = diag::ext_typename_missing; 2596 SourceLocation Loc = SS.getBeginLoc(); 2597 auto D = Diag(Loc, DiagID); 2598 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2599 << SourceRange(Loc, NameInfo.getEndLoc()); 2600 2601 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2602 // context. 2603 if (!RecoveryTSI) 2604 return ExprError(); 2605 2606 // Only issue the fixit if we're prepared to recover. 2607 D << FixItHint::CreateInsertion(Loc, "typename "); 2608 2609 // Recover by pretending this was an elaborated type. 2610 QualType Ty = Context.getTypeDeclType(TD); 2611 TypeLocBuilder TLB; 2612 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2613 2614 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2615 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2616 QTL.setElaboratedKeywordLoc(SourceLocation()); 2617 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2618 2619 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2620 2621 return ExprEmpty(); 2622 } 2623 2624 // Defend against this resolving to an implicit member access. We usually 2625 // won't get here if this might be a legitimate a class member (we end up in 2626 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2627 // a pointer-to-member or in an unevaluated context in C++11. 2628 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2629 return BuildPossibleImplicitMemberExpr(SS, 2630 /*TemplateKWLoc=*/SourceLocation(), 2631 R, /*TemplateArgs=*/nullptr, S); 2632 2633 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2634 } 2635 2636 /// The parser has read a name in, and Sema has detected that we're currently 2637 /// inside an ObjC method. Perform some additional checks and determine if we 2638 /// should form a reference to an ivar. 2639 /// 2640 /// Ideally, most of this would be done by lookup, but there's 2641 /// actually quite a lot of extra work involved. 2642 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2643 IdentifierInfo *II) { 2644 SourceLocation Loc = Lookup.getNameLoc(); 2645 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2646 2647 // Check for error condition which is already reported. 2648 if (!CurMethod) 2649 return DeclResult(true); 2650 2651 // There are two cases to handle here. 1) scoped lookup could have failed, 2652 // in which case we should look for an ivar. 2) scoped lookup could have 2653 // found a decl, but that decl is outside the current instance method (i.e. 2654 // a global variable). In these two cases, we do a lookup for an ivar with 2655 // this name, if the lookup sucedes, we replace it our current decl. 2656 2657 // If we're in a class method, we don't normally want to look for 2658 // ivars. But if we don't find anything else, and there's an 2659 // ivar, that's an error. 2660 bool IsClassMethod = CurMethod->isClassMethod(); 2661 2662 bool LookForIvars; 2663 if (Lookup.empty()) 2664 LookForIvars = true; 2665 else if (IsClassMethod) 2666 LookForIvars = false; 2667 else 2668 LookForIvars = (Lookup.isSingleResult() && 2669 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2670 ObjCInterfaceDecl *IFace = nullptr; 2671 if (LookForIvars) { 2672 IFace = CurMethod->getClassInterface(); 2673 ObjCInterfaceDecl *ClassDeclared; 2674 ObjCIvarDecl *IV = nullptr; 2675 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2676 // Diagnose using an ivar in a class method. 2677 if (IsClassMethod) { 2678 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2679 return DeclResult(true); 2680 } 2681 2682 // Diagnose the use of an ivar outside of the declaring class. 2683 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2684 !declaresSameEntity(ClassDeclared, IFace) && 2685 !getLangOpts().DebuggerSupport) 2686 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2687 2688 // Success. 2689 return IV; 2690 } 2691 } else if (CurMethod->isInstanceMethod()) { 2692 // We should warn if a local variable hides an ivar. 2693 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2694 ObjCInterfaceDecl *ClassDeclared; 2695 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2696 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2697 declaresSameEntity(IFace, ClassDeclared)) 2698 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2699 } 2700 } 2701 } else if (Lookup.isSingleResult() && 2702 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2703 // If accessing a stand-alone ivar in a class method, this is an error. 2704 if (const ObjCIvarDecl *IV = 2705 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2706 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2707 return DeclResult(true); 2708 } 2709 } 2710 2711 // Didn't encounter an error, didn't find an ivar. 2712 return DeclResult(false); 2713 } 2714 2715 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2716 ObjCIvarDecl *IV) { 2717 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2718 assert(CurMethod && CurMethod->isInstanceMethod() && 2719 "should not reference ivar from this context"); 2720 2721 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2722 assert(IFace && "should not reference ivar from this context"); 2723 2724 // If we're referencing an invalid decl, just return this as a silent 2725 // error node. The error diagnostic was already emitted on the decl. 2726 if (IV->isInvalidDecl()) 2727 return ExprError(); 2728 2729 // Check if referencing a field with __attribute__((deprecated)). 2730 if (DiagnoseUseOfDecl(IV, Loc)) 2731 return ExprError(); 2732 2733 // FIXME: This should use a new expr for a direct reference, don't 2734 // turn this into Self->ivar, just return a BareIVarExpr or something. 2735 IdentifierInfo &II = Context.Idents.get("self"); 2736 UnqualifiedId SelfName; 2737 SelfName.setIdentifier(&II, SourceLocation()); 2738 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2739 CXXScopeSpec SelfScopeSpec; 2740 SourceLocation TemplateKWLoc; 2741 ExprResult SelfExpr = 2742 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2743 /*HasTrailingLParen=*/false, 2744 /*IsAddressOfOperand=*/false); 2745 if (SelfExpr.isInvalid()) 2746 return ExprError(); 2747 2748 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2749 if (SelfExpr.isInvalid()) 2750 return ExprError(); 2751 2752 MarkAnyDeclReferenced(Loc, IV, true); 2753 2754 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2755 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2756 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2757 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2758 2759 ObjCIvarRefExpr *Result = new (Context) 2760 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2761 IV->getLocation(), SelfExpr.get(), true, true); 2762 2763 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2764 if (!isUnevaluatedContext() && 2765 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2766 getCurFunction()->recordUseOfWeak(Result); 2767 } 2768 if (getLangOpts().ObjCAutoRefCount) 2769 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2770 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2771 2772 return Result; 2773 } 2774 2775 /// The parser has read a name in, and Sema has detected that we're currently 2776 /// inside an ObjC method. Perform some additional checks and determine if we 2777 /// should form a reference to an ivar. If so, build an expression referencing 2778 /// that ivar. 2779 ExprResult 2780 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2781 IdentifierInfo *II, bool AllowBuiltinCreation) { 2782 // FIXME: Integrate this lookup step into LookupParsedName. 2783 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2784 if (Ivar.isInvalid()) 2785 return ExprError(); 2786 if (Ivar.isUsable()) 2787 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2788 cast<ObjCIvarDecl>(Ivar.get())); 2789 2790 if (Lookup.empty() && II && AllowBuiltinCreation) 2791 LookupBuiltin(Lookup); 2792 2793 // Sentinel value saying that we didn't do anything special. 2794 return ExprResult(false); 2795 } 2796 2797 /// Cast a base object to a member's actual type. 2798 /// 2799 /// Logically this happens in three phases: 2800 /// 2801 /// * First we cast from the base type to the naming class. 2802 /// The naming class is the class into which we were looking 2803 /// when we found the member; it's the qualifier type if a 2804 /// qualifier was provided, and otherwise it's the base type. 2805 /// 2806 /// * Next we cast from the naming class to the declaring class. 2807 /// If the member we found was brought into a class's scope by 2808 /// a using declaration, this is that class; otherwise it's 2809 /// the class declaring the member. 2810 /// 2811 /// * Finally we cast from the declaring class to the "true" 2812 /// declaring class of the member. This conversion does not 2813 /// obey access control. 2814 ExprResult 2815 Sema::PerformObjectMemberConversion(Expr *From, 2816 NestedNameSpecifier *Qualifier, 2817 NamedDecl *FoundDecl, 2818 NamedDecl *Member) { 2819 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2820 if (!RD) 2821 return From; 2822 2823 QualType DestRecordType; 2824 QualType DestType; 2825 QualType FromRecordType; 2826 QualType FromType = From->getType(); 2827 bool PointerConversions = false; 2828 if (isa<FieldDecl>(Member)) { 2829 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2830 auto FromPtrType = FromType->getAs<PointerType>(); 2831 DestRecordType = Context.getAddrSpaceQualType( 2832 DestRecordType, FromPtrType 2833 ? FromType->getPointeeType().getAddressSpace() 2834 : FromType.getAddressSpace()); 2835 2836 if (FromPtrType) { 2837 DestType = Context.getPointerType(DestRecordType); 2838 FromRecordType = FromPtrType->getPointeeType(); 2839 PointerConversions = true; 2840 } else { 2841 DestType = DestRecordType; 2842 FromRecordType = FromType; 2843 } 2844 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2845 if (Method->isStatic()) 2846 return From; 2847 2848 DestType = Method->getThisType(); 2849 DestRecordType = DestType->getPointeeType(); 2850 2851 if (FromType->getAs<PointerType>()) { 2852 FromRecordType = FromType->getPointeeType(); 2853 PointerConversions = true; 2854 } else { 2855 FromRecordType = FromType; 2856 DestType = DestRecordType; 2857 } 2858 2859 LangAS FromAS = FromRecordType.getAddressSpace(); 2860 LangAS DestAS = DestRecordType.getAddressSpace(); 2861 if (FromAS != DestAS) { 2862 QualType FromRecordTypeWithoutAS = 2863 Context.removeAddrSpaceQualType(FromRecordType); 2864 QualType FromTypeWithDestAS = 2865 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2866 if (PointerConversions) 2867 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2868 From = ImpCastExprToType(From, FromTypeWithDestAS, 2869 CK_AddressSpaceConversion, From->getValueKind()) 2870 .get(); 2871 } 2872 } else { 2873 // No conversion necessary. 2874 return From; 2875 } 2876 2877 if (DestType->isDependentType() || FromType->isDependentType()) 2878 return From; 2879 2880 // If the unqualified types are the same, no conversion is necessary. 2881 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2882 return From; 2883 2884 SourceRange FromRange = From->getSourceRange(); 2885 SourceLocation FromLoc = FromRange.getBegin(); 2886 2887 ExprValueKind VK = From->getValueKind(); 2888 2889 // C++ [class.member.lookup]p8: 2890 // [...] Ambiguities can often be resolved by qualifying a name with its 2891 // class name. 2892 // 2893 // If the member was a qualified name and the qualified referred to a 2894 // specific base subobject type, we'll cast to that intermediate type 2895 // first and then to the object in which the member is declared. That allows 2896 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2897 // 2898 // class Base { public: int x; }; 2899 // class Derived1 : public Base { }; 2900 // class Derived2 : public Base { }; 2901 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2902 // 2903 // void VeryDerived::f() { 2904 // x = 17; // error: ambiguous base subobjects 2905 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2906 // } 2907 if (Qualifier && Qualifier->getAsType()) { 2908 QualType QType = QualType(Qualifier->getAsType(), 0); 2909 assert(QType->isRecordType() && "lookup done with non-record type"); 2910 2911 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2912 2913 // In C++98, the qualifier type doesn't actually have to be a base 2914 // type of the object type, in which case we just ignore it. 2915 // Otherwise build the appropriate casts. 2916 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2917 CXXCastPath BasePath; 2918 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2919 FromLoc, FromRange, &BasePath)) 2920 return ExprError(); 2921 2922 if (PointerConversions) 2923 QType = Context.getPointerType(QType); 2924 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2925 VK, &BasePath).get(); 2926 2927 FromType = QType; 2928 FromRecordType = QRecordType; 2929 2930 // If the qualifier type was the same as the destination type, 2931 // we're done. 2932 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2933 return From; 2934 } 2935 } 2936 2937 bool IgnoreAccess = false; 2938 2939 // If we actually found the member through a using declaration, cast 2940 // down to the using declaration's type. 2941 // 2942 // Pointer equality is fine here because only one declaration of a 2943 // class ever has member declarations. 2944 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2945 assert(isa<UsingShadowDecl>(FoundDecl)); 2946 QualType URecordType = Context.getTypeDeclType( 2947 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2948 2949 // We only need to do this if the naming-class to declaring-class 2950 // conversion is non-trivial. 2951 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2952 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2953 CXXCastPath BasePath; 2954 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2955 FromLoc, FromRange, &BasePath)) 2956 return ExprError(); 2957 2958 QualType UType = URecordType; 2959 if (PointerConversions) 2960 UType = Context.getPointerType(UType); 2961 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2962 VK, &BasePath).get(); 2963 FromType = UType; 2964 FromRecordType = URecordType; 2965 } 2966 2967 // We don't do access control for the conversion from the 2968 // declaring class to the true declaring class. 2969 IgnoreAccess = true; 2970 } 2971 2972 CXXCastPath BasePath; 2973 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2974 FromLoc, FromRange, &BasePath, 2975 IgnoreAccess)) 2976 return ExprError(); 2977 2978 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2979 VK, &BasePath); 2980 } 2981 2982 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2983 const LookupResult &R, 2984 bool HasTrailingLParen) { 2985 // Only when used directly as the postfix-expression of a call. 2986 if (!HasTrailingLParen) 2987 return false; 2988 2989 // Never if a scope specifier was provided. 2990 if (SS.isSet()) 2991 return false; 2992 2993 // Only in C++ or ObjC++. 2994 if (!getLangOpts().CPlusPlus) 2995 return false; 2996 2997 // Turn off ADL when we find certain kinds of declarations during 2998 // normal lookup: 2999 for (NamedDecl *D : R) { 3000 // C++0x [basic.lookup.argdep]p3: 3001 // -- a declaration of a class member 3002 // Since using decls preserve this property, we check this on the 3003 // original decl. 3004 if (D->isCXXClassMember()) 3005 return false; 3006 3007 // C++0x [basic.lookup.argdep]p3: 3008 // -- a block-scope function declaration that is not a 3009 // using-declaration 3010 // NOTE: we also trigger this for function templates (in fact, we 3011 // don't check the decl type at all, since all other decl types 3012 // turn off ADL anyway). 3013 if (isa<UsingShadowDecl>(D)) 3014 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3015 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3016 return false; 3017 3018 // C++0x [basic.lookup.argdep]p3: 3019 // -- a declaration that is neither a function or a function 3020 // template 3021 // And also for builtin functions. 3022 if (isa<FunctionDecl>(D)) { 3023 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3024 3025 // But also builtin functions. 3026 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3027 return false; 3028 } else if (!isa<FunctionTemplateDecl>(D)) 3029 return false; 3030 } 3031 3032 return true; 3033 } 3034 3035 3036 /// Diagnoses obvious problems with the use of the given declaration 3037 /// as an expression. This is only actually called for lookups that 3038 /// were not overloaded, and it doesn't promise that the declaration 3039 /// will in fact be used. 3040 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3041 if (D->isInvalidDecl()) 3042 return true; 3043 3044 if (isa<TypedefNameDecl>(D)) { 3045 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3046 return true; 3047 } 3048 3049 if (isa<ObjCInterfaceDecl>(D)) { 3050 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3051 return true; 3052 } 3053 3054 if (isa<NamespaceDecl>(D)) { 3055 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3056 return true; 3057 } 3058 3059 return false; 3060 } 3061 3062 // Certain multiversion types should be treated as overloaded even when there is 3063 // only one result. 3064 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3065 assert(R.isSingleResult() && "Expected only a single result"); 3066 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3067 return FD && 3068 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3069 } 3070 3071 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3072 LookupResult &R, bool NeedsADL, 3073 bool AcceptInvalidDecl) { 3074 // If this is a single, fully-resolved result and we don't need ADL, 3075 // just build an ordinary singleton decl ref. 3076 if (!NeedsADL && R.isSingleResult() && 3077 !R.getAsSingle<FunctionTemplateDecl>() && 3078 !ShouldLookupResultBeMultiVersionOverload(R)) 3079 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3080 R.getRepresentativeDecl(), nullptr, 3081 AcceptInvalidDecl); 3082 3083 // We only need to check the declaration if there's exactly one 3084 // result, because in the overloaded case the results can only be 3085 // functions and function templates. 3086 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3087 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3088 return ExprError(); 3089 3090 // Otherwise, just build an unresolved lookup expression. Suppress 3091 // any lookup-related diagnostics; we'll hash these out later, when 3092 // we've picked a target. 3093 R.suppressDiagnostics(); 3094 3095 UnresolvedLookupExpr *ULE 3096 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3097 SS.getWithLocInContext(Context), 3098 R.getLookupNameInfo(), 3099 NeedsADL, R.isOverloadedResult(), 3100 R.begin(), R.end()); 3101 3102 return ULE; 3103 } 3104 3105 static void 3106 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3107 ValueDecl *var, DeclContext *DC); 3108 3109 /// Complete semantic analysis for a reference to the given declaration. 3110 ExprResult Sema::BuildDeclarationNameExpr( 3111 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3112 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3113 bool AcceptInvalidDecl) { 3114 assert(D && "Cannot refer to a NULL declaration"); 3115 assert(!isa<FunctionTemplateDecl>(D) && 3116 "Cannot refer unambiguously to a function template"); 3117 3118 SourceLocation Loc = NameInfo.getLoc(); 3119 if (CheckDeclInExpr(*this, Loc, D)) 3120 return ExprError(); 3121 3122 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3123 // Specifically diagnose references to class templates that are missing 3124 // a template argument list. 3125 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3126 return ExprError(); 3127 } 3128 3129 // Make sure that we're referring to a value. 3130 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3131 if (!VD) { 3132 Diag(Loc, diag::err_ref_non_value) 3133 << D << SS.getRange(); 3134 Diag(D->getLocation(), diag::note_declared_at); 3135 return ExprError(); 3136 } 3137 3138 // Check whether this declaration can be used. Note that we suppress 3139 // this check when we're going to perform argument-dependent lookup 3140 // on this function name, because this might not be the function 3141 // that overload resolution actually selects. 3142 if (DiagnoseUseOfDecl(VD, Loc)) 3143 return ExprError(); 3144 3145 // Only create DeclRefExpr's for valid Decl's. 3146 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3147 return ExprError(); 3148 3149 // Handle members of anonymous structs and unions. If we got here, 3150 // and the reference is to a class member indirect field, then this 3151 // must be the subject of a pointer-to-member expression. 3152 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3153 if (!indirectField->isCXXClassMember()) 3154 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3155 indirectField); 3156 3157 { 3158 QualType type = VD->getType(); 3159 if (type.isNull()) 3160 return ExprError(); 3161 ExprValueKind valueKind = VK_RValue; 3162 3163 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3164 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3165 // is expanded by some outer '...' in the context of the use. 3166 type = type.getNonPackExpansionType(); 3167 3168 switch (D->getKind()) { 3169 // Ignore all the non-ValueDecl kinds. 3170 #define ABSTRACT_DECL(kind) 3171 #define VALUE(type, base) 3172 #define DECL(type, base) \ 3173 case Decl::type: 3174 #include "clang/AST/DeclNodes.inc" 3175 llvm_unreachable("invalid value decl kind"); 3176 3177 // These shouldn't make it here. 3178 case Decl::ObjCAtDefsField: 3179 llvm_unreachable("forming non-member reference to ivar?"); 3180 3181 // Enum constants are always r-values and never references. 3182 // Unresolved using declarations are dependent. 3183 case Decl::EnumConstant: 3184 case Decl::UnresolvedUsingValue: 3185 case Decl::OMPDeclareReduction: 3186 case Decl::OMPDeclareMapper: 3187 valueKind = VK_RValue; 3188 break; 3189 3190 // Fields and indirect fields that got here must be for 3191 // pointer-to-member expressions; we just call them l-values for 3192 // internal consistency, because this subexpression doesn't really 3193 // exist in the high-level semantics. 3194 case Decl::Field: 3195 case Decl::IndirectField: 3196 case Decl::ObjCIvar: 3197 assert(getLangOpts().CPlusPlus && 3198 "building reference to field in C?"); 3199 3200 // These can't have reference type in well-formed programs, but 3201 // for internal consistency we do this anyway. 3202 type = type.getNonReferenceType(); 3203 valueKind = VK_LValue; 3204 break; 3205 3206 // Non-type template parameters are either l-values or r-values 3207 // depending on the type. 3208 case Decl::NonTypeTemplateParm: { 3209 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3210 type = reftype->getPointeeType(); 3211 valueKind = VK_LValue; // even if the parameter is an r-value reference 3212 break; 3213 } 3214 3215 // For non-references, we need to strip qualifiers just in case 3216 // the template parameter was declared as 'const int' or whatever. 3217 valueKind = VK_RValue; 3218 type = type.getUnqualifiedType(); 3219 break; 3220 } 3221 3222 case Decl::Var: 3223 case Decl::VarTemplateSpecialization: 3224 case Decl::VarTemplatePartialSpecialization: 3225 case Decl::Decomposition: 3226 case Decl::OMPCapturedExpr: 3227 // In C, "extern void blah;" is valid and is an r-value. 3228 if (!getLangOpts().CPlusPlus && 3229 !type.hasQualifiers() && 3230 type->isVoidType()) { 3231 valueKind = VK_RValue; 3232 break; 3233 } 3234 LLVM_FALLTHROUGH; 3235 3236 case Decl::ImplicitParam: 3237 case Decl::ParmVar: { 3238 // These are always l-values. 3239 valueKind = VK_LValue; 3240 type = type.getNonReferenceType(); 3241 3242 // FIXME: Does the addition of const really only apply in 3243 // potentially-evaluated contexts? Since the variable isn't actually 3244 // captured in an unevaluated context, it seems that the answer is no. 3245 if (!isUnevaluatedContext()) { 3246 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3247 if (!CapturedType.isNull()) 3248 type = CapturedType; 3249 } 3250 3251 break; 3252 } 3253 3254 case Decl::Binding: { 3255 // These are always lvalues. 3256 valueKind = VK_LValue; 3257 type = type.getNonReferenceType(); 3258 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3259 // decides how that's supposed to work. 3260 auto *BD = cast<BindingDecl>(VD); 3261 if (BD->getDeclContext() != CurContext) { 3262 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3263 if (DD && DD->hasLocalStorage()) 3264 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3265 } 3266 break; 3267 } 3268 3269 case Decl::Function: { 3270 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3271 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3272 type = Context.BuiltinFnTy; 3273 valueKind = VK_RValue; 3274 break; 3275 } 3276 } 3277 3278 const FunctionType *fty = type->castAs<FunctionType>(); 3279 3280 // If we're referring to a function with an __unknown_anytype 3281 // result type, make the entire expression __unknown_anytype. 3282 if (fty->getReturnType() == Context.UnknownAnyTy) { 3283 type = Context.UnknownAnyTy; 3284 valueKind = VK_RValue; 3285 break; 3286 } 3287 3288 // Functions are l-values in C++. 3289 if (getLangOpts().CPlusPlus) { 3290 valueKind = VK_LValue; 3291 break; 3292 } 3293 3294 // C99 DR 316 says that, if a function type comes from a 3295 // function definition (without a prototype), that type is only 3296 // used for checking compatibility. Therefore, when referencing 3297 // the function, we pretend that we don't have the full function 3298 // type. 3299 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3300 isa<FunctionProtoType>(fty)) 3301 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3302 fty->getExtInfo()); 3303 3304 // Functions are r-values in C. 3305 valueKind = VK_RValue; 3306 break; 3307 } 3308 3309 case Decl::CXXDeductionGuide: 3310 llvm_unreachable("building reference to deduction guide"); 3311 3312 case Decl::MSProperty: 3313 case Decl::MSGuid: 3314 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3315 // or duplicated between host and device? 3316 valueKind = VK_LValue; 3317 break; 3318 3319 case Decl::CXXMethod: 3320 // If we're referring to a method with an __unknown_anytype 3321 // result type, make the entire expression __unknown_anytype. 3322 // This should only be possible with a type written directly. 3323 if (const FunctionProtoType *proto 3324 = dyn_cast<FunctionProtoType>(VD->getType())) 3325 if (proto->getReturnType() == Context.UnknownAnyTy) { 3326 type = Context.UnknownAnyTy; 3327 valueKind = VK_RValue; 3328 break; 3329 } 3330 3331 // C++ methods are l-values if static, r-values if non-static. 3332 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3333 valueKind = VK_LValue; 3334 break; 3335 } 3336 LLVM_FALLTHROUGH; 3337 3338 case Decl::CXXConversion: 3339 case Decl::CXXDestructor: 3340 case Decl::CXXConstructor: 3341 valueKind = VK_RValue; 3342 break; 3343 } 3344 3345 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3346 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3347 TemplateArgs); 3348 } 3349 } 3350 3351 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3352 SmallString<32> &Target) { 3353 Target.resize(CharByteWidth * (Source.size() + 1)); 3354 char *ResultPtr = &Target[0]; 3355 const llvm::UTF8 *ErrorPtr; 3356 bool success = 3357 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3358 (void)success; 3359 assert(success); 3360 Target.resize(ResultPtr - &Target[0]); 3361 } 3362 3363 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3364 PredefinedExpr::IdentKind IK) { 3365 // Pick the current block, lambda, captured statement or function. 3366 Decl *currentDecl = nullptr; 3367 if (const BlockScopeInfo *BSI = getCurBlock()) 3368 currentDecl = BSI->TheDecl; 3369 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3370 currentDecl = LSI->CallOperator; 3371 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3372 currentDecl = CSI->TheCapturedDecl; 3373 else 3374 currentDecl = getCurFunctionOrMethodDecl(); 3375 3376 if (!currentDecl) { 3377 Diag(Loc, diag::ext_predef_outside_function); 3378 currentDecl = Context.getTranslationUnitDecl(); 3379 } 3380 3381 QualType ResTy; 3382 StringLiteral *SL = nullptr; 3383 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3384 ResTy = Context.DependentTy; 3385 else { 3386 // Pre-defined identifiers are of type char[x], where x is the length of 3387 // the string. 3388 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3389 unsigned Length = Str.length(); 3390 3391 llvm::APInt LengthI(32, Length + 1); 3392 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3393 ResTy = 3394 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3395 SmallString<32> RawChars; 3396 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3397 Str, RawChars); 3398 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3399 ArrayType::Normal, 3400 /*IndexTypeQuals*/ 0); 3401 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3402 /*Pascal*/ false, ResTy, Loc); 3403 } else { 3404 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3405 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3406 ArrayType::Normal, 3407 /*IndexTypeQuals*/ 0); 3408 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3409 /*Pascal*/ false, ResTy, Loc); 3410 } 3411 } 3412 3413 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3414 } 3415 3416 static std::pair<QualType, StringLiteral *> 3417 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3418 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3419 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3420 3421 if (OpType->isDependentType()) { 3422 Result.first = Context.DependentTy; 3423 return Result; 3424 } 3425 3426 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3427 llvm::APInt Length(32, Str.length() + 1); 3428 Result.first = 3429 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3430 Result.first = Context.getConstantArrayType( 3431 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3432 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3433 /*Pascal*/ false, Result.first, OpLoc); 3434 return Result; 3435 } 3436 3437 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3438 TypeSourceInfo *Operand) { 3439 QualType ResultTy; 3440 StringLiteral *SL; 3441 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3442 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3443 3444 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3445 PredefinedExpr::UniqueStableNameType, SL, 3446 Operand); 3447 } 3448 3449 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3450 Expr *E) { 3451 QualType ResultTy; 3452 StringLiteral *SL; 3453 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3454 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3455 3456 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3457 PredefinedExpr::UniqueStableNameExpr, SL, E); 3458 } 3459 3460 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3461 SourceLocation L, SourceLocation R, 3462 ParsedType Ty) { 3463 TypeSourceInfo *TInfo = nullptr; 3464 QualType T = GetTypeFromParser(Ty, &TInfo); 3465 3466 if (T.isNull()) 3467 return ExprError(); 3468 if (!TInfo) 3469 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3470 3471 return BuildUniqueStableName(OpLoc, TInfo); 3472 } 3473 3474 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3475 SourceLocation L, SourceLocation R, 3476 Expr *E) { 3477 return BuildUniqueStableName(OpLoc, E); 3478 } 3479 3480 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3481 PredefinedExpr::IdentKind IK; 3482 3483 switch (Kind) { 3484 default: llvm_unreachable("Unknown simple primary expr!"); 3485 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3486 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3487 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3488 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3489 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3490 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3491 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3492 } 3493 3494 return BuildPredefinedExpr(Loc, IK); 3495 } 3496 3497 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3498 SmallString<16> CharBuffer; 3499 bool Invalid = false; 3500 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3501 if (Invalid) 3502 return ExprError(); 3503 3504 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3505 PP, Tok.getKind()); 3506 if (Literal.hadError()) 3507 return ExprError(); 3508 3509 QualType Ty; 3510 if (Literal.isWide()) 3511 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3512 else if (Literal.isUTF8() && getLangOpts().Char8) 3513 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3514 else if (Literal.isUTF16()) 3515 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3516 else if (Literal.isUTF32()) 3517 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3518 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3519 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3520 else 3521 Ty = Context.CharTy; // 'x' -> char in C++ 3522 3523 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3524 if (Literal.isWide()) 3525 Kind = CharacterLiteral::Wide; 3526 else if (Literal.isUTF16()) 3527 Kind = CharacterLiteral::UTF16; 3528 else if (Literal.isUTF32()) 3529 Kind = CharacterLiteral::UTF32; 3530 else if (Literal.isUTF8()) 3531 Kind = CharacterLiteral::UTF8; 3532 3533 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3534 Tok.getLocation()); 3535 3536 if (Literal.getUDSuffix().empty()) 3537 return Lit; 3538 3539 // We're building a user-defined literal. 3540 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3541 SourceLocation UDSuffixLoc = 3542 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3543 3544 // Make sure we're allowed user-defined literals here. 3545 if (!UDLScope) 3546 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3547 3548 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3549 // operator "" X (ch) 3550 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3551 Lit, Tok.getLocation()); 3552 } 3553 3554 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3555 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3556 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3557 Context.IntTy, Loc); 3558 } 3559 3560 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3561 QualType Ty, SourceLocation Loc) { 3562 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3563 3564 using llvm::APFloat; 3565 APFloat Val(Format); 3566 3567 APFloat::opStatus result = Literal.GetFloatValue(Val); 3568 3569 // Overflow is always an error, but underflow is only an error if 3570 // we underflowed to zero (APFloat reports denormals as underflow). 3571 if ((result & APFloat::opOverflow) || 3572 ((result & APFloat::opUnderflow) && Val.isZero())) { 3573 unsigned diagnostic; 3574 SmallString<20> buffer; 3575 if (result & APFloat::opOverflow) { 3576 diagnostic = diag::warn_float_overflow; 3577 APFloat::getLargest(Format).toString(buffer); 3578 } else { 3579 diagnostic = diag::warn_float_underflow; 3580 APFloat::getSmallest(Format).toString(buffer); 3581 } 3582 3583 S.Diag(Loc, diagnostic) 3584 << Ty 3585 << StringRef(buffer.data(), buffer.size()); 3586 } 3587 3588 bool isExact = (result == APFloat::opOK); 3589 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3590 } 3591 3592 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3593 assert(E && "Invalid expression"); 3594 3595 if (E->isValueDependent()) 3596 return false; 3597 3598 QualType QT = E->getType(); 3599 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3600 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3601 return true; 3602 } 3603 3604 llvm::APSInt ValueAPS; 3605 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3606 3607 if (R.isInvalid()) 3608 return true; 3609 3610 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3611 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3612 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3613 << ValueAPS.toString(10) << ValueIsPositive; 3614 return true; 3615 } 3616 3617 return false; 3618 } 3619 3620 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3621 // Fast path for a single digit (which is quite common). A single digit 3622 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3623 if (Tok.getLength() == 1) { 3624 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3625 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3626 } 3627 3628 SmallString<128> SpellingBuffer; 3629 // NumericLiteralParser wants to overread by one character. Add padding to 3630 // the buffer in case the token is copied to the buffer. If getSpelling() 3631 // returns a StringRef to the memory buffer, it should have a null char at 3632 // the EOF, so it is also safe. 3633 SpellingBuffer.resize(Tok.getLength() + 1); 3634 3635 // Get the spelling of the token, which eliminates trigraphs, etc. 3636 bool Invalid = false; 3637 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3638 if (Invalid) 3639 return ExprError(); 3640 3641 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3642 PP.getSourceManager(), PP.getLangOpts(), 3643 PP.getTargetInfo(), PP.getDiagnostics()); 3644 if (Literal.hadError) 3645 return ExprError(); 3646 3647 if (Literal.hasUDSuffix()) { 3648 // We're building a user-defined literal. 3649 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3650 SourceLocation UDSuffixLoc = 3651 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3652 3653 // Make sure we're allowed user-defined literals here. 3654 if (!UDLScope) 3655 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3656 3657 QualType CookedTy; 3658 if (Literal.isFloatingLiteral()) { 3659 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3660 // long double, the literal is treated as a call of the form 3661 // operator "" X (f L) 3662 CookedTy = Context.LongDoubleTy; 3663 } else { 3664 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3665 // unsigned long long, the literal is treated as a call of the form 3666 // operator "" X (n ULL) 3667 CookedTy = Context.UnsignedLongLongTy; 3668 } 3669 3670 DeclarationName OpName = 3671 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3672 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3673 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3674 3675 SourceLocation TokLoc = Tok.getLocation(); 3676 3677 // Perform literal operator lookup to determine if we're building a raw 3678 // literal or a cooked one. 3679 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3680 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3681 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3682 /*AllowStringTemplate*/ false, 3683 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3684 case LOLR_ErrorNoDiagnostic: 3685 // Lookup failure for imaginary constants isn't fatal, there's still the 3686 // GNU extension producing _Complex types. 3687 break; 3688 case LOLR_Error: 3689 return ExprError(); 3690 case LOLR_Cooked: { 3691 Expr *Lit; 3692 if (Literal.isFloatingLiteral()) { 3693 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3694 } else { 3695 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3696 if (Literal.GetIntegerValue(ResultVal)) 3697 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3698 << /* Unsigned */ 1; 3699 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3700 Tok.getLocation()); 3701 } 3702 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3703 } 3704 3705 case LOLR_Raw: { 3706 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3707 // literal is treated as a call of the form 3708 // operator "" X ("n") 3709 unsigned Length = Literal.getUDSuffixOffset(); 3710 QualType StrTy = Context.getConstantArrayType( 3711 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3712 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3713 Expr *Lit = StringLiteral::Create( 3714 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3715 /*Pascal*/false, StrTy, &TokLoc, 1); 3716 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3717 } 3718 3719 case LOLR_Template: { 3720 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3721 // template), L is treated as a call fo the form 3722 // operator "" X <'c1', 'c2', ... 'ck'>() 3723 // where n is the source character sequence c1 c2 ... ck. 3724 TemplateArgumentListInfo ExplicitArgs; 3725 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3726 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3727 llvm::APSInt Value(CharBits, CharIsUnsigned); 3728 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3729 Value = TokSpelling[I]; 3730 TemplateArgument Arg(Context, Value, Context.CharTy); 3731 TemplateArgumentLocInfo ArgInfo; 3732 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3733 } 3734 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3735 &ExplicitArgs); 3736 } 3737 case LOLR_StringTemplate: 3738 llvm_unreachable("unexpected literal operator lookup result"); 3739 } 3740 } 3741 3742 Expr *Res; 3743 3744 if (Literal.isFixedPointLiteral()) { 3745 QualType Ty; 3746 3747 if (Literal.isAccum) { 3748 if (Literal.isHalf) { 3749 Ty = Context.ShortAccumTy; 3750 } else if (Literal.isLong) { 3751 Ty = Context.LongAccumTy; 3752 } else { 3753 Ty = Context.AccumTy; 3754 } 3755 } else if (Literal.isFract) { 3756 if (Literal.isHalf) { 3757 Ty = Context.ShortFractTy; 3758 } else if (Literal.isLong) { 3759 Ty = Context.LongFractTy; 3760 } else { 3761 Ty = Context.FractTy; 3762 } 3763 } 3764 3765 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3766 3767 bool isSigned = !Literal.isUnsigned; 3768 unsigned scale = Context.getFixedPointScale(Ty); 3769 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3770 3771 llvm::APInt Val(bit_width, 0, isSigned); 3772 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3773 bool ValIsZero = Val.isNullValue() && !Overflowed; 3774 3775 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3776 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3777 // Clause 6.4.4 - The value of a constant shall be in the range of 3778 // representable values for its type, with exception for constants of a 3779 // fract type with a value of exactly 1; such a constant shall denote 3780 // the maximal value for the type. 3781 --Val; 3782 else if (Val.ugt(MaxVal) || Overflowed) 3783 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3784 3785 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3786 Tok.getLocation(), scale); 3787 } else if (Literal.isFloatingLiteral()) { 3788 QualType Ty; 3789 if (Literal.isHalf){ 3790 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3791 Ty = Context.HalfTy; 3792 else { 3793 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3794 return ExprError(); 3795 } 3796 } else if (Literal.isFloat) 3797 Ty = Context.FloatTy; 3798 else if (Literal.isLong) 3799 Ty = Context.LongDoubleTy; 3800 else if (Literal.isFloat16) 3801 Ty = Context.Float16Ty; 3802 else if (Literal.isFloat128) 3803 Ty = Context.Float128Ty; 3804 else 3805 Ty = Context.DoubleTy; 3806 3807 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3808 3809 if (Ty == Context.DoubleTy) { 3810 if (getLangOpts().SinglePrecisionConstants) { 3811 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3812 if (BTy->getKind() != BuiltinType::Float) { 3813 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3814 } 3815 } else if (getLangOpts().OpenCL && 3816 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3817 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3818 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3819 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3820 } 3821 } 3822 } else if (!Literal.isIntegerLiteral()) { 3823 return ExprError(); 3824 } else { 3825 QualType Ty; 3826 3827 // 'long long' is a C99 or C++11 feature. 3828 if (!getLangOpts().C99 && Literal.isLongLong) { 3829 if (getLangOpts().CPlusPlus) 3830 Diag(Tok.getLocation(), 3831 getLangOpts().CPlusPlus11 ? 3832 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3833 else 3834 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3835 } 3836 3837 // Get the value in the widest-possible width. 3838 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3839 llvm::APInt ResultVal(MaxWidth, 0); 3840 3841 if (Literal.GetIntegerValue(ResultVal)) { 3842 // If this value didn't fit into uintmax_t, error and force to ull. 3843 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3844 << /* Unsigned */ 1; 3845 Ty = Context.UnsignedLongLongTy; 3846 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3847 "long long is not intmax_t?"); 3848 } else { 3849 // If this value fits into a ULL, try to figure out what else it fits into 3850 // according to the rules of C99 6.4.4.1p5. 3851 3852 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3853 // be an unsigned int. 3854 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3855 3856 // Check from smallest to largest, picking the smallest type we can. 3857 unsigned Width = 0; 3858 3859 // Microsoft specific integer suffixes are explicitly sized. 3860 if (Literal.MicrosoftInteger) { 3861 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3862 Width = 8; 3863 Ty = Context.CharTy; 3864 } else { 3865 Width = Literal.MicrosoftInteger; 3866 Ty = Context.getIntTypeForBitwidth(Width, 3867 /*Signed=*/!Literal.isUnsigned); 3868 } 3869 } 3870 3871 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3872 // Are int/unsigned possibilities? 3873 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3874 3875 // Does it fit in a unsigned int? 3876 if (ResultVal.isIntN(IntSize)) { 3877 // Does it fit in a signed int? 3878 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3879 Ty = Context.IntTy; 3880 else if (AllowUnsigned) 3881 Ty = Context.UnsignedIntTy; 3882 Width = IntSize; 3883 } 3884 } 3885 3886 // Are long/unsigned long possibilities? 3887 if (Ty.isNull() && !Literal.isLongLong) { 3888 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3889 3890 // Does it fit in a unsigned long? 3891 if (ResultVal.isIntN(LongSize)) { 3892 // Does it fit in a signed long? 3893 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3894 Ty = Context.LongTy; 3895 else if (AllowUnsigned) 3896 Ty = Context.UnsignedLongTy; 3897 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3898 // is compatible. 3899 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3900 const unsigned LongLongSize = 3901 Context.getTargetInfo().getLongLongWidth(); 3902 Diag(Tok.getLocation(), 3903 getLangOpts().CPlusPlus 3904 ? Literal.isLong 3905 ? diag::warn_old_implicitly_unsigned_long_cxx 3906 : /*C++98 UB*/ diag:: 3907 ext_old_implicitly_unsigned_long_cxx 3908 : diag::warn_old_implicitly_unsigned_long) 3909 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3910 : /*will be ill-formed*/ 1); 3911 Ty = Context.UnsignedLongTy; 3912 } 3913 Width = LongSize; 3914 } 3915 } 3916 3917 // Check long long if needed. 3918 if (Ty.isNull()) { 3919 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3920 3921 // Does it fit in a unsigned long long? 3922 if (ResultVal.isIntN(LongLongSize)) { 3923 // Does it fit in a signed long long? 3924 // To be compatible with MSVC, hex integer literals ending with the 3925 // LL or i64 suffix are always signed in Microsoft mode. 3926 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3927 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3928 Ty = Context.LongLongTy; 3929 else if (AllowUnsigned) 3930 Ty = Context.UnsignedLongLongTy; 3931 Width = LongLongSize; 3932 } 3933 } 3934 3935 // If we still couldn't decide a type, we probably have something that 3936 // does not fit in a signed long long, but has no U suffix. 3937 if (Ty.isNull()) { 3938 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3939 Ty = Context.UnsignedLongLongTy; 3940 Width = Context.getTargetInfo().getLongLongWidth(); 3941 } 3942 3943 if (ResultVal.getBitWidth() != Width) 3944 ResultVal = ResultVal.trunc(Width); 3945 } 3946 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3947 } 3948 3949 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3950 if (Literal.isImaginary) { 3951 Res = new (Context) ImaginaryLiteral(Res, 3952 Context.getComplexType(Res->getType())); 3953 3954 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3955 } 3956 return Res; 3957 } 3958 3959 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3960 assert(E && "ActOnParenExpr() missing expr"); 3961 return new (Context) ParenExpr(L, R, E); 3962 } 3963 3964 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3965 SourceLocation Loc, 3966 SourceRange ArgRange) { 3967 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3968 // scalar or vector data type argument..." 3969 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3970 // type (C99 6.2.5p18) or void. 3971 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3972 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3973 << T << ArgRange; 3974 return true; 3975 } 3976 3977 assert((T->isVoidType() || !T->isIncompleteType()) && 3978 "Scalar types should always be complete"); 3979 return false; 3980 } 3981 3982 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3983 SourceLocation Loc, 3984 SourceRange ArgRange, 3985 UnaryExprOrTypeTrait TraitKind) { 3986 // Invalid types must be hard errors for SFINAE in C++. 3987 if (S.LangOpts.CPlusPlus) 3988 return true; 3989 3990 // C99 6.5.3.4p1: 3991 if (T->isFunctionType() && 3992 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3993 TraitKind == UETT_PreferredAlignOf)) { 3994 // sizeof(function)/alignof(function) is allowed as an extension. 3995 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3996 << getTraitSpelling(TraitKind) << ArgRange; 3997 return false; 3998 } 3999 4000 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4001 // this is an error (OpenCL v1.1 s6.3.k) 4002 if (T->isVoidType()) { 4003 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4004 : diag::ext_sizeof_alignof_void_type; 4005 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4006 return false; 4007 } 4008 4009 return true; 4010 } 4011 4012 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4013 SourceLocation Loc, 4014 SourceRange ArgRange, 4015 UnaryExprOrTypeTrait TraitKind) { 4016 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4017 // runtime doesn't allow it. 4018 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4019 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4020 << T << (TraitKind == UETT_SizeOf) 4021 << ArgRange; 4022 return true; 4023 } 4024 4025 return false; 4026 } 4027 4028 /// Check whether E is a pointer from a decayed array type (the decayed 4029 /// pointer type is equal to T) and emit a warning if it is. 4030 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4031 Expr *E) { 4032 // Don't warn if the operation changed the type. 4033 if (T != E->getType()) 4034 return; 4035 4036 // Now look for array decays. 4037 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4038 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4039 return; 4040 4041 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4042 << ICE->getType() 4043 << ICE->getSubExpr()->getType(); 4044 } 4045 4046 /// Check the constraints on expression operands to unary type expression 4047 /// and type traits. 4048 /// 4049 /// Completes any types necessary and validates the constraints on the operand 4050 /// expression. The logic mostly mirrors the type-based overload, but may modify 4051 /// the expression as it completes the type for that expression through template 4052 /// instantiation, etc. 4053 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4054 UnaryExprOrTypeTrait ExprKind) { 4055 QualType ExprTy = E->getType(); 4056 assert(!ExprTy->isReferenceType()); 4057 4058 bool IsUnevaluatedOperand = 4059 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4060 ExprKind == UETT_PreferredAlignOf); 4061 if (IsUnevaluatedOperand) { 4062 ExprResult Result = CheckUnevaluatedOperand(E); 4063 if (Result.isInvalid()) 4064 return true; 4065 E = Result.get(); 4066 } 4067 4068 if (ExprKind == UETT_VecStep) 4069 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4070 E->getSourceRange()); 4071 4072 // Explicitly list some types as extensions. 4073 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4074 E->getSourceRange(), ExprKind)) 4075 return false; 4076 4077 // 'alignof' applied to an expression only requires the base element type of 4078 // the expression to be complete. 'sizeof' requires the expression's type to 4079 // be complete (and will attempt to complete it if it's an array of unknown 4080 // bound). 4081 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4082 if (RequireCompleteSizedType( 4083 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4084 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4085 getTraitSpelling(ExprKind), E->getSourceRange())) 4086 return true; 4087 } else { 4088 if (RequireCompleteSizedExprType( 4089 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4090 getTraitSpelling(ExprKind), E->getSourceRange())) 4091 return true; 4092 } 4093 4094 // Completing the expression's type may have changed it. 4095 ExprTy = E->getType(); 4096 assert(!ExprTy->isReferenceType()); 4097 4098 if (ExprTy->isFunctionType()) { 4099 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4100 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4101 return true; 4102 } 4103 4104 // The operand for sizeof and alignof is in an unevaluated expression context, 4105 // so side effects could result in unintended consequences. 4106 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4107 E->HasSideEffects(Context, false)) 4108 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4109 4110 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4111 E->getSourceRange(), ExprKind)) 4112 return true; 4113 4114 if (ExprKind == UETT_SizeOf) { 4115 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4116 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4117 QualType OType = PVD->getOriginalType(); 4118 QualType Type = PVD->getType(); 4119 if (Type->isPointerType() && OType->isArrayType()) { 4120 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4121 << Type << OType; 4122 Diag(PVD->getLocation(), diag::note_declared_at); 4123 } 4124 } 4125 } 4126 4127 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4128 // decays into a pointer and returns an unintended result. This is most 4129 // likely a typo for "sizeof(array) op x". 4130 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4131 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4132 BO->getLHS()); 4133 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4134 BO->getRHS()); 4135 } 4136 } 4137 4138 return false; 4139 } 4140 4141 /// Check the constraints on operands to unary expression and type 4142 /// traits. 4143 /// 4144 /// This will complete any types necessary, and validate the various constraints 4145 /// on those operands. 4146 /// 4147 /// The UsualUnaryConversions() function is *not* called by this routine. 4148 /// C99 6.3.2.1p[2-4] all state: 4149 /// Except when it is the operand of the sizeof operator ... 4150 /// 4151 /// C++ [expr.sizeof]p4 4152 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4153 /// standard conversions are not applied to the operand of sizeof. 4154 /// 4155 /// This policy is followed for all of the unary trait expressions. 4156 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4157 SourceLocation OpLoc, 4158 SourceRange ExprRange, 4159 UnaryExprOrTypeTrait ExprKind) { 4160 if (ExprType->isDependentType()) 4161 return false; 4162 4163 // C++ [expr.sizeof]p2: 4164 // When applied to a reference or a reference type, the result 4165 // is the size of the referenced type. 4166 // C++11 [expr.alignof]p3: 4167 // When alignof is applied to a reference type, the result 4168 // shall be the alignment of the referenced type. 4169 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4170 ExprType = Ref->getPointeeType(); 4171 4172 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4173 // When alignof or _Alignof is applied to an array type, the result 4174 // is the alignment of the element type. 4175 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4176 ExprKind == UETT_OpenMPRequiredSimdAlign) 4177 ExprType = Context.getBaseElementType(ExprType); 4178 4179 if (ExprKind == UETT_VecStep) 4180 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4181 4182 // Explicitly list some types as extensions. 4183 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4184 ExprKind)) 4185 return false; 4186 4187 if (RequireCompleteSizedType( 4188 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4189 getTraitSpelling(ExprKind), ExprRange)) 4190 return true; 4191 4192 if (ExprType->isFunctionType()) { 4193 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4194 << getTraitSpelling(ExprKind) << ExprRange; 4195 return true; 4196 } 4197 4198 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4199 ExprKind)) 4200 return true; 4201 4202 return false; 4203 } 4204 4205 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4206 // Cannot know anything else if the expression is dependent. 4207 if (E->isTypeDependent()) 4208 return false; 4209 4210 if (E->getObjectKind() == OK_BitField) { 4211 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4212 << 1 << E->getSourceRange(); 4213 return true; 4214 } 4215 4216 ValueDecl *D = nullptr; 4217 Expr *Inner = E->IgnoreParens(); 4218 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4219 D = DRE->getDecl(); 4220 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4221 D = ME->getMemberDecl(); 4222 } 4223 4224 // If it's a field, require the containing struct to have a 4225 // complete definition so that we can compute the layout. 4226 // 4227 // This can happen in C++11 onwards, either by naming the member 4228 // in a way that is not transformed into a member access expression 4229 // (in an unevaluated operand, for instance), or by naming the member 4230 // in a trailing-return-type. 4231 // 4232 // For the record, since __alignof__ on expressions is a GCC 4233 // extension, GCC seems to permit this but always gives the 4234 // nonsensical answer 0. 4235 // 4236 // We don't really need the layout here --- we could instead just 4237 // directly check for all the appropriate alignment-lowing 4238 // attributes --- but that would require duplicating a lot of 4239 // logic that just isn't worth duplicating for such a marginal 4240 // use-case. 4241 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4242 // Fast path this check, since we at least know the record has a 4243 // definition if we can find a member of it. 4244 if (!FD->getParent()->isCompleteDefinition()) { 4245 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4246 << E->getSourceRange(); 4247 return true; 4248 } 4249 4250 // Otherwise, if it's a field, and the field doesn't have 4251 // reference type, then it must have a complete type (or be a 4252 // flexible array member, which we explicitly want to 4253 // white-list anyway), which makes the following checks trivial. 4254 if (!FD->getType()->isReferenceType()) 4255 return false; 4256 } 4257 4258 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4259 } 4260 4261 bool Sema::CheckVecStepExpr(Expr *E) { 4262 E = E->IgnoreParens(); 4263 4264 // Cannot know anything else if the expression is dependent. 4265 if (E->isTypeDependent()) 4266 return false; 4267 4268 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4269 } 4270 4271 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4272 CapturingScopeInfo *CSI) { 4273 assert(T->isVariablyModifiedType()); 4274 assert(CSI != nullptr); 4275 4276 // We're going to walk down into the type and look for VLA expressions. 4277 do { 4278 const Type *Ty = T.getTypePtr(); 4279 switch (Ty->getTypeClass()) { 4280 #define TYPE(Class, Base) 4281 #define ABSTRACT_TYPE(Class, Base) 4282 #define NON_CANONICAL_TYPE(Class, Base) 4283 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4284 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4285 #include "clang/AST/TypeNodes.inc" 4286 T = QualType(); 4287 break; 4288 // These types are never variably-modified. 4289 case Type::Builtin: 4290 case Type::Complex: 4291 case Type::Vector: 4292 case Type::ExtVector: 4293 case Type::ConstantMatrix: 4294 case Type::Record: 4295 case Type::Enum: 4296 case Type::Elaborated: 4297 case Type::TemplateSpecialization: 4298 case Type::ObjCObject: 4299 case Type::ObjCInterface: 4300 case Type::ObjCObjectPointer: 4301 case Type::ObjCTypeParam: 4302 case Type::Pipe: 4303 case Type::ExtInt: 4304 llvm_unreachable("type class is never variably-modified!"); 4305 case Type::Adjusted: 4306 T = cast<AdjustedType>(Ty)->getOriginalType(); 4307 break; 4308 case Type::Decayed: 4309 T = cast<DecayedType>(Ty)->getPointeeType(); 4310 break; 4311 case Type::Pointer: 4312 T = cast<PointerType>(Ty)->getPointeeType(); 4313 break; 4314 case Type::BlockPointer: 4315 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4316 break; 4317 case Type::LValueReference: 4318 case Type::RValueReference: 4319 T = cast<ReferenceType>(Ty)->getPointeeType(); 4320 break; 4321 case Type::MemberPointer: 4322 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4323 break; 4324 case Type::ConstantArray: 4325 case Type::IncompleteArray: 4326 // Losing element qualification here is fine. 4327 T = cast<ArrayType>(Ty)->getElementType(); 4328 break; 4329 case Type::VariableArray: { 4330 // Losing element qualification here is fine. 4331 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4332 4333 // Unknown size indication requires no size computation. 4334 // Otherwise, evaluate and record it. 4335 auto Size = VAT->getSizeExpr(); 4336 if (Size && !CSI->isVLATypeCaptured(VAT) && 4337 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4338 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4339 4340 T = VAT->getElementType(); 4341 break; 4342 } 4343 case Type::FunctionProto: 4344 case Type::FunctionNoProto: 4345 T = cast<FunctionType>(Ty)->getReturnType(); 4346 break; 4347 case Type::Paren: 4348 case Type::TypeOf: 4349 case Type::UnaryTransform: 4350 case Type::Attributed: 4351 case Type::SubstTemplateTypeParm: 4352 case Type::MacroQualified: 4353 // Keep walking after single level desugaring. 4354 T = T.getSingleStepDesugaredType(Context); 4355 break; 4356 case Type::Typedef: 4357 T = cast<TypedefType>(Ty)->desugar(); 4358 break; 4359 case Type::Decltype: 4360 T = cast<DecltypeType>(Ty)->desugar(); 4361 break; 4362 case Type::Auto: 4363 case Type::DeducedTemplateSpecialization: 4364 T = cast<DeducedType>(Ty)->getDeducedType(); 4365 break; 4366 case Type::TypeOfExpr: 4367 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4368 break; 4369 case Type::Atomic: 4370 T = cast<AtomicType>(Ty)->getValueType(); 4371 break; 4372 } 4373 } while (!T.isNull() && T->isVariablyModifiedType()); 4374 } 4375 4376 /// Build a sizeof or alignof expression given a type operand. 4377 ExprResult 4378 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4379 SourceLocation OpLoc, 4380 UnaryExprOrTypeTrait ExprKind, 4381 SourceRange R) { 4382 if (!TInfo) 4383 return ExprError(); 4384 4385 QualType T = TInfo->getType(); 4386 4387 if (!T->isDependentType() && 4388 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4389 return ExprError(); 4390 4391 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4392 if (auto *TT = T->getAs<TypedefType>()) { 4393 for (auto I = FunctionScopes.rbegin(), 4394 E = std::prev(FunctionScopes.rend()); 4395 I != E; ++I) { 4396 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4397 if (CSI == nullptr) 4398 break; 4399 DeclContext *DC = nullptr; 4400 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4401 DC = LSI->CallOperator; 4402 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4403 DC = CRSI->TheCapturedDecl; 4404 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4405 DC = BSI->TheDecl; 4406 if (DC) { 4407 if (DC->containsDecl(TT->getDecl())) 4408 break; 4409 captureVariablyModifiedType(Context, T, CSI); 4410 } 4411 } 4412 } 4413 } 4414 4415 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4416 return new (Context) UnaryExprOrTypeTraitExpr( 4417 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4418 } 4419 4420 /// Build a sizeof or alignof expression given an expression 4421 /// operand. 4422 ExprResult 4423 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4424 UnaryExprOrTypeTrait ExprKind) { 4425 ExprResult PE = CheckPlaceholderExpr(E); 4426 if (PE.isInvalid()) 4427 return ExprError(); 4428 4429 E = PE.get(); 4430 4431 // Verify that the operand is valid. 4432 bool isInvalid = false; 4433 if (E->isTypeDependent()) { 4434 // Delay type-checking for type-dependent expressions. 4435 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4436 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4437 } else if (ExprKind == UETT_VecStep) { 4438 isInvalid = CheckVecStepExpr(E); 4439 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4440 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4441 isInvalid = true; 4442 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4443 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4444 isInvalid = true; 4445 } else { 4446 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4447 } 4448 4449 if (isInvalid) 4450 return ExprError(); 4451 4452 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4453 PE = TransformToPotentiallyEvaluated(E); 4454 if (PE.isInvalid()) return ExprError(); 4455 E = PE.get(); 4456 } 4457 4458 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4459 return new (Context) UnaryExprOrTypeTraitExpr( 4460 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4461 } 4462 4463 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4464 /// expr and the same for @c alignof and @c __alignof 4465 /// Note that the ArgRange is invalid if isType is false. 4466 ExprResult 4467 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4468 UnaryExprOrTypeTrait ExprKind, bool IsType, 4469 void *TyOrEx, SourceRange ArgRange) { 4470 // If error parsing type, ignore. 4471 if (!TyOrEx) return ExprError(); 4472 4473 if (IsType) { 4474 TypeSourceInfo *TInfo; 4475 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4476 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4477 } 4478 4479 Expr *ArgEx = (Expr *)TyOrEx; 4480 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4481 return Result; 4482 } 4483 4484 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4485 bool IsReal) { 4486 if (V.get()->isTypeDependent()) 4487 return S.Context.DependentTy; 4488 4489 // _Real and _Imag are only l-values for normal l-values. 4490 if (V.get()->getObjectKind() != OK_Ordinary) { 4491 V = S.DefaultLvalueConversion(V.get()); 4492 if (V.isInvalid()) 4493 return QualType(); 4494 } 4495 4496 // These operators return the element type of a complex type. 4497 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4498 return CT->getElementType(); 4499 4500 // Otherwise they pass through real integer and floating point types here. 4501 if (V.get()->getType()->isArithmeticType()) 4502 return V.get()->getType(); 4503 4504 // Test for placeholders. 4505 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4506 if (PR.isInvalid()) return QualType(); 4507 if (PR.get() != V.get()) { 4508 V = PR; 4509 return CheckRealImagOperand(S, V, Loc, IsReal); 4510 } 4511 4512 // Reject anything else. 4513 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4514 << (IsReal ? "__real" : "__imag"); 4515 return QualType(); 4516 } 4517 4518 4519 4520 ExprResult 4521 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4522 tok::TokenKind Kind, Expr *Input) { 4523 UnaryOperatorKind Opc; 4524 switch (Kind) { 4525 default: llvm_unreachable("Unknown unary op!"); 4526 case tok::plusplus: Opc = UO_PostInc; break; 4527 case tok::minusminus: Opc = UO_PostDec; break; 4528 } 4529 4530 // Since this might is a postfix expression, get rid of ParenListExprs. 4531 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4532 if (Result.isInvalid()) return ExprError(); 4533 Input = Result.get(); 4534 4535 return BuildUnaryOp(S, OpLoc, Opc, Input); 4536 } 4537 4538 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4539 /// 4540 /// \return true on error 4541 static bool checkArithmeticOnObjCPointer(Sema &S, 4542 SourceLocation opLoc, 4543 Expr *op) { 4544 assert(op->getType()->isObjCObjectPointerType()); 4545 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4546 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4547 return false; 4548 4549 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4550 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4551 << op->getSourceRange(); 4552 return true; 4553 } 4554 4555 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4556 auto *BaseNoParens = Base->IgnoreParens(); 4557 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4558 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4559 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4560 } 4561 4562 ExprResult 4563 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4564 Expr *idx, SourceLocation rbLoc) { 4565 if (base && !base->getType().isNull() && 4566 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4567 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4568 SourceLocation(), /*Length*/ nullptr, 4569 /*Stride=*/nullptr, rbLoc); 4570 4571 // Since this might be a postfix expression, get rid of ParenListExprs. 4572 if (isa<ParenListExpr>(base)) { 4573 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4574 if (result.isInvalid()) return ExprError(); 4575 base = result.get(); 4576 } 4577 4578 // Check if base and idx form a MatrixSubscriptExpr. 4579 // 4580 // Helper to check for comma expressions, which are not allowed as indices for 4581 // matrix subscript expressions. 4582 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4583 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4584 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4585 << SourceRange(base->getBeginLoc(), rbLoc); 4586 return true; 4587 } 4588 return false; 4589 }; 4590 // The matrix subscript operator ([][])is considered a single operator. 4591 // Separating the index expressions by parenthesis is not allowed. 4592 if (base->getType()->isSpecificPlaceholderType( 4593 BuiltinType::IncompleteMatrixIdx) && 4594 !isa<MatrixSubscriptExpr>(base)) { 4595 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4596 << SourceRange(base->getBeginLoc(), rbLoc); 4597 return ExprError(); 4598 } 4599 // If the base is a MatrixSubscriptExpr, try to create a new 4600 // MatrixSubscriptExpr. 4601 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4602 if (matSubscriptE) { 4603 if (CheckAndReportCommaError(idx)) 4604 return ExprError(); 4605 4606 assert(matSubscriptE->isIncomplete() && 4607 "base has to be an incomplete matrix subscript"); 4608 return CreateBuiltinMatrixSubscriptExpr( 4609 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4610 } 4611 4612 // Handle any non-overload placeholder types in the base and index 4613 // expressions. We can't handle overloads here because the other 4614 // operand might be an overloadable type, in which case the overload 4615 // resolution for the operator overload should get the first crack 4616 // at the overload. 4617 bool IsMSPropertySubscript = false; 4618 if (base->getType()->isNonOverloadPlaceholderType()) { 4619 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4620 if (!IsMSPropertySubscript) { 4621 ExprResult result = CheckPlaceholderExpr(base); 4622 if (result.isInvalid()) 4623 return ExprError(); 4624 base = result.get(); 4625 } 4626 } 4627 4628 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4629 if (base->getType()->isMatrixType()) { 4630 if (CheckAndReportCommaError(idx)) 4631 return ExprError(); 4632 4633 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4634 } 4635 4636 // A comma-expression as the index is deprecated in C++2a onwards. 4637 if (getLangOpts().CPlusPlus20 && 4638 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4639 (isa<CXXOperatorCallExpr>(idx) && 4640 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4641 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4642 << SourceRange(base->getBeginLoc(), rbLoc); 4643 } 4644 4645 if (idx->getType()->isNonOverloadPlaceholderType()) { 4646 ExprResult result = CheckPlaceholderExpr(idx); 4647 if (result.isInvalid()) return ExprError(); 4648 idx = result.get(); 4649 } 4650 4651 // Build an unanalyzed expression if either operand is type-dependent. 4652 if (getLangOpts().CPlusPlus && 4653 (base->isTypeDependent() || idx->isTypeDependent())) { 4654 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4655 VK_LValue, OK_Ordinary, rbLoc); 4656 } 4657 4658 // MSDN, property (C++) 4659 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4660 // This attribute can also be used in the declaration of an empty array in a 4661 // class or structure definition. For example: 4662 // __declspec(property(get=GetX, put=PutX)) int x[]; 4663 // The above statement indicates that x[] can be used with one or more array 4664 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4665 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4666 if (IsMSPropertySubscript) { 4667 // Build MS property subscript expression if base is MS property reference 4668 // or MS property subscript. 4669 return new (Context) MSPropertySubscriptExpr( 4670 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4671 } 4672 4673 // Use C++ overloaded-operator rules if either operand has record 4674 // type. The spec says to do this if either type is *overloadable*, 4675 // but enum types can't declare subscript operators or conversion 4676 // operators, so there's nothing interesting for overload resolution 4677 // to do if there aren't any record types involved. 4678 // 4679 // ObjC pointers have their own subscripting logic that is not tied 4680 // to overload resolution and so should not take this path. 4681 if (getLangOpts().CPlusPlus && 4682 (base->getType()->isRecordType() || 4683 (!base->getType()->isObjCObjectPointerType() && 4684 idx->getType()->isRecordType()))) { 4685 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4686 } 4687 4688 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4689 4690 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4691 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4692 4693 return Res; 4694 } 4695 4696 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4697 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4698 InitializationKind Kind = 4699 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4700 InitializationSequence InitSeq(*this, Entity, Kind, E); 4701 return InitSeq.Perform(*this, Entity, Kind, E); 4702 } 4703 4704 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4705 Expr *ColumnIdx, 4706 SourceLocation RBLoc) { 4707 ExprResult BaseR = CheckPlaceholderExpr(Base); 4708 if (BaseR.isInvalid()) 4709 return BaseR; 4710 Base = BaseR.get(); 4711 4712 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4713 if (RowR.isInvalid()) 4714 return RowR; 4715 RowIdx = RowR.get(); 4716 4717 if (!ColumnIdx) 4718 return new (Context) MatrixSubscriptExpr( 4719 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4720 4721 // Build an unanalyzed expression if any of the operands is type-dependent. 4722 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4723 ColumnIdx->isTypeDependent()) 4724 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4725 Context.DependentTy, RBLoc); 4726 4727 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4728 if (ColumnR.isInvalid()) 4729 return ColumnR; 4730 ColumnIdx = ColumnR.get(); 4731 4732 // Check that IndexExpr is an integer expression. If it is a constant 4733 // expression, check that it is less than Dim (= the number of elements in the 4734 // corresponding dimension). 4735 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4736 bool IsColumnIdx) -> Expr * { 4737 if (!IndexExpr->getType()->isIntegerType() && 4738 !IndexExpr->isTypeDependent()) { 4739 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4740 << IsColumnIdx; 4741 return nullptr; 4742 } 4743 4744 if (Optional<llvm::APSInt> Idx = 4745 IndexExpr->getIntegerConstantExpr(Context)) { 4746 if ((*Idx < 0 || *Idx >= Dim)) { 4747 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4748 << IsColumnIdx << Dim; 4749 return nullptr; 4750 } 4751 } 4752 4753 ExprResult ConvExpr = 4754 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4755 assert(!ConvExpr.isInvalid() && 4756 "should be able to convert any integer type to size type"); 4757 return ConvExpr.get(); 4758 }; 4759 4760 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4761 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4762 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4763 if (!RowIdx || !ColumnIdx) 4764 return ExprError(); 4765 4766 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4767 MTy->getElementType(), RBLoc); 4768 } 4769 4770 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4771 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4772 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4773 4774 // For expressions like `&(*s).b`, the base is recorded and what should be 4775 // checked. 4776 const MemberExpr *Member = nullptr; 4777 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4778 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4779 4780 LastRecord.PossibleDerefs.erase(StrippedExpr); 4781 } 4782 4783 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4784 QualType ResultTy = E->getType(); 4785 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4786 4787 // Bail if the element is an array since it is not memory access. 4788 if (isa<ArrayType>(ResultTy)) 4789 return; 4790 4791 if (ResultTy->hasAttr(attr::NoDeref)) { 4792 LastRecord.PossibleDerefs.insert(E); 4793 return; 4794 } 4795 4796 // Check if the base type is a pointer to a member access of a struct 4797 // marked with noderef. 4798 const Expr *Base = E->getBase(); 4799 QualType BaseTy = Base->getType(); 4800 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4801 // Not a pointer access 4802 return; 4803 4804 const MemberExpr *Member = nullptr; 4805 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4806 Member->isArrow()) 4807 Base = Member->getBase(); 4808 4809 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4810 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4811 LastRecord.PossibleDerefs.insert(E); 4812 } 4813 } 4814 4815 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4816 Expr *LowerBound, 4817 SourceLocation ColonLocFirst, 4818 SourceLocation ColonLocSecond, 4819 Expr *Length, Expr *Stride, 4820 SourceLocation RBLoc) { 4821 if (Base->getType()->isPlaceholderType() && 4822 !Base->getType()->isSpecificPlaceholderType( 4823 BuiltinType::OMPArraySection)) { 4824 ExprResult Result = CheckPlaceholderExpr(Base); 4825 if (Result.isInvalid()) 4826 return ExprError(); 4827 Base = Result.get(); 4828 } 4829 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4830 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4831 if (Result.isInvalid()) 4832 return ExprError(); 4833 Result = DefaultLvalueConversion(Result.get()); 4834 if (Result.isInvalid()) 4835 return ExprError(); 4836 LowerBound = Result.get(); 4837 } 4838 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4839 ExprResult Result = CheckPlaceholderExpr(Length); 4840 if (Result.isInvalid()) 4841 return ExprError(); 4842 Result = DefaultLvalueConversion(Result.get()); 4843 if (Result.isInvalid()) 4844 return ExprError(); 4845 Length = Result.get(); 4846 } 4847 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4848 ExprResult Result = CheckPlaceholderExpr(Stride); 4849 if (Result.isInvalid()) 4850 return ExprError(); 4851 Result = DefaultLvalueConversion(Result.get()); 4852 if (Result.isInvalid()) 4853 return ExprError(); 4854 Stride = Result.get(); 4855 } 4856 4857 // Build an unanalyzed expression if either operand is type-dependent. 4858 if (Base->isTypeDependent() || 4859 (LowerBound && 4860 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4861 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4862 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4863 return new (Context) OMPArraySectionExpr( 4864 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4865 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4866 } 4867 4868 // Perform default conversions. 4869 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4870 QualType ResultTy; 4871 if (OriginalTy->isAnyPointerType()) { 4872 ResultTy = OriginalTy->getPointeeType(); 4873 } else if (OriginalTy->isArrayType()) { 4874 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4875 } else { 4876 return ExprError( 4877 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4878 << Base->getSourceRange()); 4879 } 4880 // C99 6.5.2.1p1 4881 if (LowerBound) { 4882 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4883 LowerBound); 4884 if (Res.isInvalid()) 4885 return ExprError(Diag(LowerBound->getExprLoc(), 4886 diag::err_omp_typecheck_section_not_integer) 4887 << 0 << LowerBound->getSourceRange()); 4888 LowerBound = Res.get(); 4889 4890 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4891 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4892 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4893 << 0 << LowerBound->getSourceRange(); 4894 } 4895 if (Length) { 4896 auto Res = 4897 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4898 if (Res.isInvalid()) 4899 return ExprError(Diag(Length->getExprLoc(), 4900 diag::err_omp_typecheck_section_not_integer) 4901 << 1 << Length->getSourceRange()); 4902 Length = Res.get(); 4903 4904 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4905 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4906 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4907 << 1 << Length->getSourceRange(); 4908 } 4909 if (Stride) { 4910 ExprResult Res = 4911 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4912 if (Res.isInvalid()) 4913 return ExprError(Diag(Stride->getExprLoc(), 4914 diag::err_omp_typecheck_section_not_integer) 4915 << 1 << Stride->getSourceRange()); 4916 Stride = Res.get(); 4917 4918 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4919 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4920 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4921 << 1 << Stride->getSourceRange(); 4922 } 4923 4924 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4925 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4926 // type. Note that functions are not objects, and that (in C99 parlance) 4927 // incomplete types are not object types. 4928 if (ResultTy->isFunctionType()) { 4929 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4930 << ResultTy << Base->getSourceRange(); 4931 return ExprError(); 4932 } 4933 4934 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4935 diag::err_omp_section_incomplete_type, Base)) 4936 return ExprError(); 4937 4938 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4939 Expr::EvalResult Result; 4940 if (LowerBound->EvaluateAsInt(Result, Context)) { 4941 // OpenMP 5.0, [2.1.5 Array Sections] 4942 // The array section must be a subset of the original array. 4943 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4944 if (LowerBoundValue.isNegative()) { 4945 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4946 << LowerBound->getSourceRange(); 4947 return ExprError(); 4948 } 4949 } 4950 } 4951 4952 if (Length) { 4953 Expr::EvalResult Result; 4954 if (Length->EvaluateAsInt(Result, Context)) { 4955 // OpenMP 5.0, [2.1.5 Array Sections] 4956 // The length must evaluate to non-negative integers. 4957 llvm::APSInt LengthValue = Result.Val.getInt(); 4958 if (LengthValue.isNegative()) { 4959 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4960 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4961 << Length->getSourceRange(); 4962 return ExprError(); 4963 } 4964 } 4965 } else if (ColonLocFirst.isValid() && 4966 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4967 !OriginalTy->isVariableArrayType()))) { 4968 // OpenMP 5.0, [2.1.5 Array Sections] 4969 // When the size of the array dimension is not known, the length must be 4970 // specified explicitly. 4971 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 4972 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4973 return ExprError(); 4974 } 4975 4976 if (Stride) { 4977 Expr::EvalResult Result; 4978 if (Stride->EvaluateAsInt(Result, Context)) { 4979 // OpenMP 5.0, [2.1.5 Array Sections] 4980 // The stride must evaluate to a positive integer. 4981 llvm::APSInt StrideValue = Result.Val.getInt(); 4982 if (!StrideValue.isStrictlyPositive()) { 4983 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 4984 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 4985 << Stride->getSourceRange(); 4986 return ExprError(); 4987 } 4988 } 4989 } 4990 4991 if (!Base->getType()->isSpecificPlaceholderType( 4992 BuiltinType::OMPArraySection)) { 4993 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4994 if (Result.isInvalid()) 4995 return ExprError(); 4996 Base = Result.get(); 4997 } 4998 return new (Context) OMPArraySectionExpr( 4999 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5000 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5001 } 5002 5003 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5004 SourceLocation RParenLoc, 5005 ArrayRef<Expr *> Dims, 5006 ArrayRef<SourceRange> Brackets) { 5007 if (Base->getType()->isPlaceholderType()) { 5008 ExprResult Result = CheckPlaceholderExpr(Base); 5009 if (Result.isInvalid()) 5010 return ExprError(); 5011 Result = DefaultLvalueConversion(Result.get()); 5012 if (Result.isInvalid()) 5013 return ExprError(); 5014 Base = Result.get(); 5015 } 5016 QualType BaseTy = Base->getType(); 5017 // Delay analysis of the types/expressions if instantiation/specialization is 5018 // required. 5019 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5020 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5021 LParenLoc, RParenLoc, Dims, Brackets); 5022 if (!BaseTy->isPointerType() || 5023 (!Base->isTypeDependent() && 5024 BaseTy->getPointeeType()->isIncompleteType())) 5025 return ExprError(Diag(Base->getExprLoc(), 5026 diag::err_omp_non_pointer_type_array_shaping_base) 5027 << Base->getSourceRange()); 5028 5029 SmallVector<Expr *, 4> NewDims; 5030 bool ErrorFound = false; 5031 for (Expr *Dim : Dims) { 5032 if (Dim->getType()->isPlaceholderType()) { 5033 ExprResult Result = CheckPlaceholderExpr(Dim); 5034 if (Result.isInvalid()) { 5035 ErrorFound = true; 5036 continue; 5037 } 5038 Result = DefaultLvalueConversion(Result.get()); 5039 if (Result.isInvalid()) { 5040 ErrorFound = true; 5041 continue; 5042 } 5043 Dim = Result.get(); 5044 } 5045 if (!Dim->isTypeDependent()) { 5046 ExprResult Result = 5047 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5048 if (Result.isInvalid()) { 5049 ErrorFound = true; 5050 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5051 << Dim->getSourceRange(); 5052 continue; 5053 } 5054 Dim = Result.get(); 5055 Expr::EvalResult EvResult; 5056 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5057 // OpenMP 5.0, [2.1.4 Array Shaping] 5058 // Each si is an integral type expression that must evaluate to a 5059 // positive integer. 5060 llvm::APSInt Value = EvResult.Val.getInt(); 5061 if (!Value.isStrictlyPositive()) { 5062 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5063 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5064 << Dim->getSourceRange(); 5065 ErrorFound = true; 5066 continue; 5067 } 5068 } 5069 } 5070 NewDims.push_back(Dim); 5071 } 5072 if (ErrorFound) 5073 return ExprError(); 5074 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5075 LParenLoc, RParenLoc, NewDims, Brackets); 5076 } 5077 5078 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5079 SourceLocation LLoc, SourceLocation RLoc, 5080 ArrayRef<OMPIteratorData> Data) { 5081 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5082 bool IsCorrect = true; 5083 for (const OMPIteratorData &D : Data) { 5084 TypeSourceInfo *TInfo = nullptr; 5085 SourceLocation StartLoc; 5086 QualType DeclTy; 5087 if (!D.Type.getAsOpaquePtr()) { 5088 // OpenMP 5.0, 2.1.6 Iterators 5089 // In an iterator-specifier, if the iterator-type is not specified then 5090 // the type of that iterator is of int type. 5091 DeclTy = Context.IntTy; 5092 StartLoc = D.DeclIdentLoc; 5093 } else { 5094 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5095 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5096 } 5097 5098 bool IsDeclTyDependent = DeclTy->isDependentType() || 5099 DeclTy->containsUnexpandedParameterPack() || 5100 DeclTy->isInstantiationDependentType(); 5101 if (!IsDeclTyDependent) { 5102 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5103 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5104 // The iterator-type must be an integral or pointer type. 5105 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5106 << DeclTy; 5107 IsCorrect = false; 5108 continue; 5109 } 5110 if (DeclTy.isConstant(Context)) { 5111 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5112 // The iterator-type must not be const qualified. 5113 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5114 << DeclTy; 5115 IsCorrect = false; 5116 continue; 5117 } 5118 } 5119 5120 // Iterator declaration. 5121 assert(D.DeclIdent && "Identifier expected."); 5122 // Always try to create iterator declarator to avoid extra error messages 5123 // about unknown declarations use. 5124 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5125 D.DeclIdent, DeclTy, TInfo, SC_None); 5126 VD->setImplicit(); 5127 if (S) { 5128 // Check for conflicting previous declaration. 5129 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5130 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5131 ForVisibleRedeclaration); 5132 Previous.suppressDiagnostics(); 5133 LookupName(Previous, S); 5134 5135 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5136 /*AllowInlineNamespace=*/false); 5137 if (!Previous.empty()) { 5138 NamedDecl *Old = Previous.getRepresentativeDecl(); 5139 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5140 Diag(Old->getLocation(), diag::note_previous_definition); 5141 } else { 5142 PushOnScopeChains(VD, S); 5143 } 5144 } else { 5145 CurContext->addDecl(VD); 5146 } 5147 Expr *Begin = D.Range.Begin; 5148 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5149 ExprResult BeginRes = 5150 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5151 Begin = BeginRes.get(); 5152 } 5153 Expr *End = D.Range.End; 5154 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5155 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5156 End = EndRes.get(); 5157 } 5158 Expr *Step = D.Range.Step; 5159 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5160 if (!Step->getType()->isIntegralType(Context)) { 5161 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5162 << Step << Step->getSourceRange(); 5163 IsCorrect = false; 5164 continue; 5165 } 5166 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5167 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5168 // If the step expression of a range-specification equals zero, the 5169 // behavior is unspecified. 5170 if (Result && Result->isNullValue()) { 5171 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5172 << Step << Step->getSourceRange(); 5173 IsCorrect = false; 5174 continue; 5175 } 5176 } 5177 if (!Begin || !End || !IsCorrect) { 5178 IsCorrect = false; 5179 continue; 5180 } 5181 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5182 IDElem.IteratorDecl = VD; 5183 IDElem.AssignmentLoc = D.AssignLoc; 5184 IDElem.Range.Begin = Begin; 5185 IDElem.Range.End = End; 5186 IDElem.Range.Step = Step; 5187 IDElem.ColonLoc = D.ColonLoc; 5188 IDElem.SecondColonLoc = D.SecColonLoc; 5189 } 5190 if (!IsCorrect) { 5191 // Invalidate all created iterator declarations if error is found. 5192 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5193 if (Decl *ID = D.IteratorDecl) 5194 ID->setInvalidDecl(); 5195 } 5196 return ExprError(); 5197 } 5198 SmallVector<OMPIteratorHelperData, 4> Helpers; 5199 if (!CurContext->isDependentContext()) { 5200 // Build number of ityeration for each iteration range. 5201 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5202 // ((Begini-Stepi-1-Endi) / -Stepi); 5203 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5204 // (Endi - Begini) 5205 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5206 D.Range.Begin); 5207 if(!Res.isUsable()) { 5208 IsCorrect = false; 5209 continue; 5210 } 5211 ExprResult St, St1; 5212 if (D.Range.Step) { 5213 St = D.Range.Step; 5214 // (Endi - Begini) + Stepi 5215 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5216 if (!Res.isUsable()) { 5217 IsCorrect = false; 5218 continue; 5219 } 5220 // (Endi - Begini) + Stepi - 1 5221 Res = 5222 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5223 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5224 if (!Res.isUsable()) { 5225 IsCorrect = false; 5226 continue; 5227 } 5228 // ((Endi - Begini) + Stepi - 1) / Stepi 5229 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5230 if (!Res.isUsable()) { 5231 IsCorrect = false; 5232 continue; 5233 } 5234 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5235 // (Begini - Endi) 5236 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5237 D.Range.Begin, D.Range.End); 5238 if (!Res1.isUsable()) { 5239 IsCorrect = false; 5240 continue; 5241 } 5242 // (Begini - Endi) - Stepi 5243 Res1 = 5244 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5245 if (!Res1.isUsable()) { 5246 IsCorrect = false; 5247 continue; 5248 } 5249 // (Begini - Endi) - Stepi - 1 5250 Res1 = 5251 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5252 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5253 if (!Res1.isUsable()) { 5254 IsCorrect = false; 5255 continue; 5256 } 5257 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5258 Res1 = 5259 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5260 if (!Res1.isUsable()) { 5261 IsCorrect = false; 5262 continue; 5263 } 5264 // Stepi > 0. 5265 ExprResult CmpRes = 5266 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5267 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5268 if (!CmpRes.isUsable()) { 5269 IsCorrect = false; 5270 continue; 5271 } 5272 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5273 Res.get(), Res1.get()); 5274 if (!Res.isUsable()) { 5275 IsCorrect = false; 5276 continue; 5277 } 5278 } 5279 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5280 if (!Res.isUsable()) { 5281 IsCorrect = false; 5282 continue; 5283 } 5284 5285 // Build counter update. 5286 // Build counter. 5287 auto *CounterVD = 5288 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5289 D.IteratorDecl->getBeginLoc(), nullptr, 5290 Res.get()->getType(), nullptr, SC_None); 5291 CounterVD->setImplicit(); 5292 ExprResult RefRes = 5293 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5294 D.IteratorDecl->getBeginLoc()); 5295 // Build counter update. 5296 // I = Begini + counter * Stepi; 5297 ExprResult UpdateRes; 5298 if (D.Range.Step) { 5299 UpdateRes = CreateBuiltinBinOp( 5300 D.AssignmentLoc, BO_Mul, 5301 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5302 } else { 5303 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5304 } 5305 if (!UpdateRes.isUsable()) { 5306 IsCorrect = false; 5307 continue; 5308 } 5309 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5310 UpdateRes.get()); 5311 if (!UpdateRes.isUsable()) { 5312 IsCorrect = false; 5313 continue; 5314 } 5315 ExprResult VDRes = 5316 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5317 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5318 D.IteratorDecl->getBeginLoc()); 5319 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5320 UpdateRes.get()); 5321 if (!UpdateRes.isUsable()) { 5322 IsCorrect = false; 5323 continue; 5324 } 5325 UpdateRes = 5326 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5327 if (!UpdateRes.isUsable()) { 5328 IsCorrect = false; 5329 continue; 5330 } 5331 ExprResult CounterUpdateRes = 5332 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5333 if (!CounterUpdateRes.isUsable()) { 5334 IsCorrect = false; 5335 continue; 5336 } 5337 CounterUpdateRes = 5338 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5339 if (!CounterUpdateRes.isUsable()) { 5340 IsCorrect = false; 5341 continue; 5342 } 5343 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5344 HD.CounterVD = CounterVD; 5345 HD.Upper = Res.get(); 5346 HD.Update = UpdateRes.get(); 5347 HD.CounterUpdate = CounterUpdateRes.get(); 5348 } 5349 } else { 5350 Helpers.assign(ID.size(), {}); 5351 } 5352 if (!IsCorrect) { 5353 // Invalidate all created iterator declarations if error is found. 5354 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5355 if (Decl *ID = D.IteratorDecl) 5356 ID->setInvalidDecl(); 5357 } 5358 return ExprError(); 5359 } 5360 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5361 LLoc, RLoc, ID, Helpers); 5362 } 5363 5364 ExprResult 5365 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5366 Expr *Idx, SourceLocation RLoc) { 5367 Expr *LHSExp = Base; 5368 Expr *RHSExp = Idx; 5369 5370 ExprValueKind VK = VK_LValue; 5371 ExprObjectKind OK = OK_Ordinary; 5372 5373 // Per C++ core issue 1213, the result is an xvalue if either operand is 5374 // a non-lvalue array, and an lvalue otherwise. 5375 if (getLangOpts().CPlusPlus11) { 5376 for (auto *Op : {LHSExp, RHSExp}) { 5377 Op = Op->IgnoreImplicit(); 5378 if (Op->getType()->isArrayType() && !Op->isLValue()) 5379 VK = VK_XValue; 5380 } 5381 } 5382 5383 // Perform default conversions. 5384 if (!LHSExp->getType()->getAs<VectorType>()) { 5385 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5386 if (Result.isInvalid()) 5387 return ExprError(); 5388 LHSExp = Result.get(); 5389 } 5390 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5391 if (Result.isInvalid()) 5392 return ExprError(); 5393 RHSExp = Result.get(); 5394 5395 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5396 5397 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5398 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5399 // in the subscript position. As a result, we need to derive the array base 5400 // and index from the expression types. 5401 Expr *BaseExpr, *IndexExpr; 5402 QualType ResultType; 5403 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5404 BaseExpr = LHSExp; 5405 IndexExpr = RHSExp; 5406 ResultType = Context.DependentTy; 5407 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5408 BaseExpr = LHSExp; 5409 IndexExpr = RHSExp; 5410 ResultType = PTy->getPointeeType(); 5411 } else if (const ObjCObjectPointerType *PTy = 5412 LHSTy->getAs<ObjCObjectPointerType>()) { 5413 BaseExpr = LHSExp; 5414 IndexExpr = RHSExp; 5415 5416 // Use custom logic if this should be the pseudo-object subscript 5417 // expression. 5418 if (!LangOpts.isSubscriptPointerArithmetic()) 5419 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5420 nullptr); 5421 5422 ResultType = PTy->getPointeeType(); 5423 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5424 // Handle the uncommon case of "123[Ptr]". 5425 BaseExpr = RHSExp; 5426 IndexExpr = LHSExp; 5427 ResultType = PTy->getPointeeType(); 5428 } else if (const ObjCObjectPointerType *PTy = 5429 RHSTy->getAs<ObjCObjectPointerType>()) { 5430 // Handle the uncommon case of "123[Ptr]". 5431 BaseExpr = RHSExp; 5432 IndexExpr = LHSExp; 5433 ResultType = PTy->getPointeeType(); 5434 if (!LangOpts.isSubscriptPointerArithmetic()) { 5435 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5436 << ResultType << BaseExpr->getSourceRange(); 5437 return ExprError(); 5438 } 5439 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5440 BaseExpr = LHSExp; // vectors: V[123] 5441 IndexExpr = RHSExp; 5442 // We apply C++ DR1213 to vector subscripting too. 5443 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5444 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5445 if (Materialized.isInvalid()) 5446 return ExprError(); 5447 LHSExp = Materialized.get(); 5448 } 5449 VK = LHSExp->getValueKind(); 5450 if (VK != VK_RValue) 5451 OK = OK_VectorComponent; 5452 5453 ResultType = VTy->getElementType(); 5454 QualType BaseType = BaseExpr->getType(); 5455 Qualifiers BaseQuals = BaseType.getQualifiers(); 5456 Qualifiers MemberQuals = ResultType.getQualifiers(); 5457 Qualifiers Combined = BaseQuals + MemberQuals; 5458 if (Combined != MemberQuals) 5459 ResultType = Context.getQualifiedType(ResultType, Combined); 5460 } else if (LHSTy->isArrayType()) { 5461 // If we see an array that wasn't promoted by 5462 // DefaultFunctionArrayLvalueConversion, it must be an array that 5463 // wasn't promoted because of the C90 rule that doesn't 5464 // allow promoting non-lvalue arrays. Warn, then 5465 // force the promotion here. 5466 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5467 << LHSExp->getSourceRange(); 5468 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5469 CK_ArrayToPointerDecay).get(); 5470 LHSTy = LHSExp->getType(); 5471 5472 BaseExpr = LHSExp; 5473 IndexExpr = RHSExp; 5474 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5475 } else if (RHSTy->isArrayType()) { 5476 // Same as previous, except for 123[f().a] case 5477 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5478 << RHSExp->getSourceRange(); 5479 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5480 CK_ArrayToPointerDecay).get(); 5481 RHSTy = RHSExp->getType(); 5482 5483 BaseExpr = RHSExp; 5484 IndexExpr = LHSExp; 5485 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5486 } else { 5487 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5488 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5489 } 5490 // C99 6.5.2.1p1 5491 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5492 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5493 << IndexExpr->getSourceRange()); 5494 5495 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5496 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5497 && !IndexExpr->isTypeDependent()) 5498 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5499 5500 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5501 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5502 // type. Note that Functions are not objects, and that (in C99 parlance) 5503 // incomplete types are not object types. 5504 if (ResultType->isFunctionType()) { 5505 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5506 << ResultType << BaseExpr->getSourceRange(); 5507 return ExprError(); 5508 } 5509 5510 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5511 // GNU extension: subscripting on pointer to void 5512 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5513 << BaseExpr->getSourceRange(); 5514 5515 // C forbids expressions of unqualified void type from being l-values. 5516 // See IsCForbiddenLValueType. 5517 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5518 } else if (!ResultType->isDependentType() && 5519 RequireCompleteSizedType( 5520 LLoc, ResultType, 5521 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5522 return ExprError(); 5523 5524 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5525 !ResultType.isCForbiddenLValueType()); 5526 5527 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5528 FunctionScopes.size() > 1) { 5529 if (auto *TT = 5530 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5531 for (auto I = FunctionScopes.rbegin(), 5532 E = std::prev(FunctionScopes.rend()); 5533 I != E; ++I) { 5534 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5535 if (CSI == nullptr) 5536 break; 5537 DeclContext *DC = nullptr; 5538 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5539 DC = LSI->CallOperator; 5540 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5541 DC = CRSI->TheCapturedDecl; 5542 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5543 DC = BSI->TheDecl; 5544 if (DC) { 5545 if (DC->containsDecl(TT->getDecl())) 5546 break; 5547 captureVariablyModifiedType( 5548 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5549 } 5550 } 5551 } 5552 } 5553 5554 return new (Context) 5555 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5556 } 5557 5558 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5559 ParmVarDecl *Param) { 5560 if (Param->hasUnparsedDefaultArg()) { 5561 // If we've already cleared out the location for the default argument, 5562 // that means we're parsing it right now. 5563 if (!UnparsedDefaultArgLocs.count(Param)) { 5564 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5565 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5566 Param->setInvalidDecl(); 5567 return true; 5568 } 5569 5570 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5571 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5572 Diag(UnparsedDefaultArgLocs[Param], 5573 diag::note_default_argument_declared_here); 5574 return true; 5575 } 5576 5577 if (Param->hasUninstantiatedDefaultArg() && 5578 InstantiateDefaultArgument(CallLoc, FD, Param)) 5579 return true; 5580 5581 assert(Param->hasInit() && "default argument but no initializer?"); 5582 5583 // If the default expression creates temporaries, we need to 5584 // push them to the current stack of expression temporaries so they'll 5585 // be properly destroyed. 5586 // FIXME: We should really be rebuilding the default argument with new 5587 // bound temporaries; see the comment in PR5810. 5588 // We don't need to do that with block decls, though, because 5589 // blocks in default argument expression can never capture anything. 5590 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5591 // Set the "needs cleanups" bit regardless of whether there are 5592 // any explicit objects. 5593 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5594 5595 // Append all the objects to the cleanup list. Right now, this 5596 // should always be a no-op, because blocks in default argument 5597 // expressions should never be able to capture anything. 5598 assert(!Init->getNumObjects() && 5599 "default argument expression has capturing blocks?"); 5600 } 5601 5602 // We already type-checked the argument, so we know it works. 5603 // Just mark all of the declarations in this potentially-evaluated expression 5604 // as being "referenced". 5605 EnterExpressionEvaluationContext EvalContext( 5606 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5607 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5608 /*SkipLocalVariables=*/true); 5609 return false; 5610 } 5611 5612 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5613 FunctionDecl *FD, ParmVarDecl *Param) { 5614 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5615 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5616 return ExprError(); 5617 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5618 } 5619 5620 Sema::VariadicCallType 5621 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5622 Expr *Fn) { 5623 if (Proto && Proto->isVariadic()) { 5624 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5625 return VariadicConstructor; 5626 else if (Fn && Fn->getType()->isBlockPointerType()) 5627 return VariadicBlock; 5628 else if (FDecl) { 5629 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5630 if (Method->isInstance()) 5631 return VariadicMethod; 5632 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5633 return VariadicMethod; 5634 return VariadicFunction; 5635 } 5636 return VariadicDoesNotApply; 5637 } 5638 5639 namespace { 5640 class FunctionCallCCC final : public FunctionCallFilterCCC { 5641 public: 5642 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5643 unsigned NumArgs, MemberExpr *ME) 5644 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5645 FunctionName(FuncName) {} 5646 5647 bool ValidateCandidate(const TypoCorrection &candidate) override { 5648 if (!candidate.getCorrectionSpecifier() || 5649 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5650 return false; 5651 } 5652 5653 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5654 } 5655 5656 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5657 return std::make_unique<FunctionCallCCC>(*this); 5658 } 5659 5660 private: 5661 const IdentifierInfo *const FunctionName; 5662 }; 5663 } 5664 5665 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5666 FunctionDecl *FDecl, 5667 ArrayRef<Expr *> Args) { 5668 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5669 DeclarationName FuncName = FDecl->getDeclName(); 5670 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5671 5672 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5673 if (TypoCorrection Corrected = S.CorrectTypo( 5674 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5675 S.getScopeForContext(S.CurContext), nullptr, CCC, 5676 Sema::CTK_ErrorRecovery)) { 5677 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5678 if (Corrected.isOverloaded()) { 5679 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5680 OverloadCandidateSet::iterator Best; 5681 for (NamedDecl *CD : Corrected) { 5682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5683 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5684 OCS); 5685 } 5686 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5687 case OR_Success: 5688 ND = Best->FoundDecl; 5689 Corrected.setCorrectionDecl(ND); 5690 break; 5691 default: 5692 break; 5693 } 5694 } 5695 ND = ND->getUnderlyingDecl(); 5696 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5697 return Corrected; 5698 } 5699 } 5700 return TypoCorrection(); 5701 } 5702 5703 /// ConvertArgumentsForCall - Converts the arguments specified in 5704 /// Args/NumArgs to the parameter types of the function FDecl with 5705 /// function prototype Proto. Call is the call expression itself, and 5706 /// Fn is the function expression. For a C++ member function, this 5707 /// routine does not attempt to convert the object argument. Returns 5708 /// true if the call is ill-formed. 5709 bool 5710 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5711 FunctionDecl *FDecl, 5712 const FunctionProtoType *Proto, 5713 ArrayRef<Expr *> Args, 5714 SourceLocation RParenLoc, 5715 bool IsExecConfig) { 5716 // Bail out early if calling a builtin with custom typechecking. 5717 if (FDecl) 5718 if (unsigned ID = FDecl->getBuiltinID()) 5719 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5720 return false; 5721 5722 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5723 // assignment, to the types of the corresponding parameter, ... 5724 unsigned NumParams = Proto->getNumParams(); 5725 bool Invalid = false; 5726 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5727 unsigned FnKind = Fn->getType()->isBlockPointerType() 5728 ? 1 /* block */ 5729 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5730 : 0 /* function */); 5731 5732 // If too few arguments are available (and we don't have default 5733 // arguments for the remaining parameters), don't make the call. 5734 if (Args.size() < NumParams) { 5735 if (Args.size() < MinArgs) { 5736 TypoCorrection TC; 5737 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5738 unsigned diag_id = 5739 MinArgs == NumParams && !Proto->isVariadic() 5740 ? diag::err_typecheck_call_too_few_args_suggest 5741 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5742 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5743 << static_cast<unsigned>(Args.size()) 5744 << TC.getCorrectionRange()); 5745 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5746 Diag(RParenLoc, 5747 MinArgs == NumParams && !Proto->isVariadic() 5748 ? diag::err_typecheck_call_too_few_args_one 5749 : diag::err_typecheck_call_too_few_args_at_least_one) 5750 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5751 else 5752 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5753 ? diag::err_typecheck_call_too_few_args 5754 : diag::err_typecheck_call_too_few_args_at_least) 5755 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5756 << Fn->getSourceRange(); 5757 5758 // Emit the location of the prototype. 5759 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5760 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5761 5762 return true; 5763 } 5764 // We reserve space for the default arguments when we create 5765 // the call expression, before calling ConvertArgumentsForCall. 5766 assert((Call->getNumArgs() == NumParams) && 5767 "We should have reserved space for the default arguments before!"); 5768 } 5769 5770 // If too many are passed and not variadic, error on the extras and drop 5771 // them. 5772 if (Args.size() > NumParams) { 5773 if (!Proto->isVariadic()) { 5774 TypoCorrection TC; 5775 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5776 unsigned diag_id = 5777 MinArgs == NumParams && !Proto->isVariadic() 5778 ? diag::err_typecheck_call_too_many_args_suggest 5779 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5780 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5781 << static_cast<unsigned>(Args.size()) 5782 << TC.getCorrectionRange()); 5783 } else if (NumParams == 1 && FDecl && 5784 FDecl->getParamDecl(0)->getDeclName()) 5785 Diag(Args[NumParams]->getBeginLoc(), 5786 MinArgs == NumParams 5787 ? diag::err_typecheck_call_too_many_args_one 5788 : diag::err_typecheck_call_too_many_args_at_most_one) 5789 << FnKind << FDecl->getParamDecl(0) 5790 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5791 << SourceRange(Args[NumParams]->getBeginLoc(), 5792 Args.back()->getEndLoc()); 5793 else 5794 Diag(Args[NumParams]->getBeginLoc(), 5795 MinArgs == NumParams 5796 ? diag::err_typecheck_call_too_many_args 5797 : diag::err_typecheck_call_too_many_args_at_most) 5798 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5799 << Fn->getSourceRange() 5800 << SourceRange(Args[NumParams]->getBeginLoc(), 5801 Args.back()->getEndLoc()); 5802 5803 // Emit the location of the prototype. 5804 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5805 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5806 5807 // This deletes the extra arguments. 5808 Call->shrinkNumArgs(NumParams); 5809 return true; 5810 } 5811 } 5812 SmallVector<Expr *, 8> AllArgs; 5813 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5814 5815 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5816 AllArgs, CallType); 5817 if (Invalid) 5818 return true; 5819 unsigned TotalNumArgs = AllArgs.size(); 5820 for (unsigned i = 0; i < TotalNumArgs; ++i) 5821 Call->setArg(i, AllArgs[i]); 5822 5823 return false; 5824 } 5825 5826 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5827 const FunctionProtoType *Proto, 5828 unsigned FirstParam, ArrayRef<Expr *> Args, 5829 SmallVectorImpl<Expr *> &AllArgs, 5830 VariadicCallType CallType, bool AllowExplicit, 5831 bool IsListInitialization) { 5832 unsigned NumParams = Proto->getNumParams(); 5833 bool Invalid = false; 5834 size_t ArgIx = 0; 5835 // Continue to check argument types (even if we have too few/many args). 5836 for (unsigned i = FirstParam; i < NumParams; i++) { 5837 QualType ProtoArgType = Proto->getParamType(i); 5838 5839 Expr *Arg; 5840 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5841 if (ArgIx < Args.size()) { 5842 Arg = Args[ArgIx++]; 5843 5844 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5845 diag::err_call_incomplete_argument, Arg)) 5846 return true; 5847 5848 // Strip the unbridged-cast placeholder expression off, if applicable. 5849 bool CFAudited = false; 5850 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5851 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5852 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5853 Arg = stripARCUnbridgedCast(Arg); 5854 else if (getLangOpts().ObjCAutoRefCount && 5855 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5856 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5857 CFAudited = true; 5858 5859 if (Proto->getExtParameterInfo(i).isNoEscape()) 5860 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5861 BE->getBlockDecl()->setDoesNotEscape(); 5862 5863 InitializedEntity Entity = 5864 Param ? InitializedEntity::InitializeParameter(Context, Param, 5865 ProtoArgType) 5866 : InitializedEntity::InitializeParameter( 5867 Context, ProtoArgType, Proto->isParamConsumed(i)); 5868 5869 // Remember that parameter belongs to a CF audited API. 5870 if (CFAudited) 5871 Entity.setParameterCFAudited(); 5872 5873 ExprResult ArgE = PerformCopyInitialization( 5874 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5875 if (ArgE.isInvalid()) 5876 return true; 5877 5878 Arg = ArgE.getAs<Expr>(); 5879 } else { 5880 assert(Param && "can't use default arguments without a known callee"); 5881 5882 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5883 if (ArgExpr.isInvalid()) 5884 return true; 5885 5886 Arg = ArgExpr.getAs<Expr>(); 5887 } 5888 5889 // Check for array bounds violations for each argument to the call. This 5890 // check only triggers warnings when the argument isn't a more complex Expr 5891 // with its own checking, such as a BinaryOperator. 5892 CheckArrayAccess(Arg); 5893 5894 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5895 CheckStaticArrayArgument(CallLoc, Param, Arg); 5896 5897 AllArgs.push_back(Arg); 5898 } 5899 5900 // If this is a variadic call, handle args passed through "...". 5901 if (CallType != VariadicDoesNotApply) { 5902 // Assume that extern "C" functions with variadic arguments that 5903 // return __unknown_anytype aren't *really* variadic. 5904 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5905 FDecl->isExternC()) { 5906 for (Expr *A : Args.slice(ArgIx)) { 5907 QualType paramType; // ignored 5908 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5909 Invalid |= arg.isInvalid(); 5910 AllArgs.push_back(arg.get()); 5911 } 5912 5913 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5914 } else { 5915 for (Expr *A : Args.slice(ArgIx)) { 5916 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5917 Invalid |= Arg.isInvalid(); 5918 AllArgs.push_back(Arg.get()); 5919 } 5920 } 5921 5922 // Check for array bounds violations. 5923 for (Expr *A : Args.slice(ArgIx)) 5924 CheckArrayAccess(A); 5925 } 5926 return Invalid; 5927 } 5928 5929 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5930 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5931 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5932 TL = DTL.getOriginalLoc(); 5933 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5934 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5935 << ATL.getLocalSourceRange(); 5936 } 5937 5938 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5939 /// array parameter, check that it is non-null, and that if it is formed by 5940 /// array-to-pointer decay, the underlying array is sufficiently large. 5941 /// 5942 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5943 /// array type derivation, then for each call to the function, the value of the 5944 /// corresponding actual argument shall provide access to the first element of 5945 /// an array with at least as many elements as specified by the size expression. 5946 void 5947 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5948 ParmVarDecl *Param, 5949 const Expr *ArgExpr) { 5950 // Static array parameters are not supported in C++. 5951 if (!Param || getLangOpts().CPlusPlus) 5952 return; 5953 5954 QualType OrigTy = Param->getOriginalType(); 5955 5956 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5957 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5958 return; 5959 5960 if (ArgExpr->isNullPointerConstant(Context, 5961 Expr::NPC_NeverValueDependent)) { 5962 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5963 DiagnoseCalleeStaticArrayParam(*this, Param); 5964 return; 5965 } 5966 5967 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5968 if (!CAT) 5969 return; 5970 5971 const ConstantArrayType *ArgCAT = 5972 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5973 if (!ArgCAT) 5974 return; 5975 5976 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5977 ArgCAT->getElementType())) { 5978 if (ArgCAT->getSize().ult(CAT->getSize())) { 5979 Diag(CallLoc, diag::warn_static_array_too_small) 5980 << ArgExpr->getSourceRange() 5981 << (unsigned)ArgCAT->getSize().getZExtValue() 5982 << (unsigned)CAT->getSize().getZExtValue() << 0; 5983 DiagnoseCalleeStaticArrayParam(*this, Param); 5984 } 5985 return; 5986 } 5987 5988 Optional<CharUnits> ArgSize = 5989 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5990 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5991 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5992 Diag(CallLoc, diag::warn_static_array_too_small) 5993 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5994 << (unsigned)ParmSize->getQuantity() << 1; 5995 DiagnoseCalleeStaticArrayParam(*this, Param); 5996 } 5997 } 5998 5999 /// Given a function expression of unknown-any type, try to rebuild it 6000 /// to have a function type. 6001 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6002 6003 /// Is the given type a placeholder that we need to lower out 6004 /// immediately during argument processing? 6005 static bool isPlaceholderToRemoveAsArg(QualType type) { 6006 // Placeholders are never sugared. 6007 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6008 if (!placeholder) return false; 6009 6010 switch (placeholder->getKind()) { 6011 // Ignore all the non-placeholder types. 6012 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6013 case BuiltinType::Id: 6014 #include "clang/Basic/OpenCLImageTypes.def" 6015 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6016 case BuiltinType::Id: 6017 #include "clang/Basic/OpenCLExtensionTypes.def" 6018 // In practice we'll never use this, since all SVE types are sugared 6019 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6020 #define SVE_TYPE(Name, Id, SingletonId) \ 6021 case BuiltinType::Id: 6022 #include "clang/Basic/AArch64SVEACLETypes.def" 6023 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6024 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6025 #include "clang/AST/BuiltinTypes.def" 6026 return false; 6027 6028 // We cannot lower out overload sets; they might validly be resolved 6029 // by the call machinery. 6030 case BuiltinType::Overload: 6031 return false; 6032 6033 // Unbridged casts in ARC can be handled in some call positions and 6034 // should be left in place. 6035 case BuiltinType::ARCUnbridgedCast: 6036 return false; 6037 6038 // Pseudo-objects should be converted as soon as possible. 6039 case BuiltinType::PseudoObject: 6040 return true; 6041 6042 // The debugger mode could theoretically but currently does not try 6043 // to resolve unknown-typed arguments based on known parameter types. 6044 case BuiltinType::UnknownAny: 6045 return true; 6046 6047 // These are always invalid as call arguments and should be reported. 6048 case BuiltinType::BoundMember: 6049 case BuiltinType::BuiltinFn: 6050 case BuiltinType::IncompleteMatrixIdx: 6051 case BuiltinType::OMPArraySection: 6052 case BuiltinType::OMPArrayShaping: 6053 case BuiltinType::OMPIterator: 6054 return true; 6055 6056 } 6057 llvm_unreachable("bad builtin type kind"); 6058 } 6059 6060 /// Check an argument list for placeholders that we won't try to 6061 /// handle later. 6062 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6063 // Apply this processing to all the arguments at once instead of 6064 // dying at the first failure. 6065 bool hasInvalid = false; 6066 for (size_t i = 0, e = args.size(); i != e; i++) { 6067 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6068 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6069 if (result.isInvalid()) hasInvalid = true; 6070 else args[i] = result.get(); 6071 } else if (hasInvalid) { 6072 (void)S.CorrectDelayedTyposInExpr(args[i]); 6073 } 6074 } 6075 return hasInvalid; 6076 } 6077 6078 /// If a builtin function has a pointer argument with no explicit address 6079 /// space, then it should be able to accept a pointer to any address 6080 /// space as input. In order to do this, we need to replace the 6081 /// standard builtin declaration with one that uses the same address space 6082 /// as the call. 6083 /// 6084 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6085 /// it does not contain any pointer arguments without 6086 /// an address space qualifer. Otherwise the rewritten 6087 /// FunctionDecl is returned. 6088 /// TODO: Handle pointer return types. 6089 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6090 FunctionDecl *FDecl, 6091 MultiExprArg ArgExprs) { 6092 6093 QualType DeclType = FDecl->getType(); 6094 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6095 6096 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6097 ArgExprs.size() < FT->getNumParams()) 6098 return nullptr; 6099 6100 bool NeedsNewDecl = false; 6101 unsigned i = 0; 6102 SmallVector<QualType, 8> OverloadParams; 6103 6104 for (QualType ParamType : FT->param_types()) { 6105 6106 // Convert array arguments to pointer to simplify type lookup. 6107 ExprResult ArgRes = 6108 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6109 if (ArgRes.isInvalid()) 6110 return nullptr; 6111 Expr *Arg = ArgRes.get(); 6112 QualType ArgType = Arg->getType(); 6113 if (!ParamType->isPointerType() || 6114 ParamType.hasAddressSpace() || 6115 !ArgType->isPointerType() || 6116 !ArgType->getPointeeType().hasAddressSpace()) { 6117 OverloadParams.push_back(ParamType); 6118 continue; 6119 } 6120 6121 QualType PointeeType = ParamType->getPointeeType(); 6122 if (PointeeType.hasAddressSpace()) 6123 continue; 6124 6125 NeedsNewDecl = true; 6126 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6127 6128 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6129 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6130 } 6131 6132 if (!NeedsNewDecl) 6133 return nullptr; 6134 6135 FunctionProtoType::ExtProtoInfo EPI; 6136 EPI.Variadic = FT->isVariadic(); 6137 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6138 OverloadParams, EPI); 6139 DeclContext *Parent = FDecl->getParent(); 6140 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6141 FDecl->getLocation(), 6142 FDecl->getLocation(), 6143 FDecl->getIdentifier(), 6144 OverloadTy, 6145 /*TInfo=*/nullptr, 6146 SC_Extern, false, 6147 /*hasPrototype=*/true); 6148 SmallVector<ParmVarDecl*, 16> Params; 6149 FT = cast<FunctionProtoType>(OverloadTy); 6150 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6151 QualType ParamType = FT->getParamType(i); 6152 ParmVarDecl *Parm = 6153 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6154 SourceLocation(), nullptr, ParamType, 6155 /*TInfo=*/nullptr, SC_None, nullptr); 6156 Parm->setScopeInfo(0, i); 6157 Params.push_back(Parm); 6158 } 6159 OverloadDecl->setParams(Params); 6160 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6161 return OverloadDecl; 6162 } 6163 6164 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6165 FunctionDecl *Callee, 6166 MultiExprArg ArgExprs) { 6167 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6168 // similar attributes) really don't like it when functions are called with an 6169 // invalid number of args. 6170 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6171 /*PartialOverloading=*/false) && 6172 !Callee->isVariadic()) 6173 return; 6174 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6175 return; 6176 6177 if (const EnableIfAttr *Attr = 6178 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6179 S.Diag(Fn->getBeginLoc(), 6180 isa<CXXMethodDecl>(Callee) 6181 ? diag::err_ovl_no_viable_member_function_in_call 6182 : diag::err_ovl_no_viable_function_in_call) 6183 << Callee << Callee->getSourceRange(); 6184 S.Diag(Callee->getLocation(), 6185 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6186 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6187 return; 6188 } 6189 } 6190 6191 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6192 const UnresolvedMemberExpr *const UME, Sema &S) { 6193 6194 const auto GetFunctionLevelDCIfCXXClass = 6195 [](Sema &S) -> const CXXRecordDecl * { 6196 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6197 if (!DC || !DC->getParent()) 6198 return nullptr; 6199 6200 // If the call to some member function was made from within a member 6201 // function body 'M' return return 'M's parent. 6202 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6203 return MD->getParent()->getCanonicalDecl(); 6204 // else the call was made from within a default member initializer of a 6205 // class, so return the class. 6206 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6207 return RD->getCanonicalDecl(); 6208 return nullptr; 6209 }; 6210 // If our DeclContext is neither a member function nor a class (in the 6211 // case of a lambda in a default member initializer), we can't have an 6212 // enclosing 'this'. 6213 6214 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6215 if (!CurParentClass) 6216 return false; 6217 6218 // The naming class for implicit member functions call is the class in which 6219 // name lookup starts. 6220 const CXXRecordDecl *const NamingClass = 6221 UME->getNamingClass()->getCanonicalDecl(); 6222 assert(NamingClass && "Must have naming class even for implicit access"); 6223 6224 // If the unresolved member functions were found in a 'naming class' that is 6225 // related (either the same or derived from) to the class that contains the 6226 // member function that itself contained the implicit member access. 6227 6228 return CurParentClass == NamingClass || 6229 CurParentClass->isDerivedFrom(NamingClass); 6230 } 6231 6232 static void 6233 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6234 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6235 6236 if (!UME) 6237 return; 6238 6239 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6240 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6241 // already been captured, or if this is an implicit member function call (if 6242 // it isn't, an attempt to capture 'this' should already have been made). 6243 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6244 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6245 return; 6246 6247 // Check if the naming class in which the unresolved members were found is 6248 // related (same as or is a base of) to the enclosing class. 6249 6250 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6251 return; 6252 6253 6254 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6255 // If the enclosing function is not dependent, then this lambda is 6256 // capture ready, so if we can capture this, do so. 6257 if (!EnclosingFunctionCtx->isDependentContext()) { 6258 // If the current lambda and all enclosing lambdas can capture 'this' - 6259 // then go ahead and capture 'this' (since our unresolved overload set 6260 // contains at least one non-static member function). 6261 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6262 S.CheckCXXThisCapture(CallLoc); 6263 } else if (S.CurContext->isDependentContext()) { 6264 // ... since this is an implicit member reference, that might potentially 6265 // involve a 'this' capture, mark 'this' for potential capture in 6266 // enclosing lambdas. 6267 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6268 CurLSI->addPotentialThisCapture(CallLoc); 6269 } 6270 } 6271 6272 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6273 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6274 Expr *ExecConfig) { 6275 ExprResult Call = 6276 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6277 if (Call.isInvalid()) 6278 return Call; 6279 6280 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6281 // language modes. 6282 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6283 if (ULE->hasExplicitTemplateArgs() && 6284 ULE->decls_begin() == ULE->decls_end()) { 6285 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6286 ? diag::warn_cxx17_compat_adl_only_template_id 6287 : diag::ext_adl_only_template_id) 6288 << ULE->getName(); 6289 } 6290 } 6291 6292 if (LangOpts.OpenMP) 6293 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6294 ExecConfig); 6295 6296 return Call; 6297 } 6298 6299 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6300 /// This provides the location of the left/right parens and a list of comma 6301 /// locations. 6302 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6303 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6304 Expr *ExecConfig, bool IsExecConfig) { 6305 // Since this might be a postfix expression, get rid of ParenListExprs. 6306 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6307 if (Result.isInvalid()) return ExprError(); 6308 Fn = Result.get(); 6309 6310 if (checkArgsForPlaceholders(*this, ArgExprs)) 6311 return ExprError(); 6312 6313 if (getLangOpts().CPlusPlus) { 6314 // If this is a pseudo-destructor expression, build the call immediately. 6315 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6316 if (!ArgExprs.empty()) { 6317 // Pseudo-destructor calls should not have any arguments. 6318 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6319 << FixItHint::CreateRemoval( 6320 SourceRange(ArgExprs.front()->getBeginLoc(), 6321 ArgExprs.back()->getEndLoc())); 6322 } 6323 6324 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6325 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6326 } 6327 if (Fn->getType() == Context.PseudoObjectTy) { 6328 ExprResult result = CheckPlaceholderExpr(Fn); 6329 if (result.isInvalid()) return ExprError(); 6330 Fn = result.get(); 6331 } 6332 6333 // Determine whether this is a dependent call inside a C++ template, 6334 // in which case we won't do any semantic analysis now. 6335 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6336 if (ExecConfig) { 6337 return CUDAKernelCallExpr::Create( 6338 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6339 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6340 } else { 6341 6342 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6343 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6344 Fn->getBeginLoc()); 6345 6346 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6347 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6348 } 6349 } 6350 6351 // Determine whether this is a call to an object (C++ [over.call.object]). 6352 if (Fn->getType()->isRecordType()) 6353 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6354 RParenLoc); 6355 6356 if (Fn->getType() == Context.UnknownAnyTy) { 6357 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6358 if (result.isInvalid()) return ExprError(); 6359 Fn = result.get(); 6360 } 6361 6362 if (Fn->getType() == Context.BoundMemberTy) { 6363 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6364 RParenLoc); 6365 } 6366 } 6367 6368 // Check for overloaded calls. This can happen even in C due to extensions. 6369 if (Fn->getType() == Context.OverloadTy) { 6370 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6371 6372 // We aren't supposed to apply this logic if there's an '&' involved. 6373 if (!find.HasFormOfMemberPointer) { 6374 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6375 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6376 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6377 OverloadExpr *ovl = find.Expression; 6378 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6379 return BuildOverloadedCallExpr( 6380 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6381 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6382 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6383 RParenLoc); 6384 } 6385 } 6386 6387 // If we're directly calling a function, get the appropriate declaration. 6388 if (Fn->getType() == Context.UnknownAnyTy) { 6389 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6390 if (result.isInvalid()) return ExprError(); 6391 Fn = result.get(); 6392 } 6393 6394 Expr *NakedFn = Fn->IgnoreParens(); 6395 6396 bool CallingNDeclIndirectly = false; 6397 NamedDecl *NDecl = nullptr; 6398 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6399 if (UnOp->getOpcode() == UO_AddrOf) { 6400 CallingNDeclIndirectly = true; 6401 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6402 } 6403 } 6404 6405 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6406 NDecl = DRE->getDecl(); 6407 6408 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6409 if (FDecl && FDecl->getBuiltinID()) { 6410 // Rewrite the function decl for this builtin by replacing parameters 6411 // with no explicit address space with the address space of the arguments 6412 // in ArgExprs. 6413 if ((FDecl = 6414 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6415 NDecl = FDecl; 6416 Fn = DeclRefExpr::Create( 6417 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6418 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6419 nullptr, DRE->isNonOdrUse()); 6420 } 6421 } 6422 } else if (isa<MemberExpr>(NakedFn)) 6423 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6424 6425 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6426 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6427 FD, /*Complain=*/true, Fn->getBeginLoc())) 6428 return ExprError(); 6429 6430 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6431 return ExprError(); 6432 6433 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6434 } 6435 6436 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6437 ExecConfig, IsExecConfig); 6438 } 6439 6440 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6441 /// 6442 /// __builtin_astype( value, dst type ) 6443 /// 6444 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6445 SourceLocation BuiltinLoc, 6446 SourceLocation RParenLoc) { 6447 ExprValueKind VK = VK_RValue; 6448 ExprObjectKind OK = OK_Ordinary; 6449 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6450 QualType SrcTy = E->getType(); 6451 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6452 return ExprError(Diag(BuiltinLoc, 6453 diag::err_invalid_astype_of_different_size) 6454 << DstTy 6455 << SrcTy 6456 << E->getSourceRange()); 6457 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6458 } 6459 6460 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6461 /// provided arguments. 6462 /// 6463 /// __builtin_convertvector( value, dst type ) 6464 /// 6465 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6466 SourceLocation BuiltinLoc, 6467 SourceLocation RParenLoc) { 6468 TypeSourceInfo *TInfo; 6469 GetTypeFromParser(ParsedDestTy, &TInfo); 6470 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6471 } 6472 6473 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6474 /// i.e. an expression not of \p OverloadTy. The expression should 6475 /// unary-convert to an expression of function-pointer or 6476 /// block-pointer type. 6477 /// 6478 /// \param NDecl the declaration being called, if available 6479 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6480 SourceLocation LParenLoc, 6481 ArrayRef<Expr *> Args, 6482 SourceLocation RParenLoc, Expr *Config, 6483 bool IsExecConfig, ADLCallKind UsesADL) { 6484 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6485 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6486 6487 // Functions with 'interrupt' attribute cannot be called directly. 6488 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6489 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6490 return ExprError(); 6491 } 6492 6493 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6494 // so there's some risk when calling out to non-interrupt handler functions 6495 // that the callee might not preserve them. This is easy to diagnose here, 6496 // but can be very challenging to debug. 6497 if (auto *Caller = getCurFunctionDecl()) 6498 if (Caller->hasAttr<ARMInterruptAttr>()) { 6499 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6500 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6501 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6502 } 6503 6504 // Promote the function operand. 6505 // We special-case function promotion here because we only allow promoting 6506 // builtin functions to function pointers in the callee of a call. 6507 ExprResult Result; 6508 QualType ResultTy; 6509 if (BuiltinID && 6510 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6511 // Extract the return type from the (builtin) function pointer type. 6512 // FIXME Several builtins still have setType in 6513 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6514 // Builtins.def to ensure they are correct before removing setType calls. 6515 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6516 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6517 ResultTy = FDecl->getCallResultType(); 6518 } else { 6519 Result = CallExprUnaryConversions(Fn); 6520 ResultTy = Context.BoolTy; 6521 } 6522 if (Result.isInvalid()) 6523 return ExprError(); 6524 Fn = Result.get(); 6525 6526 // Check for a valid function type, but only if it is not a builtin which 6527 // requires custom type checking. These will be handled by 6528 // CheckBuiltinFunctionCall below just after creation of the call expression. 6529 const FunctionType *FuncT = nullptr; 6530 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6531 retry: 6532 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6533 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6534 // have type pointer to function". 6535 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6536 if (!FuncT) 6537 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6538 << Fn->getType() << Fn->getSourceRange()); 6539 } else if (const BlockPointerType *BPT = 6540 Fn->getType()->getAs<BlockPointerType>()) { 6541 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6542 } else { 6543 // Handle calls to expressions of unknown-any type. 6544 if (Fn->getType() == Context.UnknownAnyTy) { 6545 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6546 if (rewrite.isInvalid()) 6547 return ExprError(); 6548 Fn = rewrite.get(); 6549 goto retry; 6550 } 6551 6552 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6553 << Fn->getType() << Fn->getSourceRange()); 6554 } 6555 } 6556 6557 // Get the number of parameters in the function prototype, if any. 6558 // We will allocate space for max(Args.size(), NumParams) arguments 6559 // in the call expression. 6560 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6561 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6562 6563 CallExpr *TheCall; 6564 if (Config) { 6565 assert(UsesADL == ADLCallKind::NotADL && 6566 "CUDAKernelCallExpr should not use ADL"); 6567 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6568 Args, ResultTy, VK_RValue, RParenLoc, 6569 CurFPFeatureOverrides(), NumParams); 6570 } else { 6571 TheCall = 6572 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6573 CurFPFeatureOverrides(), NumParams, UsesADL); 6574 } 6575 6576 if (!getLangOpts().CPlusPlus) { 6577 // Forget about the nulled arguments since typo correction 6578 // do not handle them well. 6579 TheCall->shrinkNumArgs(Args.size()); 6580 // C cannot always handle TypoExpr nodes in builtin calls and direct 6581 // function calls as their argument checking don't necessarily handle 6582 // dependent types properly, so make sure any TypoExprs have been 6583 // dealt with. 6584 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6585 if (!Result.isUsable()) return ExprError(); 6586 CallExpr *TheOldCall = TheCall; 6587 TheCall = dyn_cast<CallExpr>(Result.get()); 6588 bool CorrectedTypos = TheCall != TheOldCall; 6589 if (!TheCall) return Result; 6590 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6591 6592 // A new call expression node was created if some typos were corrected. 6593 // However it may not have been constructed with enough storage. In this 6594 // case, rebuild the node with enough storage. The waste of space is 6595 // immaterial since this only happens when some typos were corrected. 6596 if (CorrectedTypos && Args.size() < NumParams) { 6597 if (Config) 6598 TheCall = CUDAKernelCallExpr::Create( 6599 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6600 RParenLoc, CurFPFeatureOverrides(), NumParams); 6601 else 6602 TheCall = 6603 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6604 CurFPFeatureOverrides(), NumParams, UsesADL); 6605 } 6606 // We can now handle the nulled arguments for the default arguments. 6607 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6608 } 6609 6610 // Bail out early if calling a builtin with custom type checking. 6611 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6612 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6613 6614 if (getLangOpts().CUDA) { 6615 if (Config) { 6616 // CUDA: Kernel calls must be to global functions 6617 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6618 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6619 << FDecl << Fn->getSourceRange()); 6620 6621 // CUDA: Kernel function must have 'void' return type 6622 if (!FuncT->getReturnType()->isVoidType() && 6623 !FuncT->getReturnType()->getAs<AutoType>() && 6624 !FuncT->getReturnType()->isInstantiationDependentType()) 6625 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6626 << Fn->getType() << Fn->getSourceRange()); 6627 } else { 6628 // CUDA: Calls to global functions must be configured 6629 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6630 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6631 << FDecl << Fn->getSourceRange()); 6632 } 6633 } 6634 6635 // Check for a valid return type 6636 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6637 FDecl)) 6638 return ExprError(); 6639 6640 // We know the result type of the call, set it. 6641 TheCall->setType(FuncT->getCallResultType(Context)); 6642 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6643 6644 if (Proto) { 6645 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6646 IsExecConfig)) 6647 return ExprError(); 6648 } else { 6649 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6650 6651 if (FDecl) { 6652 // Check if we have too few/too many template arguments, based 6653 // on our knowledge of the function definition. 6654 const FunctionDecl *Def = nullptr; 6655 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6656 Proto = Def->getType()->getAs<FunctionProtoType>(); 6657 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6658 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6659 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6660 } 6661 6662 // If the function we're calling isn't a function prototype, but we have 6663 // a function prototype from a prior declaratiom, use that prototype. 6664 if (!FDecl->hasPrototype()) 6665 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6666 } 6667 6668 // Promote the arguments (C99 6.5.2.2p6). 6669 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6670 Expr *Arg = Args[i]; 6671 6672 if (Proto && i < Proto->getNumParams()) { 6673 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6674 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6675 ExprResult ArgE = 6676 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6677 if (ArgE.isInvalid()) 6678 return true; 6679 6680 Arg = ArgE.getAs<Expr>(); 6681 6682 } else { 6683 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6684 6685 if (ArgE.isInvalid()) 6686 return true; 6687 6688 Arg = ArgE.getAs<Expr>(); 6689 } 6690 6691 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6692 diag::err_call_incomplete_argument, Arg)) 6693 return ExprError(); 6694 6695 TheCall->setArg(i, Arg); 6696 } 6697 } 6698 6699 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6700 if (!Method->isStatic()) 6701 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6702 << Fn->getSourceRange()); 6703 6704 // Check for sentinels 6705 if (NDecl) 6706 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6707 6708 // Warn for unions passing across security boundary (CMSE). 6709 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6710 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6711 if (const auto *RT = 6712 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6713 if (RT->getDecl()->isOrContainsUnion()) 6714 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6715 << 0 << i; 6716 } 6717 } 6718 } 6719 6720 // Do special checking on direct calls to functions. 6721 if (FDecl) { 6722 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6723 return ExprError(); 6724 6725 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6726 6727 if (BuiltinID) 6728 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6729 } else if (NDecl) { 6730 if (CheckPointerCall(NDecl, TheCall, Proto)) 6731 return ExprError(); 6732 } else { 6733 if (CheckOtherCall(TheCall, Proto)) 6734 return ExprError(); 6735 } 6736 6737 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6738 } 6739 6740 ExprResult 6741 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6742 SourceLocation RParenLoc, Expr *InitExpr) { 6743 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6744 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6745 6746 TypeSourceInfo *TInfo; 6747 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6748 if (!TInfo) 6749 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6750 6751 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6752 } 6753 6754 ExprResult 6755 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6756 SourceLocation RParenLoc, Expr *LiteralExpr) { 6757 QualType literalType = TInfo->getType(); 6758 6759 if (literalType->isArrayType()) { 6760 if (RequireCompleteSizedType( 6761 LParenLoc, Context.getBaseElementType(literalType), 6762 diag::err_array_incomplete_or_sizeless_type, 6763 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6764 return ExprError(); 6765 if (literalType->isVariableArrayType()) 6766 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6767 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6768 } else if (!literalType->isDependentType() && 6769 RequireCompleteType(LParenLoc, literalType, 6770 diag::err_typecheck_decl_incomplete_type, 6771 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6772 return ExprError(); 6773 6774 InitializedEntity Entity 6775 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6776 InitializationKind Kind 6777 = InitializationKind::CreateCStyleCast(LParenLoc, 6778 SourceRange(LParenLoc, RParenLoc), 6779 /*InitList=*/true); 6780 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6781 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6782 &literalType); 6783 if (Result.isInvalid()) 6784 return ExprError(); 6785 LiteralExpr = Result.get(); 6786 6787 bool isFileScope = !CurContext->isFunctionOrMethod(); 6788 6789 // In C, compound literals are l-values for some reason. 6790 // For GCC compatibility, in C++, file-scope array compound literals with 6791 // constant initializers are also l-values, and compound literals are 6792 // otherwise prvalues. 6793 // 6794 // (GCC also treats C++ list-initialized file-scope array prvalues with 6795 // constant initializers as l-values, but that's non-conforming, so we don't 6796 // follow it there.) 6797 // 6798 // FIXME: It would be better to handle the lvalue cases as materializing and 6799 // lifetime-extending a temporary object, but our materialized temporaries 6800 // representation only supports lifetime extension from a variable, not "out 6801 // of thin air". 6802 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6803 // is bound to the result of applying array-to-pointer decay to the compound 6804 // literal. 6805 // FIXME: GCC supports compound literals of reference type, which should 6806 // obviously have a value kind derived from the kind of reference involved. 6807 ExprValueKind VK = 6808 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6809 ? VK_RValue 6810 : VK_LValue; 6811 6812 if (isFileScope) 6813 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6814 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6815 Expr *Init = ILE->getInit(i); 6816 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6817 } 6818 6819 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6820 VK, LiteralExpr, isFileScope); 6821 if (isFileScope) { 6822 if (!LiteralExpr->isTypeDependent() && 6823 !LiteralExpr->isValueDependent() && 6824 !literalType->isDependentType()) // C99 6.5.2.5p3 6825 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6826 return ExprError(); 6827 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6828 literalType.getAddressSpace() != LangAS::Default) { 6829 // Embedded-C extensions to C99 6.5.2.5: 6830 // "If the compound literal occurs inside the body of a function, the 6831 // type name shall not be qualified by an address-space qualifier." 6832 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6833 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6834 return ExprError(); 6835 } 6836 6837 if (!isFileScope && !getLangOpts().CPlusPlus) { 6838 // Compound literals that have automatic storage duration are destroyed at 6839 // the end of the scope in C; in C++, they're just temporaries. 6840 6841 // Emit diagnostics if it is or contains a C union type that is non-trivial 6842 // to destruct. 6843 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6844 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6845 NTCUC_CompoundLiteral, NTCUK_Destruct); 6846 6847 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6848 if (literalType.isDestructedType()) { 6849 Cleanup.setExprNeedsCleanups(true); 6850 ExprCleanupObjects.push_back(E); 6851 getCurFunction()->setHasBranchProtectedScope(); 6852 } 6853 } 6854 6855 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6856 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6857 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6858 E->getInitializer()->getExprLoc()); 6859 6860 return MaybeBindToTemporary(E); 6861 } 6862 6863 ExprResult 6864 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6865 SourceLocation RBraceLoc) { 6866 // Only produce each kind of designated initialization diagnostic once. 6867 SourceLocation FirstDesignator; 6868 bool DiagnosedArrayDesignator = false; 6869 bool DiagnosedNestedDesignator = false; 6870 bool DiagnosedMixedDesignator = false; 6871 6872 // Check that any designated initializers are syntactically valid in the 6873 // current language mode. 6874 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6875 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6876 if (FirstDesignator.isInvalid()) 6877 FirstDesignator = DIE->getBeginLoc(); 6878 6879 if (!getLangOpts().CPlusPlus) 6880 break; 6881 6882 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6883 DiagnosedNestedDesignator = true; 6884 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6885 << DIE->getDesignatorsSourceRange(); 6886 } 6887 6888 for (auto &Desig : DIE->designators()) { 6889 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6890 DiagnosedArrayDesignator = true; 6891 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6892 << Desig.getSourceRange(); 6893 } 6894 } 6895 6896 if (!DiagnosedMixedDesignator && 6897 !isa<DesignatedInitExpr>(InitArgList[0])) { 6898 DiagnosedMixedDesignator = true; 6899 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6900 << DIE->getSourceRange(); 6901 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6902 << InitArgList[0]->getSourceRange(); 6903 } 6904 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6905 isa<DesignatedInitExpr>(InitArgList[0])) { 6906 DiagnosedMixedDesignator = true; 6907 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6908 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6909 << DIE->getSourceRange(); 6910 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6911 << InitArgList[I]->getSourceRange(); 6912 } 6913 } 6914 6915 if (FirstDesignator.isValid()) { 6916 // Only diagnose designated initiaization as a C++20 extension if we didn't 6917 // already diagnose use of (non-C++20) C99 designator syntax. 6918 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6919 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6920 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6921 ? diag::warn_cxx17_compat_designated_init 6922 : diag::ext_cxx_designated_init); 6923 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6924 Diag(FirstDesignator, diag::ext_designated_init); 6925 } 6926 } 6927 6928 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6929 } 6930 6931 ExprResult 6932 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6933 SourceLocation RBraceLoc) { 6934 // Semantic analysis for initializers is done by ActOnDeclarator() and 6935 // CheckInitializer() - it requires knowledge of the object being initialized. 6936 6937 // Immediately handle non-overload placeholders. Overloads can be 6938 // resolved contextually, but everything else here can't. 6939 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6940 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6941 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6942 6943 // Ignore failures; dropping the entire initializer list because 6944 // of one failure would be terrible for indexing/etc. 6945 if (result.isInvalid()) continue; 6946 6947 InitArgList[I] = result.get(); 6948 } 6949 } 6950 6951 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6952 RBraceLoc); 6953 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6954 return E; 6955 } 6956 6957 /// Do an explicit extend of the given block pointer if we're in ARC. 6958 void Sema::maybeExtendBlockObject(ExprResult &E) { 6959 assert(E.get()->getType()->isBlockPointerType()); 6960 assert(E.get()->isRValue()); 6961 6962 // Only do this in an r-value context. 6963 if (!getLangOpts().ObjCAutoRefCount) return; 6964 6965 E = ImplicitCastExpr::Create( 6966 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 6967 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 6968 Cleanup.setExprNeedsCleanups(true); 6969 } 6970 6971 /// Prepare a conversion of the given expression to an ObjC object 6972 /// pointer type. 6973 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6974 QualType type = E.get()->getType(); 6975 if (type->isObjCObjectPointerType()) { 6976 return CK_BitCast; 6977 } else if (type->isBlockPointerType()) { 6978 maybeExtendBlockObject(E); 6979 return CK_BlockPointerToObjCPointerCast; 6980 } else { 6981 assert(type->isPointerType()); 6982 return CK_CPointerToObjCPointerCast; 6983 } 6984 } 6985 6986 /// Prepares for a scalar cast, performing all the necessary stages 6987 /// except the final cast and returning the kind required. 6988 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6989 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6990 // Also, callers should have filtered out the invalid cases with 6991 // pointers. Everything else should be possible. 6992 6993 QualType SrcTy = Src.get()->getType(); 6994 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6995 return CK_NoOp; 6996 6997 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6998 case Type::STK_MemberPointer: 6999 llvm_unreachable("member pointer type in C"); 7000 7001 case Type::STK_CPointer: 7002 case Type::STK_BlockPointer: 7003 case Type::STK_ObjCObjectPointer: 7004 switch (DestTy->getScalarTypeKind()) { 7005 case Type::STK_CPointer: { 7006 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7007 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7008 if (SrcAS != DestAS) 7009 return CK_AddressSpaceConversion; 7010 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7011 return CK_NoOp; 7012 return CK_BitCast; 7013 } 7014 case Type::STK_BlockPointer: 7015 return (SrcKind == Type::STK_BlockPointer 7016 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7017 case Type::STK_ObjCObjectPointer: 7018 if (SrcKind == Type::STK_ObjCObjectPointer) 7019 return CK_BitCast; 7020 if (SrcKind == Type::STK_CPointer) 7021 return CK_CPointerToObjCPointerCast; 7022 maybeExtendBlockObject(Src); 7023 return CK_BlockPointerToObjCPointerCast; 7024 case Type::STK_Bool: 7025 return CK_PointerToBoolean; 7026 case Type::STK_Integral: 7027 return CK_PointerToIntegral; 7028 case Type::STK_Floating: 7029 case Type::STK_FloatingComplex: 7030 case Type::STK_IntegralComplex: 7031 case Type::STK_MemberPointer: 7032 case Type::STK_FixedPoint: 7033 llvm_unreachable("illegal cast from pointer"); 7034 } 7035 llvm_unreachable("Should have returned before this"); 7036 7037 case Type::STK_FixedPoint: 7038 switch (DestTy->getScalarTypeKind()) { 7039 case Type::STK_FixedPoint: 7040 return CK_FixedPointCast; 7041 case Type::STK_Bool: 7042 return CK_FixedPointToBoolean; 7043 case Type::STK_Integral: 7044 return CK_FixedPointToIntegral; 7045 case Type::STK_Floating: 7046 case Type::STK_IntegralComplex: 7047 case Type::STK_FloatingComplex: 7048 Diag(Src.get()->getExprLoc(), 7049 diag::err_unimplemented_conversion_with_fixed_point_type) 7050 << DestTy; 7051 return CK_IntegralCast; 7052 case Type::STK_CPointer: 7053 case Type::STK_ObjCObjectPointer: 7054 case Type::STK_BlockPointer: 7055 case Type::STK_MemberPointer: 7056 llvm_unreachable("illegal cast to pointer type"); 7057 } 7058 llvm_unreachable("Should have returned before this"); 7059 7060 case Type::STK_Bool: // casting from bool is like casting from an integer 7061 case Type::STK_Integral: 7062 switch (DestTy->getScalarTypeKind()) { 7063 case Type::STK_CPointer: 7064 case Type::STK_ObjCObjectPointer: 7065 case Type::STK_BlockPointer: 7066 if (Src.get()->isNullPointerConstant(Context, 7067 Expr::NPC_ValueDependentIsNull)) 7068 return CK_NullToPointer; 7069 return CK_IntegralToPointer; 7070 case Type::STK_Bool: 7071 return CK_IntegralToBoolean; 7072 case Type::STK_Integral: 7073 return CK_IntegralCast; 7074 case Type::STK_Floating: 7075 return CK_IntegralToFloating; 7076 case Type::STK_IntegralComplex: 7077 Src = ImpCastExprToType(Src.get(), 7078 DestTy->castAs<ComplexType>()->getElementType(), 7079 CK_IntegralCast); 7080 return CK_IntegralRealToComplex; 7081 case Type::STK_FloatingComplex: 7082 Src = ImpCastExprToType(Src.get(), 7083 DestTy->castAs<ComplexType>()->getElementType(), 7084 CK_IntegralToFloating); 7085 return CK_FloatingRealToComplex; 7086 case Type::STK_MemberPointer: 7087 llvm_unreachable("member pointer type in C"); 7088 case Type::STK_FixedPoint: 7089 return CK_IntegralToFixedPoint; 7090 } 7091 llvm_unreachable("Should have returned before this"); 7092 7093 case Type::STK_Floating: 7094 switch (DestTy->getScalarTypeKind()) { 7095 case Type::STK_Floating: 7096 return CK_FloatingCast; 7097 case Type::STK_Bool: 7098 return CK_FloatingToBoolean; 7099 case Type::STK_Integral: 7100 return CK_FloatingToIntegral; 7101 case Type::STK_FloatingComplex: 7102 Src = ImpCastExprToType(Src.get(), 7103 DestTy->castAs<ComplexType>()->getElementType(), 7104 CK_FloatingCast); 7105 return CK_FloatingRealToComplex; 7106 case Type::STK_IntegralComplex: 7107 Src = ImpCastExprToType(Src.get(), 7108 DestTy->castAs<ComplexType>()->getElementType(), 7109 CK_FloatingToIntegral); 7110 return CK_IntegralRealToComplex; 7111 case Type::STK_CPointer: 7112 case Type::STK_ObjCObjectPointer: 7113 case Type::STK_BlockPointer: 7114 llvm_unreachable("valid float->pointer cast?"); 7115 case Type::STK_MemberPointer: 7116 llvm_unreachable("member pointer type in C"); 7117 case Type::STK_FixedPoint: 7118 Diag(Src.get()->getExprLoc(), 7119 diag::err_unimplemented_conversion_with_fixed_point_type) 7120 << SrcTy; 7121 return CK_IntegralCast; 7122 } 7123 llvm_unreachable("Should have returned before this"); 7124 7125 case Type::STK_FloatingComplex: 7126 switch (DestTy->getScalarTypeKind()) { 7127 case Type::STK_FloatingComplex: 7128 return CK_FloatingComplexCast; 7129 case Type::STK_IntegralComplex: 7130 return CK_FloatingComplexToIntegralComplex; 7131 case Type::STK_Floating: { 7132 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7133 if (Context.hasSameType(ET, DestTy)) 7134 return CK_FloatingComplexToReal; 7135 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7136 return CK_FloatingCast; 7137 } 7138 case Type::STK_Bool: 7139 return CK_FloatingComplexToBoolean; 7140 case Type::STK_Integral: 7141 Src = ImpCastExprToType(Src.get(), 7142 SrcTy->castAs<ComplexType>()->getElementType(), 7143 CK_FloatingComplexToReal); 7144 return CK_FloatingToIntegral; 7145 case Type::STK_CPointer: 7146 case Type::STK_ObjCObjectPointer: 7147 case Type::STK_BlockPointer: 7148 llvm_unreachable("valid complex float->pointer cast?"); 7149 case Type::STK_MemberPointer: 7150 llvm_unreachable("member pointer type in C"); 7151 case Type::STK_FixedPoint: 7152 Diag(Src.get()->getExprLoc(), 7153 diag::err_unimplemented_conversion_with_fixed_point_type) 7154 << SrcTy; 7155 return CK_IntegralCast; 7156 } 7157 llvm_unreachable("Should have returned before this"); 7158 7159 case Type::STK_IntegralComplex: 7160 switch (DestTy->getScalarTypeKind()) { 7161 case Type::STK_FloatingComplex: 7162 return CK_IntegralComplexToFloatingComplex; 7163 case Type::STK_IntegralComplex: 7164 return CK_IntegralComplexCast; 7165 case Type::STK_Integral: { 7166 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7167 if (Context.hasSameType(ET, DestTy)) 7168 return CK_IntegralComplexToReal; 7169 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7170 return CK_IntegralCast; 7171 } 7172 case Type::STK_Bool: 7173 return CK_IntegralComplexToBoolean; 7174 case Type::STK_Floating: 7175 Src = ImpCastExprToType(Src.get(), 7176 SrcTy->castAs<ComplexType>()->getElementType(), 7177 CK_IntegralComplexToReal); 7178 return CK_IntegralToFloating; 7179 case Type::STK_CPointer: 7180 case Type::STK_ObjCObjectPointer: 7181 case Type::STK_BlockPointer: 7182 llvm_unreachable("valid complex int->pointer cast?"); 7183 case Type::STK_MemberPointer: 7184 llvm_unreachable("member pointer type in C"); 7185 case Type::STK_FixedPoint: 7186 Diag(Src.get()->getExprLoc(), 7187 diag::err_unimplemented_conversion_with_fixed_point_type) 7188 << SrcTy; 7189 return CK_IntegralCast; 7190 } 7191 llvm_unreachable("Should have returned before this"); 7192 } 7193 7194 llvm_unreachable("Unhandled scalar cast"); 7195 } 7196 7197 static bool breakDownVectorType(QualType type, uint64_t &len, 7198 QualType &eltType) { 7199 // Vectors are simple. 7200 if (const VectorType *vecType = type->getAs<VectorType>()) { 7201 len = vecType->getNumElements(); 7202 eltType = vecType->getElementType(); 7203 assert(eltType->isScalarType()); 7204 return true; 7205 } 7206 7207 // We allow lax conversion to and from non-vector types, but only if 7208 // they're real types (i.e. non-complex, non-pointer scalar types). 7209 if (!type->isRealType()) return false; 7210 7211 len = 1; 7212 eltType = type; 7213 return true; 7214 } 7215 7216 /// Are the two types lax-compatible vector types? That is, given 7217 /// that one of them is a vector, do they have equal storage sizes, 7218 /// where the storage size is the number of elements times the element 7219 /// size? 7220 /// 7221 /// This will also return false if either of the types is neither a 7222 /// vector nor a real type. 7223 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7224 assert(destTy->isVectorType() || srcTy->isVectorType()); 7225 7226 // Disallow lax conversions between scalars and ExtVectors (these 7227 // conversions are allowed for other vector types because common headers 7228 // depend on them). Most scalar OP ExtVector cases are handled by the 7229 // splat path anyway, which does what we want (convert, not bitcast). 7230 // What this rules out for ExtVectors is crazy things like char4*float. 7231 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7232 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7233 7234 uint64_t srcLen, destLen; 7235 QualType srcEltTy, destEltTy; 7236 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7237 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7238 7239 // ASTContext::getTypeSize will return the size rounded up to a 7240 // power of 2, so instead of using that, we need to use the raw 7241 // element size multiplied by the element count. 7242 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7243 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7244 7245 return (srcLen * srcEltSize == destLen * destEltSize); 7246 } 7247 7248 /// Is this a legal conversion between two types, one of which is 7249 /// known to be a vector type? 7250 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7251 assert(destTy->isVectorType() || srcTy->isVectorType()); 7252 7253 switch (Context.getLangOpts().getLaxVectorConversions()) { 7254 case LangOptions::LaxVectorConversionKind::None: 7255 return false; 7256 7257 case LangOptions::LaxVectorConversionKind::Integer: 7258 if (!srcTy->isIntegralOrEnumerationType()) { 7259 auto *Vec = srcTy->getAs<VectorType>(); 7260 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7261 return false; 7262 } 7263 if (!destTy->isIntegralOrEnumerationType()) { 7264 auto *Vec = destTy->getAs<VectorType>(); 7265 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7266 return false; 7267 } 7268 // OK, integer (vector) -> integer (vector) bitcast. 7269 break; 7270 7271 case LangOptions::LaxVectorConversionKind::All: 7272 break; 7273 } 7274 7275 return areLaxCompatibleVectorTypes(srcTy, destTy); 7276 } 7277 7278 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7279 CastKind &Kind) { 7280 assert(VectorTy->isVectorType() && "Not a vector type!"); 7281 7282 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7283 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7284 return Diag(R.getBegin(), 7285 Ty->isVectorType() ? 7286 diag::err_invalid_conversion_between_vectors : 7287 diag::err_invalid_conversion_between_vector_and_integer) 7288 << VectorTy << Ty << R; 7289 } else 7290 return Diag(R.getBegin(), 7291 diag::err_invalid_conversion_between_vector_and_scalar) 7292 << VectorTy << Ty << R; 7293 7294 Kind = CK_BitCast; 7295 return false; 7296 } 7297 7298 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7299 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7300 7301 if (DestElemTy == SplattedExpr->getType()) 7302 return SplattedExpr; 7303 7304 assert(DestElemTy->isFloatingType() || 7305 DestElemTy->isIntegralOrEnumerationType()); 7306 7307 CastKind CK; 7308 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7309 // OpenCL requires that we convert `true` boolean expressions to -1, but 7310 // only when splatting vectors. 7311 if (DestElemTy->isFloatingType()) { 7312 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7313 // in two steps: boolean to signed integral, then to floating. 7314 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7315 CK_BooleanToSignedIntegral); 7316 SplattedExpr = CastExprRes.get(); 7317 CK = CK_IntegralToFloating; 7318 } else { 7319 CK = CK_BooleanToSignedIntegral; 7320 } 7321 } else { 7322 ExprResult CastExprRes = SplattedExpr; 7323 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7324 if (CastExprRes.isInvalid()) 7325 return ExprError(); 7326 SplattedExpr = CastExprRes.get(); 7327 } 7328 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7329 } 7330 7331 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7332 Expr *CastExpr, CastKind &Kind) { 7333 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7334 7335 QualType SrcTy = CastExpr->getType(); 7336 7337 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7338 // an ExtVectorType. 7339 // In OpenCL, casts between vectors of different types are not allowed. 7340 // (See OpenCL 6.2). 7341 if (SrcTy->isVectorType()) { 7342 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7343 (getLangOpts().OpenCL && 7344 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7345 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7346 << DestTy << SrcTy << R; 7347 return ExprError(); 7348 } 7349 Kind = CK_BitCast; 7350 return CastExpr; 7351 } 7352 7353 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7354 // conversion will take place first from scalar to elt type, and then 7355 // splat from elt type to vector. 7356 if (SrcTy->isPointerType()) 7357 return Diag(R.getBegin(), 7358 diag::err_invalid_conversion_between_vector_and_scalar) 7359 << DestTy << SrcTy << R; 7360 7361 Kind = CK_VectorSplat; 7362 return prepareVectorSplat(DestTy, CastExpr); 7363 } 7364 7365 ExprResult 7366 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7367 Declarator &D, ParsedType &Ty, 7368 SourceLocation RParenLoc, Expr *CastExpr) { 7369 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7370 "ActOnCastExpr(): missing type or expr"); 7371 7372 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7373 if (D.isInvalidType()) 7374 return ExprError(); 7375 7376 if (getLangOpts().CPlusPlus) { 7377 // Check that there are no default arguments (C++ only). 7378 CheckExtraCXXDefaultArguments(D); 7379 } else { 7380 // Make sure any TypoExprs have been dealt with. 7381 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7382 if (!Res.isUsable()) 7383 return ExprError(); 7384 CastExpr = Res.get(); 7385 } 7386 7387 checkUnusedDeclAttributes(D); 7388 7389 QualType castType = castTInfo->getType(); 7390 Ty = CreateParsedType(castType, castTInfo); 7391 7392 bool isVectorLiteral = false; 7393 7394 // Check for an altivec or OpenCL literal, 7395 // i.e. all the elements are integer constants. 7396 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7397 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7398 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7399 && castType->isVectorType() && (PE || PLE)) { 7400 if (PLE && PLE->getNumExprs() == 0) { 7401 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7402 return ExprError(); 7403 } 7404 if (PE || PLE->getNumExprs() == 1) { 7405 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7406 if (!E->getType()->isVectorType()) 7407 isVectorLiteral = true; 7408 } 7409 else 7410 isVectorLiteral = true; 7411 } 7412 7413 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7414 // then handle it as such. 7415 if (isVectorLiteral) 7416 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7417 7418 // If the Expr being casted is a ParenListExpr, handle it specially. 7419 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7420 // sequence of BinOp comma operators. 7421 if (isa<ParenListExpr>(CastExpr)) { 7422 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7423 if (Result.isInvalid()) return ExprError(); 7424 CastExpr = Result.get(); 7425 } 7426 7427 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7428 !getSourceManager().isInSystemMacro(LParenLoc)) 7429 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7430 7431 CheckTollFreeBridgeCast(castType, CastExpr); 7432 7433 CheckObjCBridgeRelatedCast(castType, CastExpr); 7434 7435 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7436 7437 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7438 } 7439 7440 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7441 SourceLocation RParenLoc, Expr *E, 7442 TypeSourceInfo *TInfo) { 7443 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7444 "Expected paren or paren list expression"); 7445 7446 Expr **exprs; 7447 unsigned numExprs; 7448 Expr *subExpr; 7449 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7450 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7451 LiteralLParenLoc = PE->getLParenLoc(); 7452 LiteralRParenLoc = PE->getRParenLoc(); 7453 exprs = PE->getExprs(); 7454 numExprs = PE->getNumExprs(); 7455 } else { // isa<ParenExpr> by assertion at function entrance 7456 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7457 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7458 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7459 exprs = &subExpr; 7460 numExprs = 1; 7461 } 7462 7463 QualType Ty = TInfo->getType(); 7464 assert(Ty->isVectorType() && "Expected vector type"); 7465 7466 SmallVector<Expr *, 8> initExprs; 7467 const VectorType *VTy = Ty->castAs<VectorType>(); 7468 unsigned numElems = VTy->getNumElements(); 7469 7470 // '(...)' form of vector initialization in AltiVec: the number of 7471 // initializers must be one or must match the size of the vector. 7472 // If a single value is specified in the initializer then it will be 7473 // replicated to all the components of the vector 7474 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7475 // The number of initializers must be one or must match the size of the 7476 // vector. If a single value is specified in the initializer then it will 7477 // be replicated to all the components of the vector 7478 if (numExprs == 1) { 7479 QualType ElemTy = VTy->getElementType(); 7480 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7481 if (Literal.isInvalid()) 7482 return ExprError(); 7483 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7484 PrepareScalarCast(Literal, ElemTy)); 7485 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7486 } 7487 else if (numExprs < numElems) { 7488 Diag(E->getExprLoc(), 7489 diag::err_incorrect_number_of_vector_initializers); 7490 return ExprError(); 7491 } 7492 else 7493 initExprs.append(exprs, exprs + numExprs); 7494 } 7495 else { 7496 // For OpenCL, when the number of initializers is a single value, 7497 // it will be replicated to all components of the vector. 7498 if (getLangOpts().OpenCL && 7499 VTy->getVectorKind() == VectorType::GenericVector && 7500 numExprs == 1) { 7501 QualType ElemTy = VTy->getElementType(); 7502 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7503 if (Literal.isInvalid()) 7504 return ExprError(); 7505 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7506 PrepareScalarCast(Literal, ElemTy)); 7507 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7508 } 7509 7510 initExprs.append(exprs, exprs + numExprs); 7511 } 7512 // FIXME: This means that pretty-printing the final AST will produce curly 7513 // braces instead of the original commas. 7514 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7515 initExprs, LiteralRParenLoc); 7516 initE->setType(Ty); 7517 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7518 } 7519 7520 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7521 /// the ParenListExpr into a sequence of comma binary operators. 7522 ExprResult 7523 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7524 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7525 if (!E) 7526 return OrigExpr; 7527 7528 ExprResult Result(E->getExpr(0)); 7529 7530 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7531 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7532 E->getExpr(i)); 7533 7534 if (Result.isInvalid()) return ExprError(); 7535 7536 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7537 } 7538 7539 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7540 SourceLocation R, 7541 MultiExprArg Val) { 7542 return ParenListExpr::Create(Context, L, Val, R); 7543 } 7544 7545 /// Emit a specialized diagnostic when one expression is a null pointer 7546 /// constant and the other is not a pointer. Returns true if a diagnostic is 7547 /// emitted. 7548 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7549 SourceLocation QuestionLoc) { 7550 Expr *NullExpr = LHSExpr; 7551 Expr *NonPointerExpr = RHSExpr; 7552 Expr::NullPointerConstantKind NullKind = 7553 NullExpr->isNullPointerConstant(Context, 7554 Expr::NPC_ValueDependentIsNotNull); 7555 7556 if (NullKind == Expr::NPCK_NotNull) { 7557 NullExpr = RHSExpr; 7558 NonPointerExpr = LHSExpr; 7559 NullKind = 7560 NullExpr->isNullPointerConstant(Context, 7561 Expr::NPC_ValueDependentIsNotNull); 7562 } 7563 7564 if (NullKind == Expr::NPCK_NotNull) 7565 return false; 7566 7567 if (NullKind == Expr::NPCK_ZeroExpression) 7568 return false; 7569 7570 if (NullKind == Expr::NPCK_ZeroLiteral) { 7571 // In this case, check to make sure that we got here from a "NULL" 7572 // string in the source code. 7573 NullExpr = NullExpr->IgnoreParenImpCasts(); 7574 SourceLocation loc = NullExpr->getExprLoc(); 7575 if (!findMacroSpelling(loc, "NULL")) 7576 return false; 7577 } 7578 7579 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7580 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7581 << NonPointerExpr->getType() << DiagType 7582 << NonPointerExpr->getSourceRange(); 7583 return true; 7584 } 7585 7586 /// Return false if the condition expression is valid, true otherwise. 7587 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7588 QualType CondTy = Cond->getType(); 7589 7590 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7591 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7592 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7593 << CondTy << Cond->getSourceRange(); 7594 return true; 7595 } 7596 7597 // C99 6.5.15p2 7598 if (CondTy->isScalarType()) return false; 7599 7600 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7601 << CondTy << Cond->getSourceRange(); 7602 return true; 7603 } 7604 7605 /// Handle when one or both operands are void type. 7606 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7607 ExprResult &RHS) { 7608 Expr *LHSExpr = LHS.get(); 7609 Expr *RHSExpr = RHS.get(); 7610 7611 if (!LHSExpr->getType()->isVoidType()) 7612 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7613 << RHSExpr->getSourceRange(); 7614 if (!RHSExpr->getType()->isVoidType()) 7615 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7616 << LHSExpr->getSourceRange(); 7617 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7618 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7619 return S.Context.VoidTy; 7620 } 7621 7622 /// Return false if the NullExpr can be promoted to PointerTy, 7623 /// true otherwise. 7624 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7625 QualType PointerTy) { 7626 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7627 !NullExpr.get()->isNullPointerConstant(S.Context, 7628 Expr::NPC_ValueDependentIsNull)) 7629 return true; 7630 7631 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7632 return false; 7633 } 7634 7635 /// Checks compatibility between two pointers and return the resulting 7636 /// type. 7637 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7638 ExprResult &RHS, 7639 SourceLocation Loc) { 7640 QualType LHSTy = LHS.get()->getType(); 7641 QualType RHSTy = RHS.get()->getType(); 7642 7643 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7644 // Two identical pointers types are always compatible. 7645 return LHSTy; 7646 } 7647 7648 QualType lhptee, rhptee; 7649 7650 // Get the pointee types. 7651 bool IsBlockPointer = false; 7652 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7653 lhptee = LHSBTy->getPointeeType(); 7654 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7655 IsBlockPointer = true; 7656 } else { 7657 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7658 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7659 } 7660 7661 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7662 // differently qualified versions of compatible types, the result type is 7663 // a pointer to an appropriately qualified version of the composite 7664 // type. 7665 7666 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7667 // clause doesn't make sense for our extensions. E.g. address space 2 should 7668 // be incompatible with address space 3: they may live on different devices or 7669 // anything. 7670 Qualifiers lhQual = lhptee.getQualifiers(); 7671 Qualifiers rhQual = rhptee.getQualifiers(); 7672 7673 LangAS ResultAddrSpace = LangAS::Default; 7674 LangAS LAddrSpace = lhQual.getAddressSpace(); 7675 LangAS RAddrSpace = rhQual.getAddressSpace(); 7676 7677 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7678 // spaces is disallowed. 7679 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7680 ResultAddrSpace = LAddrSpace; 7681 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7682 ResultAddrSpace = RAddrSpace; 7683 else { 7684 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7685 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7686 << RHS.get()->getSourceRange(); 7687 return QualType(); 7688 } 7689 7690 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7691 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7692 lhQual.removeCVRQualifiers(); 7693 rhQual.removeCVRQualifiers(); 7694 7695 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7696 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7697 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7698 // qual types are compatible iff 7699 // * corresponded types are compatible 7700 // * CVR qualifiers are equal 7701 // * address spaces are equal 7702 // Thus for conditional operator we merge CVR and address space unqualified 7703 // pointees and if there is a composite type we return a pointer to it with 7704 // merged qualifiers. 7705 LHSCastKind = 7706 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7707 RHSCastKind = 7708 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7709 lhQual.removeAddressSpace(); 7710 rhQual.removeAddressSpace(); 7711 7712 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7713 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7714 7715 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7716 7717 if (CompositeTy.isNull()) { 7718 // In this situation, we assume void* type. No especially good 7719 // reason, but this is what gcc does, and we do have to pick 7720 // to get a consistent AST. 7721 QualType incompatTy; 7722 incompatTy = S.Context.getPointerType( 7723 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7724 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7725 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7726 7727 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7728 // for casts between types with incompatible address space qualifiers. 7729 // For the following code the compiler produces casts between global and 7730 // local address spaces of the corresponded innermost pointees: 7731 // local int *global *a; 7732 // global int *global *b; 7733 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7734 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7735 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7736 << RHS.get()->getSourceRange(); 7737 7738 return incompatTy; 7739 } 7740 7741 // The pointer types are compatible. 7742 // In case of OpenCL ResultTy should have the address space qualifier 7743 // which is a superset of address spaces of both the 2nd and the 3rd 7744 // operands of the conditional operator. 7745 QualType ResultTy = [&, ResultAddrSpace]() { 7746 if (S.getLangOpts().OpenCL) { 7747 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7748 CompositeQuals.setAddressSpace(ResultAddrSpace); 7749 return S.Context 7750 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7751 .withCVRQualifiers(MergedCVRQual); 7752 } 7753 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7754 }(); 7755 if (IsBlockPointer) 7756 ResultTy = S.Context.getBlockPointerType(ResultTy); 7757 else 7758 ResultTy = S.Context.getPointerType(ResultTy); 7759 7760 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7761 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7762 return ResultTy; 7763 } 7764 7765 /// Return the resulting type when the operands are both block pointers. 7766 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7767 ExprResult &LHS, 7768 ExprResult &RHS, 7769 SourceLocation Loc) { 7770 QualType LHSTy = LHS.get()->getType(); 7771 QualType RHSTy = RHS.get()->getType(); 7772 7773 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7774 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7775 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7776 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7777 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7778 return destType; 7779 } 7780 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7781 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7782 << RHS.get()->getSourceRange(); 7783 return QualType(); 7784 } 7785 7786 // We have 2 block pointer types. 7787 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7788 } 7789 7790 /// Return the resulting type when the operands are both pointers. 7791 static QualType 7792 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7793 ExprResult &RHS, 7794 SourceLocation Loc) { 7795 // get the pointer types 7796 QualType LHSTy = LHS.get()->getType(); 7797 QualType RHSTy = RHS.get()->getType(); 7798 7799 // get the "pointed to" types 7800 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7801 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7802 7803 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7804 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7805 // Figure out necessary qualifiers (C99 6.5.15p6) 7806 QualType destPointee 7807 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7808 QualType destType = S.Context.getPointerType(destPointee); 7809 // Add qualifiers if necessary. 7810 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7811 // Promote to void*. 7812 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7813 return destType; 7814 } 7815 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7816 QualType destPointee 7817 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7818 QualType destType = S.Context.getPointerType(destPointee); 7819 // Add qualifiers if necessary. 7820 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7821 // Promote to void*. 7822 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7823 return destType; 7824 } 7825 7826 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7827 } 7828 7829 /// Return false if the first expression is not an integer and the second 7830 /// expression is not a pointer, true otherwise. 7831 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7832 Expr* PointerExpr, SourceLocation Loc, 7833 bool IsIntFirstExpr) { 7834 if (!PointerExpr->getType()->isPointerType() || 7835 !Int.get()->getType()->isIntegerType()) 7836 return false; 7837 7838 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7839 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7840 7841 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7842 << Expr1->getType() << Expr2->getType() 7843 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7844 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7845 CK_IntegralToPointer); 7846 return true; 7847 } 7848 7849 /// Simple conversion between integer and floating point types. 7850 /// 7851 /// Used when handling the OpenCL conditional operator where the 7852 /// condition is a vector while the other operands are scalar. 7853 /// 7854 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7855 /// types are either integer or floating type. Between the two 7856 /// operands, the type with the higher rank is defined as the "result 7857 /// type". The other operand needs to be promoted to the same type. No 7858 /// other type promotion is allowed. We cannot use 7859 /// UsualArithmeticConversions() for this purpose, since it always 7860 /// promotes promotable types. 7861 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7862 ExprResult &RHS, 7863 SourceLocation QuestionLoc) { 7864 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7865 if (LHS.isInvalid()) 7866 return QualType(); 7867 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7868 if (RHS.isInvalid()) 7869 return QualType(); 7870 7871 // For conversion purposes, we ignore any qualifiers. 7872 // For example, "const float" and "float" are equivalent. 7873 QualType LHSType = 7874 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7875 QualType RHSType = 7876 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7877 7878 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7879 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7880 << LHSType << LHS.get()->getSourceRange(); 7881 return QualType(); 7882 } 7883 7884 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7885 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7886 << RHSType << RHS.get()->getSourceRange(); 7887 return QualType(); 7888 } 7889 7890 // If both types are identical, no conversion is needed. 7891 if (LHSType == RHSType) 7892 return LHSType; 7893 7894 // Now handle "real" floating types (i.e. float, double, long double). 7895 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7896 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7897 /*IsCompAssign = */ false); 7898 7899 // Finally, we have two differing integer types. 7900 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7901 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7902 } 7903 7904 /// Convert scalar operands to a vector that matches the 7905 /// condition in length. 7906 /// 7907 /// Used when handling the OpenCL conditional operator where the 7908 /// condition is a vector while the other operands are scalar. 7909 /// 7910 /// We first compute the "result type" for the scalar operands 7911 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7912 /// into a vector of that type where the length matches the condition 7913 /// vector type. s6.11.6 requires that the element types of the result 7914 /// and the condition must have the same number of bits. 7915 static QualType 7916 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7917 QualType CondTy, SourceLocation QuestionLoc) { 7918 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7919 if (ResTy.isNull()) return QualType(); 7920 7921 const VectorType *CV = CondTy->getAs<VectorType>(); 7922 assert(CV); 7923 7924 // Determine the vector result type 7925 unsigned NumElements = CV->getNumElements(); 7926 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7927 7928 // Ensure that all types have the same number of bits 7929 if (S.Context.getTypeSize(CV->getElementType()) 7930 != S.Context.getTypeSize(ResTy)) { 7931 // Since VectorTy is created internally, it does not pretty print 7932 // with an OpenCL name. Instead, we just print a description. 7933 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7934 SmallString<64> Str; 7935 llvm::raw_svector_ostream OS(Str); 7936 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7937 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7938 << CondTy << OS.str(); 7939 return QualType(); 7940 } 7941 7942 // Convert operands to the vector result type 7943 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7944 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7945 7946 return VectorTy; 7947 } 7948 7949 /// Return false if this is a valid OpenCL condition vector 7950 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7951 SourceLocation QuestionLoc) { 7952 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7953 // integral type. 7954 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7955 assert(CondTy); 7956 QualType EleTy = CondTy->getElementType(); 7957 if (EleTy->isIntegerType()) return false; 7958 7959 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7960 << Cond->getType() << Cond->getSourceRange(); 7961 return true; 7962 } 7963 7964 /// Return false if the vector condition type and the vector 7965 /// result type are compatible. 7966 /// 7967 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7968 /// number of elements, and their element types have the same number 7969 /// of bits. 7970 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7971 SourceLocation QuestionLoc) { 7972 const VectorType *CV = CondTy->getAs<VectorType>(); 7973 const VectorType *RV = VecResTy->getAs<VectorType>(); 7974 assert(CV && RV); 7975 7976 if (CV->getNumElements() != RV->getNumElements()) { 7977 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7978 << CondTy << VecResTy; 7979 return true; 7980 } 7981 7982 QualType CVE = CV->getElementType(); 7983 QualType RVE = RV->getElementType(); 7984 7985 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7986 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7987 << CondTy << VecResTy; 7988 return true; 7989 } 7990 7991 return false; 7992 } 7993 7994 /// Return the resulting type for the conditional operator in 7995 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7996 /// s6.3.i) when the condition is a vector type. 7997 static QualType 7998 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7999 ExprResult &LHS, ExprResult &RHS, 8000 SourceLocation QuestionLoc) { 8001 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8002 if (Cond.isInvalid()) 8003 return QualType(); 8004 QualType CondTy = Cond.get()->getType(); 8005 8006 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8007 return QualType(); 8008 8009 // If either operand is a vector then find the vector type of the 8010 // result as specified in OpenCL v1.1 s6.3.i. 8011 if (LHS.get()->getType()->isVectorType() || 8012 RHS.get()->getType()->isVectorType()) { 8013 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8014 /*isCompAssign*/false, 8015 /*AllowBothBool*/true, 8016 /*AllowBoolConversions*/false); 8017 if (VecResTy.isNull()) return QualType(); 8018 // The result type must match the condition type as specified in 8019 // OpenCL v1.1 s6.11.6. 8020 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8021 return QualType(); 8022 return VecResTy; 8023 } 8024 8025 // Both operands are scalar. 8026 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8027 } 8028 8029 /// Return true if the Expr is block type 8030 static bool checkBlockType(Sema &S, const Expr *E) { 8031 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8032 QualType Ty = CE->getCallee()->getType(); 8033 if (Ty->isBlockPointerType()) { 8034 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8035 return true; 8036 } 8037 } 8038 return false; 8039 } 8040 8041 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8042 /// In that case, LHS = cond. 8043 /// C99 6.5.15 8044 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8045 ExprResult &RHS, ExprValueKind &VK, 8046 ExprObjectKind &OK, 8047 SourceLocation QuestionLoc) { 8048 8049 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8050 if (!LHSResult.isUsable()) return QualType(); 8051 LHS = LHSResult; 8052 8053 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8054 if (!RHSResult.isUsable()) return QualType(); 8055 RHS = RHSResult; 8056 8057 // C++ is sufficiently different to merit its own checker. 8058 if (getLangOpts().CPlusPlus) 8059 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8060 8061 VK = VK_RValue; 8062 OK = OK_Ordinary; 8063 8064 // The OpenCL operator with a vector condition is sufficiently 8065 // different to merit its own checker. 8066 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8067 Cond.get()->getType()->isExtVectorType()) 8068 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8069 8070 // First, check the condition. 8071 Cond = UsualUnaryConversions(Cond.get()); 8072 if (Cond.isInvalid()) 8073 return QualType(); 8074 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8075 return QualType(); 8076 8077 // Now check the two expressions. 8078 if (LHS.get()->getType()->isVectorType() || 8079 RHS.get()->getType()->isVectorType()) 8080 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8081 /*AllowBothBool*/true, 8082 /*AllowBoolConversions*/false); 8083 8084 QualType ResTy = 8085 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8086 if (LHS.isInvalid() || RHS.isInvalid()) 8087 return QualType(); 8088 8089 QualType LHSTy = LHS.get()->getType(); 8090 QualType RHSTy = RHS.get()->getType(); 8091 8092 // Diagnose attempts to convert between __float128 and long double where 8093 // such conversions currently can't be handled. 8094 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8095 Diag(QuestionLoc, 8096 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8097 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8098 return QualType(); 8099 } 8100 8101 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8102 // selection operator (?:). 8103 if (getLangOpts().OpenCL && 8104 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8105 return QualType(); 8106 } 8107 8108 // If both operands have arithmetic type, do the usual arithmetic conversions 8109 // to find a common type: C99 6.5.15p3,5. 8110 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8111 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8112 // different sizes, or between ExtInts and other types. 8113 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8114 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8115 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8116 << RHS.get()->getSourceRange(); 8117 return QualType(); 8118 } 8119 8120 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8121 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8122 8123 return ResTy; 8124 } 8125 8126 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8127 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8128 return LHSTy; 8129 } 8130 8131 // If both operands are the same structure or union type, the result is that 8132 // type. 8133 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8134 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8135 if (LHSRT->getDecl() == RHSRT->getDecl()) 8136 // "If both the operands have structure or union type, the result has 8137 // that type." This implies that CV qualifiers are dropped. 8138 return LHSTy.getUnqualifiedType(); 8139 // FIXME: Type of conditional expression must be complete in C mode. 8140 } 8141 8142 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8143 // The following || allows only one side to be void (a GCC-ism). 8144 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8145 return checkConditionalVoidType(*this, LHS, RHS); 8146 } 8147 8148 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8149 // the type of the other operand." 8150 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8151 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8152 8153 // All objective-c pointer type analysis is done here. 8154 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8155 QuestionLoc); 8156 if (LHS.isInvalid() || RHS.isInvalid()) 8157 return QualType(); 8158 if (!compositeType.isNull()) 8159 return compositeType; 8160 8161 8162 // Handle block pointer types. 8163 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8164 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8165 QuestionLoc); 8166 8167 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8168 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8169 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8170 QuestionLoc); 8171 8172 // GCC compatibility: soften pointer/integer mismatch. Note that 8173 // null pointers have been filtered out by this point. 8174 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8175 /*IsIntFirstExpr=*/true)) 8176 return RHSTy; 8177 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8178 /*IsIntFirstExpr=*/false)) 8179 return LHSTy; 8180 8181 // Allow ?: operations in which both operands have the same 8182 // built-in sizeless type. 8183 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8184 return LHSTy; 8185 8186 // Emit a better diagnostic if one of the expressions is a null pointer 8187 // constant and the other is not a pointer type. In this case, the user most 8188 // likely forgot to take the address of the other expression. 8189 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8190 return QualType(); 8191 8192 // Otherwise, the operands are not compatible. 8193 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8194 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8195 << RHS.get()->getSourceRange(); 8196 return QualType(); 8197 } 8198 8199 /// FindCompositeObjCPointerType - Helper method to find composite type of 8200 /// two objective-c pointer types of the two input expressions. 8201 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8202 SourceLocation QuestionLoc) { 8203 QualType LHSTy = LHS.get()->getType(); 8204 QualType RHSTy = RHS.get()->getType(); 8205 8206 // Handle things like Class and struct objc_class*. Here we case the result 8207 // to the pseudo-builtin, because that will be implicitly cast back to the 8208 // redefinition type if an attempt is made to access its fields. 8209 if (LHSTy->isObjCClassType() && 8210 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8211 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8212 return LHSTy; 8213 } 8214 if (RHSTy->isObjCClassType() && 8215 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8216 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8217 return RHSTy; 8218 } 8219 // And the same for struct objc_object* / id 8220 if (LHSTy->isObjCIdType() && 8221 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8222 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8223 return LHSTy; 8224 } 8225 if (RHSTy->isObjCIdType() && 8226 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8227 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8228 return RHSTy; 8229 } 8230 // And the same for struct objc_selector* / SEL 8231 if (Context.isObjCSelType(LHSTy) && 8232 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8233 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8234 return LHSTy; 8235 } 8236 if (Context.isObjCSelType(RHSTy) && 8237 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8238 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8239 return RHSTy; 8240 } 8241 // Check constraints for Objective-C object pointers types. 8242 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8243 8244 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8245 // Two identical object pointer types are always compatible. 8246 return LHSTy; 8247 } 8248 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8249 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8250 QualType compositeType = LHSTy; 8251 8252 // If both operands are interfaces and either operand can be 8253 // assigned to the other, use that type as the composite 8254 // type. This allows 8255 // xxx ? (A*) a : (B*) b 8256 // where B is a subclass of A. 8257 // 8258 // Additionally, as for assignment, if either type is 'id' 8259 // allow silent coercion. Finally, if the types are 8260 // incompatible then make sure to use 'id' as the composite 8261 // type so the result is acceptable for sending messages to. 8262 8263 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8264 // It could return the composite type. 8265 if (!(compositeType = 8266 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8267 // Nothing more to do. 8268 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8269 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8270 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8271 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8272 } else if ((LHSOPT->isObjCQualifiedIdType() || 8273 RHSOPT->isObjCQualifiedIdType()) && 8274 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8275 true)) { 8276 // Need to handle "id<xx>" explicitly. 8277 // GCC allows qualified id and any Objective-C type to devolve to 8278 // id. Currently localizing to here until clear this should be 8279 // part of ObjCQualifiedIdTypesAreCompatible. 8280 compositeType = Context.getObjCIdType(); 8281 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8282 compositeType = Context.getObjCIdType(); 8283 } else { 8284 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8285 << LHSTy << RHSTy 8286 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8287 QualType incompatTy = Context.getObjCIdType(); 8288 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8289 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8290 return incompatTy; 8291 } 8292 // The object pointer types are compatible. 8293 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8294 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8295 return compositeType; 8296 } 8297 // Check Objective-C object pointer types and 'void *' 8298 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8299 if (getLangOpts().ObjCAutoRefCount) { 8300 // ARC forbids the implicit conversion of object pointers to 'void *', 8301 // so these types are not compatible. 8302 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8303 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8304 LHS = RHS = true; 8305 return QualType(); 8306 } 8307 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8308 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8309 QualType destPointee 8310 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8311 QualType destType = Context.getPointerType(destPointee); 8312 // Add qualifiers if necessary. 8313 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8314 // Promote to void*. 8315 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8316 return destType; 8317 } 8318 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8319 if (getLangOpts().ObjCAutoRefCount) { 8320 // ARC forbids the implicit conversion of object pointers to 'void *', 8321 // so these types are not compatible. 8322 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8323 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8324 LHS = RHS = true; 8325 return QualType(); 8326 } 8327 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8328 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8329 QualType destPointee 8330 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8331 QualType destType = Context.getPointerType(destPointee); 8332 // Add qualifiers if necessary. 8333 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8334 // Promote to void*. 8335 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8336 return destType; 8337 } 8338 return QualType(); 8339 } 8340 8341 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8342 /// ParenRange in parentheses. 8343 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8344 const PartialDiagnostic &Note, 8345 SourceRange ParenRange) { 8346 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8347 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8348 EndLoc.isValid()) { 8349 Self.Diag(Loc, Note) 8350 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8351 << FixItHint::CreateInsertion(EndLoc, ")"); 8352 } else { 8353 // We can't display the parentheses, so just show the bare note. 8354 Self.Diag(Loc, Note) << ParenRange; 8355 } 8356 } 8357 8358 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8359 return BinaryOperator::isAdditiveOp(Opc) || 8360 BinaryOperator::isMultiplicativeOp(Opc) || 8361 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8362 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8363 // not any of the logical operators. Bitwise-xor is commonly used as a 8364 // logical-xor because there is no logical-xor operator. The logical 8365 // operators, including uses of xor, have a high false positive rate for 8366 // precedence warnings. 8367 } 8368 8369 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8370 /// expression, either using a built-in or overloaded operator, 8371 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8372 /// expression. 8373 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8374 Expr **RHSExprs) { 8375 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8376 E = E->IgnoreImpCasts(); 8377 E = E->IgnoreConversionOperatorSingleStep(); 8378 E = E->IgnoreImpCasts(); 8379 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8380 E = MTE->getSubExpr(); 8381 E = E->IgnoreImpCasts(); 8382 } 8383 8384 // Built-in binary operator. 8385 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8386 if (IsArithmeticOp(OP->getOpcode())) { 8387 *Opcode = OP->getOpcode(); 8388 *RHSExprs = OP->getRHS(); 8389 return true; 8390 } 8391 } 8392 8393 // Overloaded operator. 8394 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8395 if (Call->getNumArgs() != 2) 8396 return false; 8397 8398 // Make sure this is really a binary operator that is safe to pass into 8399 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8400 OverloadedOperatorKind OO = Call->getOperator(); 8401 if (OO < OO_Plus || OO > OO_Arrow || 8402 OO == OO_PlusPlus || OO == OO_MinusMinus) 8403 return false; 8404 8405 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8406 if (IsArithmeticOp(OpKind)) { 8407 *Opcode = OpKind; 8408 *RHSExprs = Call->getArg(1); 8409 return true; 8410 } 8411 } 8412 8413 return false; 8414 } 8415 8416 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8417 /// or is a logical expression such as (x==y) which has int type, but is 8418 /// commonly interpreted as boolean. 8419 static bool ExprLooksBoolean(Expr *E) { 8420 E = E->IgnoreParenImpCasts(); 8421 8422 if (E->getType()->isBooleanType()) 8423 return true; 8424 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8425 return OP->isComparisonOp() || OP->isLogicalOp(); 8426 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8427 return OP->getOpcode() == UO_LNot; 8428 if (E->getType()->isPointerType()) 8429 return true; 8430 // FIXME: What about overloaded operator calls returning "unspecified boolean 8431 // type"s (commonly pointer-to-members)? 8432 8433 return false; 8434 } 8435 8436 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8437 /// and binary operator are mixed in a way that suggests the programmer assumed 8438 /// the conditional operator has higher precedence, for example: 8439 /// "int x = a + someBinaryCondition ? 1 : 2". 8440 static void DiagnoseConditionalPrecedence(Sema &Self, 8441 SourceLocation OpLoc, 8442 Expr *Condition, 8443 Expr *LHSExpr, 8444 Expr *RHSExpr) { 8445 BinaryOperatorKind CondOpcode; 8446 Expr *CondRHS; 8447 8448 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8449 return; 8450 if (!ExprLooksBoolean(CondRHS)) 8451 return; 8452 8453 // The condition is an arithmetic binary expression, with a right- 8454 // hand side that looks boolean, so warn. 8455 8456 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8457 ? diag::warn_precedence_bitwise_conditional 8458 : diag::warn_precedence_conditional; 8459 8460 Self.Diag(OpLoc, DiagID) 8461 << Condition->getSourceRange() 8462 << BinaryOperator::getOpcodeStr(CondOpcode); 8463 8464 SuggestParentheses( 8465 Self, OpLoc, 8466 Self.PDiag(diag::note_precedence_silence) 8467 << BinaryOperator::getOpcodeStr(CondOpcode), 8468 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8469 8470 SuggestParentheses(Self, OpLoc, 8471 Self.PDiag(diag::note_precedence_conditional_first), 8472 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8473 } 8474 8475 /// Compute the nullability of a conditional expression. 8476 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8477 QualType LHSTy, QualType RHSTy, 8478 ASTContext &Ctx) { 8479 if (!ResTy->isAnyPointerType()) 8480 return ResTy; 8481 8482 auto GetNullability = [&Ctx](QualType Ty) { 8483 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8484 if (Kind) 8485 return *Kind; 8486 return NullabilityKind::Unspecified; 8487 }; 8488 8489 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8490 NullabilityKind MergedKind; 8491 8492 // Compute nullability of a binary conditional expression. 8493 if (IsBin) { 8494 if (LHSKind == NullabilityKind::NonNull) 8495 MergedKind = NullabilityKind::NonNull; 8496 else 8497 MergedKind = RHSKind; 8498 // Compute nullability of a normal conditional expression. 8499 } else { 8500 if (LHSKind == NullabilityKind::Nullable || 8501 RHSKind == NullabilityKind::Nullable) 8502 MergedKind = NullabilityKind::Nullable; 8503 else if (LHSKind == NullabilityKind::NonNull) 8504 MergedKind = RHSKind; 8505 else if (RHSKind == NullabilityKind::NonNull) 8506 MergedKind = LHSKind; 8507 else 8508 MergedKind = NullabilityKind::Unspecified; 8509 } 8510 8511 // Return if ResTy already has the correct nullability. 8512 if (GetNullability(ResTy) == MergedKind) 8513 return ResTy; 8514 8515 // Strip all nullability from ResTy. 8516 while (ResTy->getNullability(Ctx)) 8517 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8518 8519 // Create a new AttributedType with the new nullability kind. 8520 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8521 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8522 } 8523 8524 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8525 /// in the case of a the GNU conditional expr extension. 8526 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8527 SourceLocation ColonLoc, 8528 Expr *CondExpr, Expr *LHSExpr, 8529 Expr *RHSExpr) { 8530 if (!getLangOpts().CPlusPlus) { 8531 // C cannot handle TypoExpr nodes in the condition because it 8532 // doesn't handle dependent types properly, so make sure any TypoExprs have 8533 // been dealt with before checking the operands. 8534 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8535 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8536 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8537 8538 if (!CondResult.isUsable()) 8539 return ExprError(); 8540 8541 if (LHSExpr) { 8542 if (!LHSResult.isUsable()) 8543 return ExprError(); 8544 } 8545 8546 if (!RHSResult.isUsable()) 8547 return ExprError(); 8548 8549 CondExpr = CondResult.get(); 8550 LHSExpr = LHSResult.get(); 8551 RHSExpr = RHSResult.get(); 8552 } 8553 8554 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8555 // was the condition. 8556 OpaqueValueExpr *opaqueValue = nullptr; 8557 Expr *commonExpr = nullptr; 8558 if (!LHSExpr) { 8559 commonExpr = CondExpr; 8560 // Lower out placeholder types first. This is important so that we don't 8561 // try to capture a placeholder. This happens in few cases in C++; such 8562 // as Objective-C++'s dictionary subscripting syntax. 8563 if (commonExpr->hasPlaceholderType()) { 8564 ExprResult result = CheckPlaceholderExpr(commonExpr); 8565 if (!result.isUsable()) return ExprError(); 8566 commonExpr = result.get(); 8567 } 8568 // We usually want to apply unary conversions *before* saving, except 8569 // in the special case of a C++ l-value conditional. 8570 if (!(getLangOpts().CPlusPlus 8571 && !commonExpr->isTypeDependent() 8572 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8573 && commonExpr->isGLValue() 8574 && commonExpr->isOrdinaryOrBitFieldObject() 8575 && RHSExpr->isOrdinaryOrBitFieldObject() 8576 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8577 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8578 if (commonRes.isInvalid()) 8579 return ExprError(); 8580 commonExpr = commonRes.get(); 8581 } 8582 8583 // If the common expression is a class or array prvalue, materialize it 8584 // so that we can safely refer to it multiple times. 8585 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8586 commonExpr->getType()->isArrayType())) { 8587 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8588 if (MatExpr.isInvalid()) 8589 return ExprError(); 8590 commonExpr = MatExpr.get(); 8591 } 8592 8593 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8594 commonExpr->getType(), 8595 commonExpr->getValueKind(), 8596 commonExpr->getObjectKind(), 8597 commonExpr); 8598 LHSExpr = CondExpr = opaqueValue; 8599 } 8600 8601 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8602 ExprValueKind VK = VK_RValue; 8603 ExprObjectKind OK = OK_Ordinary; 8604 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8605 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8606 VK, OK, QuestionLoc); 8607 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8608 RHS.isInvalid()) 8609 return ExprError(); 8610 8611 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8612 RHS.get()); 8613 8614 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8615 8616 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8617 Context); 8618 8619 if (!commonExpr) 8620 return new (Context) 8621 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8622 RHS.get(), result, VK, OK); 8623 8624 return new (Context) BinaryConditionalOperator( 8625 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8626 ColonLoc, result, VK, OK); 8627 } 8628 8629 // Check if we have a conversion between incompatible cmse function pointer 8630 // types, that is, a conversion between a function pointer with the 8631 // cmse_nonsecure_call attribute and one without. 8632 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8633 QualType ToType) { 8634 if (const auto *ToFn = 8635 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8636 if (const auto *FromFn = 8637 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8638 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8639 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8640 8641 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8642 } 8643 } 8644 return false; 8645 } 8646 8647 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8648 // being closely modeled after the C99 spec:-). The odd characteristic of this 8649 // routine is it effectively iqnores the qualifiers on the top level pointee. 8650 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8651 // FIXME: add a couple examples in this comment. 8652 static Sema::AssignConvertType 8653 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8654 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8655 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8656 8657 // get the "pointed to" type (ignoring qualifiers at the top level) 8658 const Type *lhptee, *rhptee; 8659 Qualifiers lhq, rhq; 8660 std::tie(lhptee, lhq) = 8661 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8662 std::tie(rhptee, rhq) = 8663 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8664 8665 Sema::AssignConvertType ConvTy = Sema::Compatible; 8666 8667 // C99 6.5.16.1p1: This following citation is common to constraints 8668 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8669 // qualifiers of the type *pointed to* by the right; 8670 8671 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8672 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8673 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8674 // Ignore lifetime for further calculation. 8675 lhq.removeObjCLifetime(); 8676 rhq.removeObjCLifetime(); 8677 } 8678 8679 if (!lhq.compatiblyIncludes(rhq)) { 8680 // Treat address-space mismatches as fatal. 8681 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8682 return Sema::IncompatiblePointerDiscardsQualifiers; 8683 8684 // It's okay to add or remove GC or lifetime qualifiers when converting to 8685 // and from void*. 8686 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8687 .compatiblyIncludes( 8688 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8689 && (lhptee->isVoidType() || rhptee->isVoidType())) 8690 ; // keep old 8691 8692 // Treat lifetime mismatches as fatal. 8693 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8694 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8695 8696 // For GCC/MS compatibility, other qualifier mismatches are treated 8697 // as still compatible in C. 8698 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8699 } 8700 8701 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8702 // incomplete type and the other is a pointer to a qualified or unqualified 8703 // version of void... 8704 if (lhptee->isVoidType()) { 8705 if (rhptee->isIncompleteOrObjectType()) 8706 return ConvTy; 8707 8708 // As an extension, we allow cast to/from void* to function pointer. 8709 assert(rhptee->isFunctionType()); 8710 return Sema::FunctionVoidPointer; 8711 } 8712 8713 if (rhptee->isVoidType()) { 8714 if (lhptee->isIncompleteOrObjectType()) 8715 return ConvTy; 8716 8717 // As an extension, we allow cast to/from void* to function pointer. 8718 assert(lhptee->isFunctionType()); 8719 return Sema::FunctionVoidPointer; 8720 } 8721 8722 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8723 // unqualified versions of compatible types, ... 8724 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8725 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8726 // Check if the pointee types are compatible ignoring the sign. 8727 // We explicitly check for char so that we catch "char" vs 8728 // "unsigned char" on systems where "char" is unsigned. 8729 if (lhptee->isCharType()) 8730 ltrans = S.Context.UnsignedCharTy; 8731 else if (lhptee->hasSignedIntegerRepresentation()) 8732 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8733 8734 if (rhptee->isCharType()) 8735 rtrans = S.Context.UnsignedCharTy; 8736 else if (rhptee->hasSignedIntegerRepresentation()) 8737 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8738 8739 if (ltrans == rtrans) { 8740 // Types are compatible ignoring the sign. Qualifier incompatibility 8741 // takes priority over sign incompatibility because the sign 8742 // warning can be disabled. 8743 if (ConvTy != Sema::Compatible) 8744 return ConvTy; 8745 8746 return Sema::IncompatiblePointerSign; 8747 } 8748 8749 // If we are a multi-level pointer, it's possible that our issue is simply 8750 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8751 // the eventual target type is the same and the pointers have the same 8752 // level of indirection, this must be the issue. 8753 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8754 do { 8755 std::tie(lhptee, lhq) = 8756 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8757 std::tie(rhptee, rhq) = 8758 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8759 8760 // Inconsistent address spaces at this point is invalid, even if the 8761 // address spaces would be compatible. 8762 // FIXME: This doesn't catch address space mismatches for pointers of 8763 // different nesting levels, like: 8764 // __local int *** a; 8765 // int ** b = a; 8766 // It's not clear how to actually determine when such pointers are 8767 // invalidly incompatible. 8768 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8769 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8770 8771 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8772 8773 if (lhptee == rhptee) 8774 return Sema::IncompatibleNestedPointerQualifiers; 8775 } 8776 8777 // General pointer incompatibility takes priority over qualifiers. 8778 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8779 return Sema::IncompatibleFunctionPointer; 8780 return Sema::IncompatiblePointer; 8781 } 8782 if (!S.getLangOpts().CPlusPlus && 8783 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8784 return Sema::IncompatibleFunctionPointer; 8785 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8786 return Sema::IncompatibleFunctionPointer; 8787 return ConvTy; 8788 } 8789 8790 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8791 /// block pointer types are compatible or whether a block and normal pointer 8792 /// are compatible. It is more restrict than comparing two function pointer 8793 // types. 8794 static Sema::AssignConvertType 8795 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8796 QualType RHSType) { 8797 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8798 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8799 8800 QualType lhptee, rhptee; 8801 8802 // get the "pointed to" type (ignoring qualifiers at the top level) 8803 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8804 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8805 8806 // In C++, the types have to match exactly. 8807 if (S.getLangOpts().CPlusPlus) 8808 return Sema::IncompatibleBlockPointer; 8809 8810 Sema::AssignConvertType ConvTy = Sema::Compatible; 8811 8812 // For blocks we enforce that qualifiers are identical. 8813 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8814 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8815 if (S.getLangOpts().OpenCL) { 8816 LQuals.removeAddressSpace(); 8817 RQuals.removeAddressSpace(); 8818 } 8819 if (LQuals != RQuals) 8820 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8821 8822 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8823 // assignment. 8824 // The current behavior is similar to C++ lambdas. A block might be 8825 // assigned to a variable iff its return type and parameters are compatible 8826 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8827 // an assignment. Presumably it should behave in way that a function pointer 8828 // assignment does in C, so for each parameter and return type: 8829 // * CVR and address space of LHS should be a superset of CVR and address 8830 // space of RHS. 8831 // * unqualified types should be compatible. 8832 if (S.getLangOpts().OpenCL) { 8833 if (!S.Context.typesAreBlockPointerCompatible( 8834 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8835 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8836 return Sema::IncompatibleBlockPointer; 8837 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8838 return Sema::IncompatibleBlockPointer; 8839 8840 return ConvTy; 8841 } 8842 8843 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8844 /// for assignment compatibility. 8845 static Sema::AssignConvertType 8846 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8847 QualType RHSType) { 8848 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8849 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8850 8851 if (LHSType->isObjCBuiltinType()) { 8852 // Class is not compatible with ObjC object pointers. 8853 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8854 !RHSType->isObjCQualifiedClassType()) 8855 return Sema::IncompatiblePointer; 8856 return Sema::Compatible; 8857 } 8858 if (RHSType->isObjCBuiltinType()) { 8859 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8860 !LHSType->isObjCQualifiedClassType()) 8861 return Sema::IncompatiblePointer; 8862 return Sema::Compatible; 8863 } 8864 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8865 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8866 8867 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8868 // make an exception for id<P> 8869 !LHSType->isObjCQualifiedIdType()) 8870 return Sema::CompatiblePointerDiscardsQualifiers; 8871 8872 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8873 return Sema::Compatible; 8874 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8875 return Sema::IncompatibleObjCQualifiedId; 8876 return Sema::IncompatiblePointer; 8877 } 8878 8879 Sema::AssignConvertType 8880 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8881 QualType LHSType, QualType RHSType) { 8882 // Fake up an opaque expression. We don't actually care about what 8883 // cast operations are required, so if CheckAssignmentConstraints 8884 // adds casts to this they'll be wasted, but fortunately that doesn't 8885 // usually happen on valid code. 8886 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8887 ExprResult RHSPtr = &RHSExpr; 8888 CastKind K; 8889 8890 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8891 } 8892 8893 /// This helper function returns true if QT is a vector type that has element 8894 /// type ElementType. 8895 static bool isVector(QualType QT, QualType ElementType) { 8896 if (const VectorType *VT = QT->getAs<VectorType>()) 8897 return VT->getElementType().getCanonicalType() == ElementType; 8898 return false; 8899 } 8900 8901 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8902 /// has code to accommodate several GCC extensions when type checking 8903 /// pointers. Here are some objectionable examples that GCC considers warnings: 8904 /// 8905 /// int a, *pint; 8906 /// short *pshort; 8907 /// struct foo *pfoo; 8908 /// 8909 /// pint = pshort; // warning: assignment from incompatible pointer type 8910 /// a = pint; // warning: assignment makes integer from pointer without a cast 8911 /// pint = a; // warning: assignment makes pointer from integer without a cast 8912 /// pint = pfoo; // warning: assignment from incompatible pointer type 8913 /// 8914 /// As a result, the code for dealing with pointers is more complex than the 8915 /// C99 spec dictates. 8916 /// 8917 /// Sets 'Kind' for any result kind except Incompatible. 8918 Sema::AssignConvertType 8919 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8920 CastKind &Kind, bool ConvertRHS) { 8921 QualType RHSType = RHS.get()->getType(); 8922 QualType OrigLHSType = LHSType; 8923 8924 // Get canonical types. We're not formatting these types, just comparing 8925 // them. 8926 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8927 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8928 8929 // Common case: no conversion required. 8930 if (LHSType == RHSType) { 8931 Kind = CK_NoOp; 8932 return Compatible; 8933 } 8934 8935 // If we have an atomic type, try a non-atomic assignment, then just add an 8936 // atomic qualification step. 8937 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8938 Sema::AssignConvertType result = 8939 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8940 if (result != Compatible) 8941 return result; 8942 if (Kind != CK_NoOp && ConvertRHS) 8943 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8944 Kind = CK_NonAtomicToAtomic; 8945 return Compatible; 8946 } 8947 8948 // If the left-hand side is a reference type, then we are in a 8949 // (rare!) case where we've allowed the use of references in C, 8950 // e.g., as a parameter type in a built-in function. In this case, 8951 // just make sure that the type referenced is compatible with the 8952 // right-hand side type. The caller is responsible for adjusting 8953 // LHSType so that the resulting expression does not have reference 8954 // type. 8955 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8956 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8957 Kind = CK_LValueBitCast; 8958 return Compatible; 8959 } 8960 return Incompatible; 8961 } 8962 8963 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8964 // to the same ExtVector type. 8965 if (LHSType->isExtVectorType()) { 8966 if (RHSType->isExtVectorType()) 8967 return Incompatible; 8968 if (RHSType->isArithmeticType()) { 8969 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8970 if (ConvertRHS) 8971 RHS = prepareVectorSplat(LHSType, RHS.get()); 8972 Kind = CK_VectorSplat; 8973 return Compatible; 8974 } 8975 } 8976 8977 // Conversions to or from vector type. 8978 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8979 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8980 // Allow assignments of an AltiVec vector type to an equivalent GCC 8981 // vector type and vice versa 8982 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8983 Kind = CK_BitCast; 8984 return Compatible; 8985 } 8986 8987 // If we are allowing lax vector conversions, and LHS and RHS are both 8988 // vectors, the total size only needs to be the same. This is a bitcast; 8989 // no bits are changed but the result type is different. 8990 if (isLaxVectorConversion(RHSType, LHSType)) { 8991 Kind = CK_BitCast; 8992 return IncompatibleVectors; 8993 } 8994 } 8995 8996 // When the RHS comes from another lax conversion (e.g. binops between 8997 // scalars and vectors) the result is canonicalized as a vector. When the 8998 // LHS is also a vector, the lax is allowed by the condition above. Handle 8999 // the case where LHS is a scalar. 9000 if (LHSType->isScalarType()) { 9001 const VectorType *VecType = RHSType->getAs<VectorType>(); 9002 if (VecType && VecType->getNumElements() == 1 && 9003 isLaxVectorConversion(RHSType, LHSType)) { 9004 ExprResult *VecExpr = &RHS; 9005 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9006 Kind = CK_BitCast; 9007 return Compatible; 9008 } 9009 } 9010 9011 // Allow assignments between fixed-length and sizeless SVE vectors. 9012 if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9013 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) && 9014 Context.areCompatibleSveTypes(LHSType, RHSType)) { 9015 Kind = CK_BitCast; 9016 return Compatible; 9017 } 9018 9019 return Incompatible; 9020 } 9021 9022 // Diagnose attempts to convert between __float128 and long double where 9023 // such conversions currently can't be handled. 9024 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9025 return Incompatible; 9026 9027 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9028 // discards the imaginary part. 9029 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9030 !LHSType->getAs<ComplexType>()) 9031 return Incompatible; 9032 9033 // Arithmetic conversions. 9034 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9035 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9036 if (ConvertRHS) 9037 Kind = PrepareScalarCast(RHS, LHSType); 9038 return Compatible; 9039 } 9040 9041 // Conversions to normal pointers. 9042 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9043 // U* -> T* 9044 if (isa<PointerType>(RHSType)) { 9045 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9046 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9047 if (AddrSpaceL != AddrSpaceR) 9048 Kind = CK_AddressSpaceConversion; 9049 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9050 Kind = CK_NoOp; 9051 else 9052 Kind = CK_BitCast; 9053 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9054 } 9055 9056 // int -> T* 9057 if (RHSType->isIntegerType()) { 9058 Kind = CK_IntegralToPointer; // FIXME: null? 9059 return IntToPointer; 9060 } 9061 9062 // C pointers are not compatible with ObjC object pointers, 9063 // with two exceptions: 9064 if (isa<ObjCObjectPointerType>(RHSType)) { 9065 // - conversions to void* 9066 if (LHSPointer->getPointeeType()->isVoidType()) { 9067 Kind = CK_BitCast; 9068 return Compatible; 9069 } 9070 9071 // - conversions from 'Class' to the redefinition type 9072 if (RHSType->isObjCClassType() && 9073 Context.hasSameType(LHSType, 9074 Context.getObjCClassRedefinitionType())) { 9075 Kind = CK_BitCast; 9076 return Compatible; 9077 } 9078 9079 Kind = CK_BitCast; 9080 return IncompatiblePointer; 9081 } 9082 9083 // U^ -> void* 9084 if (RHSType->getAs<BlockPointerType>()) { 9085 if (LHSPointer->getPointeeType()->isVoidType()) { 9086 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9087 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9088 ->getPointeeType() 9089 .getAddressSpace(); 9090 Kind = 9091 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9092 return Compatible; 9093 } 9094 } 9095 9096 return Incompatible; 9097 } 9098 9099 // Conversions to block pointers. 9100 if (isa<BlockPointerType>(LHSType)) { 9101 // U^ -> T^ 9102 if (RHSType->isBlockPointerType()) { 9103 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9104 ->getPointeeType() 9105 .getAddressSpace(); 9106 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9107 ->getPointeeType() 9108 .getAddressSpace(); 9109 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9110 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9111 } 9112 9113 // int or null -> T^ 9114 if (RHSType->isIntegerType()) { 9115 Kind = CK_IntegralToPointer; // FIXME: null 9116 return IntToBlockPointer; 9117 } 9118 9119 // id -> T^ 9120 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9121 Kind = CK_AnyPointerToBlockPointerCast; 9122 return Compatible; 9123 } 9124 9125 // void* -> T^ 9126 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9127 if (RHSPT->getPointeeType()->isVoidType()) { 9128 Kind = CK_AnyPointerToBlockPointerCast; 9129 return Compatible; 9130 } 9131 9132 return Incompatible; 9133 } 9134 9135 // Conversions to Objective-C pointers. 9136 if (isa<ObjCObjectPointerType>(LHSType)) { 9137 // A* -> B* 9138 if (RHSType->isObjCObjectPointerType()) { 9139 Kind = CK_BitCast; 9140 Sema::AssignConvertType result = 9141 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9142 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9143 result == Compatible && 9144 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9145 result = IncompatibleObjCWeakRef; 9146 return result; 9147 } 9148 9149 // int or null -> A* 9150 if (RHSType->isIntegerType()) { 9151 Kind = CK_IntegralToPointer; // FIXME: null 9152 return IntToPointer; 9153 } 9154 9155 // In general, C pointers are not compatible with ObjC object pointers, 9156 // with two exceptions: 9157 if (isa<PointerType>(RHSType)) { 9158 Kind = CK_CPointerToObjCPointerCast; 9159 9160 // - conversions from 'void*' 9161 if (RHSType->isVoidPointerType()) { 9162 return Compatible; 9163 } 9164 9165 // - conversions to 'Class' from its redefinition type 9166 if (LHSType->isObjCClassType() && 9167 Context.hasSameType(RHSType, 9168 Context.getObjCClassRedefinitionType())) { 9169 return Compatible; 9170 } 9171 9172 return IncompatiblePointer; 9173 } 9174 9175 // Only under strict condition T^ is compatible with an Objective-C pointer. 9176 if (RHSType->isBlockPointerType() && 9177 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9178 if (ConvertRHS) 9179 maybeExtendBlockObject(RHS); 9180 Kind = CK_BlockPointerToObjCPointerCast; 9181 return Compatible; 9182 } 9183 9184 return Incompatible; 9185 } 9186 9187 // Conversions from pointers that are not covered by the above. 9188 if (isa<PointerType>(RHSType)) { 9189 // T* -> _Bool 9190 if (LHSType == Context.BoolTy) { 9191 Kind = CK_PointerToBoolean; 9192 return Compatible; 9193 } 9194 9195 // T* -> int 9196 if (LHSType->isIntegerType()) { 9197 Kind = CK_PointerToIntegral; 9198 return PointerToInt; 9199 } 9200 9201 return Incompatible; 9202 } 9203 9204 // Conversions from Objective-C pointers that are not covered by the above. 9205 if (isa<ObjCObjectPointerType>(RHSType)) { 9206 // T* -> _Bool 9207 if (LHSType == Context.BoolTy) { 9208 Kind = CK_PointerToBoolean; 9209 return Compatible; 9210 } 9211 9212 // T* -> int 9213 if (LHSType->isIntegerType()) { 9214 Kind = CK_PointerToIntegral; 9215 return PointerToInt; 9216 } 9217 9218 return Incompatible; 9219 } 9220 9221 // struct A -> struct B 9222 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9223 if (Context.typesAreCompatible(LHSType, RHSType)) { 9224 Kind = CK_NoOp; 9225 return Compatible; 9226 } 9227 } 9228 9229 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9230 Kind = CK_IntToOCLSampler; 9231 return Compatible; 9232 } 9233 9234 return Incompatible; 9235 } 9236 9237 /// Constructs a transparent union from an expression that is 9238 /// used to initialize the transparent union. 9239 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9240 ExprResult &EResult, QualType UnionType, 9241 FieldDecl *Field) { 9242 // Build an initializer list that designates the appropriate member 9243 // of the transparent union. 9244 Expr *E = EResult.get(); 9245 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9246 E, SourceLocation()); 9247 Initializer->setType(UnionType); 9248 Initializer->setInitializedFieldInUnion(Field); 9249 9250 // Build a compound literal constructing a value of the transparent 9251 // union type from this initializer list. 9252 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9253 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9254 VK_RValue, Initializer, false); 9255 } 9256 9257 Sema::AssignConvertType 9258 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9259 ExprResult &RHS) { 9260 QualType RHSType = RHS.get()->getType(); 9261 9262 // If the ArgType is a Union type, we want to handle a potential 9263 // transparent_union GCC extension. 9264 const RecordType *UT = ArgType->getAsUnionType(); 9265 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9266 return Incompatible; 9267 9268 // The field to initialize within the transparent union. 9269 RecordDecl *UD = UT->getDecl(); 9270 FieldDecl *InitField = nullptr; 9271 // It's compatible if the expression matches any of the fields. 9272 for (auto *it : UD->fields()) { 9273 if (it->getType()->isPointerType()) { 9274 // If the transparent union contains a pointer type, we allow: 9275 // 1) void pointer 9276 // 2) null pointer constant 9277 if (RHSType->isPointerType()) 9278 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9279 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9280 InitField = it; 9281 break; 9282 } 9283 9284 if (RHS.get()->isNullPointerConstant(Context, 9285 Expr::NPC_ValueDependentIsNull)) { 9286 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9287 CK_NullToPointer); 9288 InitField = it; 9289 break; 9290 } 9291 } 9292 9293 CastKind Kind; 9294 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9295 == Compatible) { 9296 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9297 InitField = it; 9298 break; 9299 } 9300 } 9301 9302 if (!InitField) 9303 return Incompatible; 9304 9305 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9306 return Compatible; 9307 } 9308 9309 Sema::AssignConvertType 9310 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9311 bool Diagnose, 9312 bool DiagnoseCFAudited, 9313 bool ConvertRHS) { 9314 // We need to be able to tell the caller whether we diagnosed a problem, if 9315 // they ask us to issue diagnostics. 9316 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9317 9318 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9319 // we can't avoid *all* modifications at the moment, so we need some somewhere 9320 // to put the updated value. 9321 ExprResult LocalRHS = CallerRHS; 9322 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9323 9324 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9325 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9326 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9327 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9328 Diag(RHS.get()->getExprLoc(), 9329 diag::warn_noderef_to_dereferenceable_pointer) 9330 << RHS.get()->getSourceRange(); 9331 } 9332 } 9333 } 9334 9335 if (getLangOpts().CPlusPlus) { 9336 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9337 // C++ 5.17p3: If the left operand is not of class type, the 9338 // expression is implicitly converted (C++ 4) to the 9339 // cv-unqualified type of the left operand. 9340 QualType RHSType = RHS.get()->getType(); 9341 if (Diagnose) { 9342 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9343 AA_Assigning); 9344 } else { 9345 ImplicitConversionSequence ICS = 9346 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9347 /*SuppressUserConversions=*/false, 9348 AllowedExplicit::None, 9349 /*InOverloadResolution=*/false, 9350 /*CStyle=*/false, 9351 /*AllowObjCWritebackConversion=*/false); 9352 if (ICS.isFailure()) 9353 return Incompatible; 9354 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9355 ICS, AA_Assigning); 9356 } 9357 if (RHS.isInvalid()) 9358 return Incompatible; 9359 Sema::AssignConvertType result = Compatible; 9360 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9361 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9362 result = IncompatibleObjCWeakRef; 9363 return result; 9364 } 9365 9366 // FIXME: Currently, we fall through and treat C++ classes like C 9367 // structures. 9368 // FIXME: We also fall through for atomics; not sure what should 9369 // happen there, though. 9370 } else if (RHS.get()->getType() == Context.OverloadTy) { 9371 // As a set of extensions to C, we support overloading on functions. These 9372 // functions need to be resolved here. 9373 DeclAccessPair DAP; 9374 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9375 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9376 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9377 else 9378 return Incompatible; 9379 } 9380 9381 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9382 // a null pointer constant. 9383 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9384 LHSType->isBlockPointerType()) && 9385 RHS.get()->isNullPointerConstant(Context, 9386 Expr::NPC_ValueDependentIsNull)) { 9387 if (Diagnose || ConvertRHS) { 9388 CastKind Kind; 9389 CXXCastPath Path; 9390 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9391 /*IgnoreBaseAccess=*/false, Diagnose); 9392 if (ConvertRHS) 9393 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9394 } 9395 return Compatible; 9396 } 9397 9398 // OpenCL queue_t type assignment. 9399 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9400 Context, Expr::NPC_ValueDependentIsNull)) { 9401 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9402 return Compatible; 9403 } 9404 9405 // This check seems unnatural, however it is necessary to ensure the proper 9406 // conversion of functions/arrays. If the conversion were done for all 9407 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9408 // expressions that suppress this implicit conversion (&, sizeof). 9409 // 9410 // Suppress this for references: C++ 8.5.3p5. 9411 if (!LHSType->isReferenceType()) { 9412 // FIXME: We potentially allocate here even if ConvertRHS is false. 9413 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9414 if (RHS.isInvalid()) 9415 return Incompatible; 9416 } 9417 CastKind Kind; 9418 Sema::AssignConvertType result = 9419 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9420 9421 // C99 6.5.16.1p2: The value of the right operand is converted to the 9422 // type of the assignment expression. 9423 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9424 // so that we can use references in built-in functions even in C. 9425 // The getNonReferenceType() call makes sure that the resulting expression 9426 // does not have reference type. 9427 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9428 QualType Ty = LHSType.getNonLValueExprType(Context); 9429 Expr *E = RHS.get(); 9430 9431 // Check for various Objective-C errors. If we are not reporting 9432 // diagnostics and just checking for errors, e.g., during overload 9433 // resolution, return Incompatible to indicate the failure. 9434 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9435 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9436 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9437 if (!Diagnose) 9438 return Incompatible; 9439 } 9440 if (getLangOpts().ObjC && 9441 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9442 E->getType(), E, Diagnose) || 9443 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9444 if (!Diagnose) 9445 return Incompatible; 9446 // Replace the expression with a corrected version and continue so we 9447 // can find further errors. 9448 RHS = E; 9449 return Compatible; 9450 } 9451 9452 if (ConvertRHS) 9453 RHS = ImpCastExprToType(E, Ty, Kind); 9454 } 9455 9456 return result; 9457 } 9458 9459 namespace { 9460 /// The original operand to an operator, prior to the application of the usual 9461 /// arithmetic conversions and converting the arguments of a builtin operator 9462 /// candidate. 9463 struct OriginalOperand { 9464 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9465 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9466 Op = MTE->getSubExpr(); 9467 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9468 Op = BTE->getSubExpr(); 9469 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9470 Orig = ICE->getSubExprAsWritten(); 9471 Conversion = ICE->getConversionFunction(); 9472 } 9473 } 9474 9475 QualType getType() const { return Orig->getType(); } 9476 9477 Expr *Orig; 9478 NamedDecl *Conversion; 9479 }; 9480 } 9481 9482 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9483 ExprResult &RHS) { 9484 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9485 9486 Diag(Loc, diag::err_typecheck_invalid_operands) 9487 << OrigLHS.getType() << OrigRHS.getType() 9488 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9489 9490 // If a user-defined conversion was applied to either of the operands prior 9491 // to applying the built-in operator rules, tell the user about it. 9492 if (OrigLHS.Conversion) { 9493 Diag(OrigLHS.Conversion->getLocation(), 9494 diag::note_typecheck_invalid_operands_converted) 9495 << 0 << LHS.get()->getType(); 9496 } 9497 if (OrigRHS.Conversion) { 9498 Diag(OrigRHS.Conversion->getLocation(), 9499 diag::note_typecheck_invalid_operands_converted) 9500 << 1 << RHS.get()->getType(); 9501 } 9502 9503 return QualType(); 9504 } 9505 9506 // Diagnose cases where a scalar was implicitly converted to a vector and 9507 // diagnose the underlying types. Otherwise, diagnose the error 9508 // as invalid vector logical operands for non-C++ cases. 9509 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9510 ExprResult &RHS) { 9511 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9512 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9513 9514 bool LHSNatVec = LHSType->isVectorType(); 9515 bool RHSNatVec = RHSType->isVectorType(); 9516 9517 if (!(LHSNatVec && RHSNatVec)) { 9518 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9519 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9520 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9521 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9522 << Vector->getSourceRange(); 9523 return QualType(); 9524 } 9525 9526 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9527 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9528 << RHS.get()->getSourceRange(); 9529 9530 return QualType(); 9531 } 9532 9533 /// Try to convert a value of non-vector type to a vector type by converting 9534 /// the type to the element type of the vector and then performing a splat. 9535 /// If the language is OpenCL, we only use conversions that promote scalar 9536 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9537 /// for float->int. 9538 /// 9539 /// OpenCL V2.0 6.2.6.p2: 9540 /// An error shall occur if any scalar operand type has greater rank 9541 /// than the type of the vector element. 9542 /// 9543 /// \param scalar - if non-null, actually perform the conversions 9544 /// \return true if the operation fails (but without diagnosing the failure) 9545 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9546 QualType scalarTy, 9547 QualType vectorEltTy, 9548 QualType vectorTy, 9549 unsigned &DiagID) { 9550 // The conversion to apply to the scalar before splatting it, 9551 // if necessary. 9552 CastKind scalarCast = CK_NoOp; 9553 9554 if (vectorEltTy->isIntegralType(S.Context)) { 9555 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9556 (scalarTy->isIntegerType() && 9557 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9558 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9559 return true; 9560 } 9561 if (!scalarTy->isIntegralType(S.Context)) 9562 return true; 9563 scalarCast = CK_IntegralCast; 9564 } else if (vectorEltTy->isRealFloatingType()) { 9565 if (scalarTy->isRealFloatingType()) { 9566 if (S.getLangOpts().OpenCL && 9567 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9568 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9569 return true; 9570 } 9571 scalarCast = CK_FloatingCast; 9572 } 9573 else if (scalarTy->isIntegralType(S.Context)) 9574 scalarCast = CK_IntegralToFloating; 9575 else 9576 return true; 9577 } else { 9578 return true; 9579 } 9580 9581 // Adjust scalar if desired. 9582 if (scalar) { 9583 if (scalarCast != CK_NoOp) 9584 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9585 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9586 } 9587 return false; 9588 } 9589 9590 /// Convert vector E to a vector with the same number of elements but different 9591 /// element type. 9592 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9593 const auto *VecTy = E->getType()->getAs<VectorType>(); 9594 assert(VecTy && "Expression E must be a vector"); 9595 QualType NewVecTy = S.Context.getVectorType(ElementType, 9596 VecTy->getNumElements(), 9597 VecTy->getVectorKind()); 9598 9599 // Look through the implicit cast. Return the subexpression if its type is 9600 // NewVecTy. 9601 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9602 if (ICE->getSubExpr()->getType() == NewVecTy) 9603 return ICE->getSubExpr(); 9604 9605 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9606 return S.ImpCastExprToType(E, NewVecTy, Cast); 9607 } 9608 9609 /// Test if a (constant) integer Int can be casted to another integer type 9610 /// IntTy without losing precision. 9611 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9612 QualType OtherIntTy) { 9613 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9614 9615 // Reject cases where the value of the Int is unknown as that would 9616 // possibly cause truncation, but accept cases where the scalar can be 9617 // demoted without loss of precision. 9618 Expr::EvalResult EVResult; 9619 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9620 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9621 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9622 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9623 9624 if (CstInt) { 9625 // If the scalar is constant and is of a higher order and has more active 9626 // bits that the vector element type, reject it. 9627 llvm::APSInt Result = EVResult.Val.getInt(); 9628 unsigned NumBits = IntSigned 9629 ? (Result.isNegative() ? Result.getMinSignedBits() 9630 : Result.getActiveBits()) 9631 : Result.getActiveBits(); 9632 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9633 return true; 9634 9635 // If the signedness of the scalar type and the vector element type 9636 // differs and the number of bits is greater than that of the vector 9637 // element reject it. 9638 return (IntSigned != OtherIntSigned && 9639 NumBits > S.Context.getIntWidth(OtherIntTy)); 9640 } 9641 9642 // Reject cases where the value of the scalar is not constant and it's 9643 // order is greater than that of the vector element type. 9644 return (Order < 0); 9645 } 9646 9647 /// Test if a (constant) integer Int can be casted to floating point type 9648 /// FloatTy without losing precision. 9649 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9650 QualType FloatTy) { 9651 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9652 9653 // Determine if the integer constant can be expressed as a floating point 9654 // number of the appropriate type. 9655 Expr::EvalResult EVResult; 9656 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9657 9658 uint64_t Bits = 0; 9659 if (CstInt) { 9660 // Reject constants that would be truncated if they were converted to 9661 // the floating point type. Test by simple to/from conversion. 9662 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9663 // could be avoided if there was a convertFromAPInt method 9664 // which could signal back if implicit truncation occurred. 9665 llvm::APSInt Result = EVResult.Val.getInt(); 9666 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9667 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9668 llvm::APFloat::rmTowardZero); 9669 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9670 !IntTy->hasSignedIntegerRepresentation()); 9671 bool Ignored = false; 9672 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9673 &Ignored); 9674 if (Result != ConvertBack) 9675 return true; 9676 } else { 9677 // Reject types that cannot be fully encoded into the mantissa of 9678 // the float. 9679 Bits = S.Context.getTypeSize(IntTy); 9680 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9681 S.Context.getFloatTypeSemantics(FloatTy)); 9682 if (Bits > FloatPrec) 9683 return true; 9684 } 9685 9686 return false; 9687 } 9688 9689 /// Attempt to convert and splat Scalar into a vector whose types matches 9690 /// Vector following GCC conversion rules. The rule is that implicit 9691 /// conversion can occur when Scalar can be casted to match Vector's element 9692 /// type without causing truncation of Scalar. 9693 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9694 ExprResult *Vector) { 9695 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9696 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9697 const VectorType *VT = VectorTy->getAs<VectorType>(); 9698 9699 assert(!isa<ExtVectorType>(VT) && 9700 "ExtVectorTypes should not be handled here!"); 9701 9702 QualType VectorEltTy = VT->getElementType(); 9703 9704 // Reject cases where the vector element type or the scalar element type are 9705 // not integral or floating point types. 9706 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9707 return true; 9708 9709 // The conversion to apply to the scalar before splatting it, 9710 // if necessary. 9711 CastKind ScalarCast = CK_NoOp; 9712 9713 // Accept cases where the vector elements are integers and the scalar is 9714 // an integer. 9715 // FIXME: Notionally if the scalar was a floating point value with a precise 9716 // integral representation, we could cast it to an appropriate integer 9717 // type and then perform the rest of the checks here. GCC will perform 9718 // this conversion in some cases as determined by the input language. 9719 // We should accept it on a language independent basis. 9720 if (VectorEltTy->isIntegralType(S.Context) && 9721 ScalarTy->isIntegralType(S.Context) && 9722 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9723 9724 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9725 return true; 9726 9727 ScalarCast = CK_IntegralCast; 9728 } else if (VectorEltTy->isIntegralType(S.Context) && 9729 ScalarTy->isRealFloatingType()) { 9730 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9731 ScalarCast = CK_FloatingToIntegral; 9732 else 9733 return true; 9734 } else if (VectorEltTy->isRealFloatingType()) { 9735 if (ScalarTy->isRealFloatingType()) { 9736 9737 // Reject cases where the scalar type is not a constant and has a higher 9738 // Order than the vector element type. 9739 llvm::APFloat Result(0.0); 9740 9741 // Determine whether this is a constant scalar. In the event that the 9742 // value is dependent (and thus cannot be evaluated by the constant 9743 // evaluator), skip the evaluation. This will then diagnose once the 9744 // expression is instantiated. 9745 bool CstScalar = Scalar->get()->isValueDependent() || 9746 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9747 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9748 if (!CstScalar && Order < 0) 9749 return true; 9750 9751 // If the scalar cannot be safely casted to the vector element type, 9752 // reject it. 9753 if (CstScalar) { 9754 bool Truncated = false; 9755 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9756 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9757 if (Truncated) 9758 return true; 9759 } 9760 9761 ScalarCast = CK_FloatingCast; 9762 } else if (ScalarTy->isIntegralType(S.Context)) { 9763 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9764 return true; 9765 9766 ScalarCast = CK_IntegralToFloating; 9767 } else 9768 return true; 9769 } else if (ScalarTy->isEnumeralType()) 9770 return true; 9771 9772 // Adjust scalar if desired. 9773 if (Scalar) { 9774 if (ScalarCast != CK_NoOp) 9775 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9776 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9777 } 9778 return false; 9779 } 9780 9781 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9782 SourceLocation Loc, bool IsCompAssign, 9783 bool AllowBothBool, 9784 bool AllowBoolConversions) { 9785 if (!IsCompAssign) { 9786 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9787 if (LHS.isInvalid()) 9788 return QualType(); 9789 } 9790 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9791 if (RHS.isInvalid()) 9792 return QualType(); 9793 9794 // For conversion purposes, we ignore any qualifiers. 9795 // For example, "const float" and "float" are equivalent. 9796 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9797 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9798 9799 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9800 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9801 assert(LHSVecType || RHSVecType); 9802 9803 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9804 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9805 return InvalidOperands(Loc, LHS, RHS); 9806 9807 // AltiVec-style "vector bool op vector bool" combinations are allowed 9808 // for some operators but not others. 9809 if (!AllowBothBool && 9810 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9811 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9812 return InvalidOperands(Loc, LHS, RHS); 9813 9814 // If the vector types are identical, return. 9815 if (Context.hasSameType(LHSType, RHSType)) 9816 return LHSType; 9817 9818 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9819 if (LHSVecType && RHSVecType && 9820 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9821 if (isa<ExtVectorType>(LHSVecType)) { 9822 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9823 return LHSType; 9824 } 9825 9826 if (!IsCompAssign) 9827 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9828 return RHSType; 9829 } 9830 9831 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9832 // can be mixed, with the result being the non-bool type. The non-bool 9833 // operand must have integer element type. 9834 if (AllowBoolConversions && LHSVecType && RHSVecType && 9835 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9836 (Context.getTypeSize(LHSVecType->getElementType()) == 9837 Context.getTypeSize(RHSVecType->getElementType()))) { 9838 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9839 LHSVecType->getElementType()->isIntegerType() && 9840 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9841 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9842 return LHSType; 9843 } 9844 if (!IsCompAssign && 9845 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9846 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9847 RHSVecType->getElementType()->isIntegerType()) { 9848 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9849 return RHSType; 9850 } 9851 } 9852 9853 // If there's a vector type and a scalar, try to convert the scalar to 9854 // the vector element type and splat. 9855 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9856 if (!RHSVecType) { 9857 if (isa<ExtVectorType>(LHSVecType)) { 9858 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9859 LHSVecType->getElementType(), LHSType, 9860 DiagID)) 9861 return LHSType; 9862 } else { 9863 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9864 return LHSType; 9865 } 9866 } 9867 if (!LHSVecType) { 9868 if (isa<ExtVectorType>(RHSVecType)) { 9869 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9870 LHSType, RHSVecType->getElementType(), 9871 RHSType, DiagID)) 9872 return RHSType; 9873 } else { 9874 if (LHS.get()->getValueKind() == VK_LValue || 9875 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9876 return RHSType; 9877 } 9878 } 9879 9880 // FIXME: The code below also handles conversion between vectors and 9881 // non-scalars, we should break this down into fine grained specific checks 9882 // and emit proper diagnostics. 9883 QualType VecType = LHSVecType ? LHSType : RHSType; 9884 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9885 QualType OtherType = LHSVecType ? RHSType : LHSType; 9886 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9887 if (isLaxVectorConversion(OtherType, VecType)) { 9888 // If we're allowing lax vector conversions, only the total (data) size 9889 // needs to be the same. For non compound assignment, if one of the types is 9890 // scalar, the result is always the vector type. 9891 if (!IsCompAssign) { 9892 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9893 return VecType; 9894 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9895 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9896 // type. Note that this is already done by non-compound assignments in 9897 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9898 // <1 x T> -> T. The result is also a vector type. 9899 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9900 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9901 ExprResult *RHSExpr = &RHS; 9902 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9903 return VecType; 9904 } 9905 } 9906 9907 // Okay, the expression is invalid. 9908 9909 // Returns true if the operands are SVE VLA and VLS types. 9910 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9911 const VectorType *VecType = SecondType->getAs<VectorType>(); 9912 return FirstType->isSizelessBuiltinType() && VecType && 9913 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9914 VecType->getVectorKind() == 9915 VectorType::SveFixedLengthPredicateVector); 9916 }; 9917 9918 // If there's a sizeless and fixed-length operand, diagnose that. 9919 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9920 Diag(Loc, diag::err_typecheck_vector_not_convertable_sizeless) 9921 << LHSType << RHSType; 9922 return QualType(); 9923 } 9924 9925 // If there's a non-vector, non-real operand, diagnose that. 9926 if ((!RHSVecType && !RHSType->isRealType()) || 9927 (!LHSVecType && !LHSType->isRealType())) { 9928 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9929 << LHSType << RHSType 9930 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9931 return QualType(); 9932 } 9933 9934 // OpenCL V1.1 6.2.6.p1: 9935 // If the operands are of more than one vector type, then an error shall 9936 // occur. Implicit conversions between vector types are not permitted, per 9937 // section 6.2.1. 9938 if (getLangOpts().OpenCL && 9939 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9940 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9941 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9942 << RHSType; 9943 return QualType(); 9944 } 9945 9946 9947 // If there is a vector type that is not a ExtVector and a scalar, we reach 9948 // this point if scalar could not be converted to the vector's element type 9949 // without truncation. 9950 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9951 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9952 QualType Scalar = LHSVecType ? RHSType : LHSType; 9953 QualType Vector = LHSVecType ? LHSType : RHSType; 9954 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9955 Diag(Loc, 9956 diag::err_typecheck_vector_not_convertable_implict_truncation) 9957 << ScalarOrVector << Scalar << Vector; 9958 9959 return QualType(); 9960 } 9961 9962 // Otherwise, use the generic diagnostic. 9963 Diag(Loc, DiagID) 9964 << LHSType << RHSType 9965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9966 return QualType(); 9967 } 9968 9969 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9970 // expression. These are mainly cases where the null pointer is used as an 9971 // integer instead of a pointer. 9972 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9973 SourceLocation Loc, bool IsCompare) { 9974 // The canonical way to check for a GNU null is with isNullPointerConstant, 9975 // but we use a bit of a hack here for speed; this is a relatively 9976 // hot path, and isNullPointerConstant is slow. 9977 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9978 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9979 9980 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9981 9982 // Avoid analyzing cases where the result will either be invalid (and 9983 // diagnosed as such) or entirely valid and not something to warn about. 9984 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9985 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9986 return; 9987 9988 // Comparison operations would not make sense with a null pointer no matter 9989 // what the other expression is. 9990 if (!IsCompare) { 9991 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9992 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9993 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9994 return; 9995 } 9996 9997 // The rest of the operations only make sense with a null pointer 9998 // if the other expression is a pointer. 9999 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10000 NonNullType->canDecayToPointerType()) 10001 return; 10002 10003 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10004 << LHSNull /* LHS is NULL */ << NonNullType 10005 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10006 } 10007 10008 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10009 SourceLocation Loc) { 10010 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10011 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10012 if (!LUE || !RUE) 10013 return; 10014 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10015 RUE->getKind() != UETT_SizeOf) 10016 return; 10017 10018 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10019 QualType LHSTy = LHSArg->getType(); 10020 QualType RHSTy; 10021 10022 if (RUE->isArgumentType()) 10023 RHSTy = RUE->getArgumentType(); 10024 else 10025 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10026 10027 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10028 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10029 return; 10030 10031 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10032 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10033 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10034 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10035 << LHSArgDecl; 10036 } 10037 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10038 QualType ArrayElemTy = ArrayTy->getElementType(); 10039 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10040 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10041 ArrayElemTy->isCharType() || 10042 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10043 return; 10044 S.Diag(Loc, diag::warn_division_sizeof_array) 10045 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10046 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10047 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10048 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10049 << LHSArgDecl; 10050 } 10051 10052 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10053 } 10054 } 10055 10056 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10057 ExprResult &RHS, 10058 SourceLocation Loc, bool IsDiv) { 10059 // Check for division/remainder by zero. 10060 Expr::EvalResult RHSValue; 10061 if (!RHS.get()->isValueDependent() && 10062 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10063 RHSValue.Val.getInt() == 0) 10064 S.DiagRuntimeBehavior(Loc, RHS.get(), 10065 S.PDiag(diag::warn_remainder_division_by_zero) 10066 << IsDiv << RHS.get()->getSourceRange()); 10067 } 10068 10069 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10070 SourceLocation Loc, 10071 bool IsCompAssign, bool IsDiv) { 10072 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10073 10074 if (LHS.get()->getType()->isVectorType() || 10075 RHS.get()->getType()->isVectorType()) 10076 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10077 /*AllowBothBool*/getLangOpts().AltiVec, 10078 /*AllowBoolConversions*/false); 10079 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10080 RHS.get()->getType()->isConstantMatrixType())) 10081 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10082 10083 QualType compType = UsualArithmeticConversions( 10084 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10085 if (LHS.isInvalid() || RHS.isInvalid()) 10086 return QualType(); 10087 10088 10089 if (compType.isNull() || !compType->isArithmeticType()) 10090 return InvalidOperands(Loc, LHS, RHS); 10091 if (IsDiv) { 10092 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10093 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10094 } 10095 return compType; 10096 } 10097 10098 QualType Sema::CheckRemainderOperands( 10099 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10100 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10101 10102 if (LHS.get()->getType()->isVectorType() || 10103 RHS.get()->getType()->isVectorType()) { 10104 if (LHS.get()->getType()->hasIntegerRepresentation() && 10105 RHS.get()->getType()->hasIntegerRepresentation()) 10106 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10107 /*AllowBothBool*/getLangOpts().AltiVec, 10108 /*AllowBoolConversions*/false); 10109 return InvalidOperands(Loc, LHS, RHS); 10110 } 10111 10112 QualType compType = UsualArithmeticConversions( 10113 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10114 if (LHS.isInvalid() || RHS.isInvalid()) 10115 return QualType(); 10116 10117 if (compType.isNull() || !compType->isIntegerType()) 10118 return InvalidOperands(Loc, LHS, RHS); 10119 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10120 return compType; 10121 } 10122 10123 /// Diagnose invalid arithmetic on two void pointers. 10124 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10125 Expr *LHSExpr, Expr *RHSExpr) { 10126 S.Diag(Loc, S.getLangOpts().CPlusPlus 10127 ? diag::err_typecheck_pointer_arith_void_type 10128 : diag::ext_gnu_void_ptr) 10129 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10130 << RHSExpr->getSourceRange(); 10131 } 10132 10133 /// Diagnose invalid arithmetic on a void pointer. 10134 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10135 Expr *Pointer) { 10136 S.Diag(Loc, S.getLangOpts().CPlusPlus 10137 ? diag::err_typecheck_pointer_arith_void_type 10138 : diag::ext_gnu_void_ptr) 10139 << 0 /* one pointer */ << Pointer->getSourceRange(); 10140 } 10141 10142 /// Diagnose invalid arithmetic on a null pointer. 10143 /// 10144 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10145 /// idiom, which we recognize as a GNU extension. 10146 /// 10147 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10148 Expr *Pointer, bool IsGNUIdiom) { 10149 if (IsGNUIdiom) 10150 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10151 << Pointer->getSourceRange(); 10152 else 10153 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10154 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10155 } 10156 10157 /// Diagnose invalid arithmetic on two function pointers. 10158 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10159 Expr *LHS, Expr *RHS) { 10160 assert(LHS->getType()->isAnyPointerType()); 10161 assert(RHS->getType()->isAnyPointerType()); 10162 S.Diag(Loc, S.getLangOpts().CPlusPlus 10163 ? diag::err_typecheck_pointer_arith_function_type 10164 : diag::ext_gnu_ptr_func_arith) 10165 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10166 // We only show the second type if it differs from the first. 10167 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10168 RHS->getType()) 10169 << RHS->getType()->getPointeeType() 10170 << LHS->getSourceRange() << RHS->getSourceRange(); 10171 } 10172 10173 /// Diagnose invalid arithmetic on a function pointer. 10174 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10175 Expr *Pointer) { 10176 assert(Pointer->getType()->isAnyPointerType()); 10177 S.Diag(Loc, S.getLangOpts().CPlusPlus 10178 ? diag::err_typecheck_pointer_arith_function_type 10179 : diag::ext_gnu_ptr_func_arith) 10180 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10181 << 0 /* one pointer, so only one type */ 10182 << Pointer->getSourceRange(); 10183 } 10184 10185 /// Emit error if Operand is incomplete pointer type 10186 /// 10187 /// \returns True if pointer has incomplete type 10188 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10189 Expr *Operand) { 10190 QualType ResType = Operand->getType(); 10191 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10192 ResType = ResAtomicType->getValueType(); 10193 10194 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10195 QualType PointeeTy = ResType->getPointeeType(); 10196 return S.RequireCompleteSizedType( 10197 Loc, PointeeTy, 10198 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10199 Operand->getSourceRange()); 10200 } 10201 10202 /// Check the validity of an arithmetic pointer operand. 10203 /// 10204 /// If the operand has pointer type, this code will check for pointer types 10205 /// which are invalid in arithmetic operations. These will be diagnosed 10206 /// appropriately, including whether or not the use is supported as an 10207 /// extension. 10208 /// 10209 /// \returns True when the operand is valid to use (even if as an extension). 10210 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10211 Expr *Operand) { 10212 QualType ResType = Operand->getType(); 10213 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10214 ResType = ResAtomicType->getValueType(); 10215 10216 if (!ResType->isAnyPointerType()) return true; 10217 10218 QualType PointeeTy = ResType->getPointeeType(); 10219 if (PointeeTy->isVoidType()) { 10220 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10221 return !S.getLangOpts().CPlusPlus; 10222 } 10223 if (PointeeTy->isFunctionType()) { 10224 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10225 return !S.getLangOpts().CPlusPlus; 10226 } 10227 10228 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10229 10230 return true; 10231 } 10232 10233 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10234 /// operands. 10235 /// 10236 /// This routine will diagnose any invalid arithmetic on pointer operands much 10237 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10238 /// for emitting a single diagnostic even for operations where both LHS and RHS 10239 /// are (potentially problematic) pointers. 10240 /// 10241 /// \returns True when the operand is valid to use (even if as an extension). 10242 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10243 Expr *LHSExpr, Expr *RHSExpr) { 10244 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10245 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10246 if (!isLHSPointer && !isRHSPointer) return true; 10247 10248 QualType LHSPointeeTy, RHSPointeeTy; 10249 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10250 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10251 10252 // if both are pointers check if operation is valid wrt address spaces 10253 if (isLHSPointer && isRHSPointer) { 10254 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10255 S.Diag(Loc, 10256 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10257 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10258 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10259 return false; 10260 } 10261 } 10262 10263 // Check for arithmetic on pointers to incomplete types. 10264 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10265 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10266 if (isLHSVoidPtr || isRHSVoidPtr) { 10267 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10268 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10269 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10270 10271 return !S.getLangOpts().CPlusPlus; 10272 } 10273 10274 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10275 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10276 if (isLHSFuncPtr || isRHSFuncPtr) { 10277 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10278 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10279 RHSExpr); 10280 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10281 10282 return !S.getLangOpts().CPlusPlus; 10283 } 10284 10285 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10286 return false; 10287 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10288 return false; 10289 10290 return true; 10291 } 10292 10293 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10294 /// literal. 10295 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10296 Expr *LHSExpr, Expr *RHSExpr) { 10297 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10298 Expr* IndexExpr = RHSExpr; 10299 if (!StrExpr) { 10300 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10301 IndexExpr = LHSExpr; 10302 } 10303 10304 bool IsStringPlusInt = StrExpr && 10305 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10306 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10307 return; 10308 10309 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10310 Self.Diag(OpLoc, diag::warn_string_plus_int) 10311 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10312 10313 // Only print a fixit for "str" + int, not for int + "str". 10314 if (IndexExpr == RHSExpr) { 10315 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10316 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10317 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10318 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10319 << FixItHint::CreateInsertion(EndLoc, "]"); 10320 } else 10321 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10322 } 10323 10324 /// Emit a warning when adding a char literal to a string. 10325 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10326 Expr *LHSExpr, Expr *RHSExpr) { 10327 const Expr *StringRefExpr = LHSExpr; 10328 const CharacterLiteral *CharExpr = 10329 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10330 10331 if (!CharExpr) { 10332 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10333 StringRefExpr = RHSExpr; 10334 } 10335 10336 if (!CharExpr || !StringRefExpr) 10337 return; 10338 10339 const QualType StringType = StringRefExpr->getType(); 10340 10341 // Return if not a PointerType. 10342 if (!StringType->isAnyPointerType()) 10343 return; 10344 10345 // Return if not a CharacterType. 10346 if (!StringType->getPointeeType()->isAnyCharacterType()) 10347 return; 10348 10349 ASTContext &Ctx = Self.getASTContext(); 10350 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10351 10352 const QualType CharType = CharExpr->getType(); 10353 if (!CharType->isAnyCharacterType() && 10354 CharType->isIntegerType() && 10355 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10356 Self.Diag(OpLoc, diag::warn_string_plus_char) 10357 << DiagRange << Ctx.CharTy; 10358 } else { 10359 Self.Diag(OpLoc, diag::warn_string_plus_char) 10360 << DiagRange << CharExpr->getType(); 10361 } 10362 10363 // Only print a fixit for str + char, not for char + str. 10364 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10365 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10366 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10367 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10368 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10369 << FixItHint::CreateInsertion(EndLoc, "]"); 10370 } else { 10371 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10372 } 10373 } 10374 10375 /// Emit error when two pointers are incompatible. 10376 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10377 Expr *LHSExpr, Expr *RHSExpr) { 10378 assert(LHSExpr->getType()->isAnyPointerType()); 10379 assert(RHSExpr->getType()->isAnyPointerType()); 10380 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10381 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10382 << RHSExpr->getSourceRange(); 10383 } 10384 10385 // C99 6.5.6 10386 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10387 SourceLocation Loc, BinaryOperatorKind Opc, 10388 QualType* CompLHSTy) { 10389 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10390 10391 if (LHS.get()->getType()->isVectorType() || 10392 RHS.get()->getType()->isVectorType()) { 10393 QualType compType = CheckVectorOperands( 10394 LHS, RHS, Loc, CompLHSTy, 10395 /*AllowBothBool*/getLangOpts().AltiVec, 10396 /*AllowBoolConversions*/getLangOpts().ZVector); 10397 if (CompLHSTy) *CompLHSTy = compType; 10398 return compType; 10399 } 10400 10401 if (LHS.get()->getType()->isConstantMatrixType() || 10402 RHS.get()->getType()->isConstantMatrixType()) { 10403 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10404 } 10405 10406 QualType compType = UsualArithmeticConversions( 10407 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10408 if (LHS.isInvalid() || RHS.isInvalid()) 10409 return QualType(); 10410 10411 // Diagnose "string literal" '+' int and string '+' "char literal". 10412 if (Opc == BO_Add) { 10413 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10414 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10415 } 10416 10417 // handle the common case first (both operands are arithmetic). 10418 if (!compType.isNull() && compType->isArithmeticType()) { 10419 if (CompLHSTy) *CompLHSTy = compType; 10420 return compType; 10421 } 10422 10423 // Type-checking. Ultimately the pointer's going to be in PExp; 10424 // note that we bias towards the LHS being the pointer. 10425 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10426 10427 bool isObjCPointer; 10428 if (PExp->getType()->isPointerType()) { 10429 isObjCPointer = false; 10430 } else if (PExp->getType()->isObjCObjectPointerType()) { 10431 isObjCPointer = true; 10432 } else { 10433 std::swap(PExp, IExp); 10434 if (PExp->getType()->isPointerType()) { 10435 isObjCPointer = false; 10436 } else if (PExp->getType()->isObjCObjectPointerType()) { 10437 isObjCPointer = true; 10438 } else { 10439 return InvalidOperands(Loc, LHS, RHS); 10440 } 10441 } 10442 assert(PExp->getType()->isAnyPointerType()); 10443 10444 if (!IExp->getType()->isIntegerType()) 10445 return InvalidOperands(Loc, LHS, RHS); 10446 10447 // Adding to a null pointer results in undefined behavior. 10448 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10449 Context, Expr::NPC_ValueDependentIsNotNull)) { 10450 // In C++ adding zero to a null pointer is defined. 10451 Expr::EvalResult KnownVal; 10452 if (!getLangOpts().CPlusPlus || 10453 (!IExp->isValueDependent() && 10454 (!IExp->EvaluateAsInt(KnownVal, Context) || 10455 KnownVal.Val.getInt() != 0))) { 10456 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10457 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10458 Context, BO_Add, PExp, IExp); 10459 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10460 } 10461 } 10462 10463 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10464 return QualType(); 10465 10466 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10467 return QualType(); 10468 10469 // Check array bounds for pointer arithemtic 10470 CheckArrayAccess(PExp, IExp); 10471 10472 if (CompLHSTy) { 10473 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10474 if (LHSTy.isNull()) { 10475 LHSTy = LHS.get()->getType(); 10476 if (LHSTy->isPromotableIntegerType()) 10477 LHSTy = Context.getPromotedIntegerType(LHSTy); 10478 } 10479 *CompLHSTy = LHSTy; 10480 } 10481 10482 return PExp->getType(); 10483 } 10484 10485 // C99 6.5.6 10486 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10487 SourceLocation Loc, 10488 QualType* CompLHSTy) { 10489 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10490 10491 if (LHS.get()->getType()->isVectorType() || 10492 RHS.get()->getType()->isVectorType()) { 10493 QualType compType = CheckVectorOperands( 10494 LHS, RHS, Loc, CompLHSTy, 10495 /*AllowBothBool*/getLangOpts().AltiVec, 10496 /*AllowBoolConversions*/getLangOpts().ZVector); 10497 if (CompLHSTy) *CompLHSTy = compType; 10498 return compType; 10499 } 10500 10501 if (LHS.get()->getType()->isConstantMatrixType() || 10502 RHS.get()->getType()->isConstantMatrixType()) { 10503 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10504 } 10505 10506 QualType compType = UsualArithmeticConversions( 10507 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10508 if (LHS.isInvalid() || RHS.isInvalid()) 10509 return QualType(); 10510 10511 // Enforce type constraints: C99 6.5.6p3. 10512 10513 // Handle the common case first (both operands are arithmetic). 10514 if (!compType.isNull() && compType->isArithmeticType()) { 10515 if (CompLHSTy) *CompLHSTy = compType; 10516 return compType; 10517 } 10518 10519 // Either ptr - int or ptr - ptr. 10520 if (LHS.get()->getType()->isAnyPointerType()) { 10521 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10522 10523 // Diagnose bad cases where we step over interface counts. 10524 if (LHS.get()->getType()->isObjCObjectPointerType() && 10525 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10526 return QualType(); 10527 10528 // The result type of a pointer-int computation is the pointer type. 10529 if (RHS.get()->getType()->isIntegerType()) { 10530 // Subtracting from a null pointer should produce a warning. 10531 // The last argument to the diagnose call says this doesn't match the 10532 // GNU int-to-pointer idiom. 10533 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10534 Expr::NPC_ValueDependentIsNotNull)) { 10535 // In C++ adding zero to a null pointer is defined. 10536 Expr::EvalResult KnownVal; 10537 if (!getLangOpts().CPlusPlus || 10538 (!RHS.get()->isValueDependent() && 10539 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10540 KnownVal.Val.getInt() != 0))) { 10541 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10542 } 10543 } 10544 10545 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10546 return QualType(); 10547 10548 // Check array bounds for pointer arithemtic 10549 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10550 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10551 10552 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10553 return LHS.get()->getType(); 10554 } 10555 10556 // Handle pointer-pointer subtractions. 10557 if (const PointerType *RHSPTy 10558 = RHS.get()->getType()->getAs<PointerType>()) { 10559 QualType rpointee = RHSPTy->getPointeeType(); 10560 10561 if (getLangOpts().CPlusPlus) { 10562 // Pointee types must be the same: C++ [expr.add] 10563 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10564 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10565 } 10566 } else { 10567 // Pointee types must be compatible C99 6.5.6p3 10568 if (!Context.typesAreCompatible( 10569 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10570 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10571 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10572 return QualType(); 10573 } 10574 } 10575 10576 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10577 LHS.get(), RHS.get())) 10578 return QualType(); 10579 10580 // FIXME: Add warnings for nullptr - ptr. 10581 10582 // The pointee type may have zero size. As an extension, a structure or 10583 // union may have zero size or an array may have zero length. In this 10584 // case subtraction does not make sense. 10585 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10586 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10587 if (ElementSize.isZero()) { 10588 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10589 << rpointee.getUnqualifiedType() 10590 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10591 } 10592 } 10593 10594 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10595 return Context.getPointerDiffType(); 10596 } 10597 } 10598 10599 return InvalidOperands(Loc, LHS, RHS); 10600 } 10601 10602 static bool isScopedEnumerationType(QualType T) { 10603 if (const EnumType *ET = T->getAs<EnumType>()) 10604 return ET->getDecl()->isScoped(); 10605 return false; 10606 } 10607 10608 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10609 SourceLocation Loc, BinaryOperatorKind Opc, 10610 QualType LHSType) { 10611 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10612 // so skip remaining warnings as we don't want to modify values within Sema. 10613 if (S.getLangOpts().OpenCL) 10614 return; 10615 10616 // Check right/shifter operand 10617 Expr::EvalResult RHSResult; 10618 if (RHS.get()->isValueDependent() || 10619 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10620 return; 10621 llvm::APSInt Right = RHSResult.Val.getInt(); 10622 10623 if (Right.isNegative()) { 10624 S.DiagRuntimeBehavior(Loc, RHS.get(), 10625 S.PDiag(diag::warn_shift_negative) 10626 << RHS.get()->getSourceRange()); 10627 return; 10628 } 10629 10630 QualType LHSExprType = LHS.get()->getType(); 10631 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10632 if (LHSExprType->isExtIntType()) 10633 LeftSize = S.Context.getIntWidth(LHSExprType); 10634 else if (LHSExprType->isFixedPointType()) { 10635 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10636 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10637 } 10638 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10639 if (Right.uge(LeftBits)) { 10640 S.DiagRuntimeBehavior(Loc, RHS.get(), 10641 S.PDiag(diag::warn_shift_gt_typewidth) 10642 << RHS.get()->getSourceRange()); 10643 return; 10644 } 10645 10646 // FIXME: We probably need to handle fixed point types specially here. 10647 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10648 return; 10649 10650 // When left shifting an ICE which is signed, we can check for overflow which 10651 // according to C++ standards prior to C++2a has undefined behavior 10652 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10653 // more than the maximum value representable in the result type, so never 10654 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10655 // expression is still probably a bug.) 10656 Expr::EvalResult LHSResult; 10657 if (LHS.get()->isValueDependent() || 10658 LHSType->hasUnsignedIntegerRepresentation() || 10659 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10660 return; 10661 llvm::APSInt Left = LHSResult.Val.getInt(); 10662 10663 // If LHS does not have a signed type and non-negative value 10664 // then, the behavior is undefined before C++2a. Warn about it. 10665 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10666 !S.getLangOpts().CPlusPlus20) { 10667 S.DiagRuntimeBehavior(Loc, LHS.get(), 10668 S.PDiag(diag::warn_shift_lhs_negative) 10669 << LHS.get()->getSourceRange()); 10670 return; 10671 } 10672 10673 llvm::APInt ResultBits = 10674 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10675 if (LeftBits.uge(ResultBits)) 10676 return; 10677 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10678 Result = Result.shl(Right); 10679 10680 // Print the bit representation of the signed integer as an unsigned 10681 // hexadecimal number. 10682 SmallString<40> HexResult; 10683 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10684 10685 // If we are only missing a sign bit, this is less likely to result in actual 10686 // bugs -- if the result is cast back to an unsigned type, it will have the 10687 // expected value. Thus we place this behind a different warning that can be 10688 // turned off separately if needed. 10689 if (LeftBits == ResultBits - 1) { 10690 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10691 << HexResult << LHSType 10692 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10693 return; 10694 } 10695 10696 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10697 << HexResult.str() << Result.getMinSignedBits() << LHSType 10698 << Left.getBitWidth() << LHS.get()->getSourceRange() 10699 << RHS.get()->getSourceRange(); 10700 } 10701 10702 /// Return the resulting type when a vector is shifted 10703 /// by a scalar or vector shift amount. 10704 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10705 SourceLocation Loc, bool IsCompAssign) { 10706 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10707 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10708 !LHS.get()->getType()->isVectorType()) { 10709 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10710 << RHS.get()->getType() << LHS.get()->getType() 10711 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10712 return QualType(); 10713 } 10714 10715 if (!IsCompAssign) { 10716 LHS = S.UsualUnaryConversions(LHS.get()); 10717 if (LHS.isInvalid()) return QualType(); 10718 } 10719 10720 RHS = S.UsualUnaryConversions(RHS.get()); 10721 if (RHS.isInvalid()) return QualType(); 10722 10723 QualType LHSType = LHS.get()->getType(); 10724 // Note that LHS might be a scalar because the routine calls not only in 10725 // OpenCL case. 10726 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10727 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10728 10729 // Note that RHS might not be a vector. 10730 QualType RHSType = RHS.get()->getType(); 10731 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10732 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10733 10734 // The operands need to be integers. 10735 if (!LHSEleType->isIntegerType()) { 10736 S.Diag(Loc, diag::err_typecheck_expect_int) 10737 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10738 return QualType(); 10739 } 10740 10741 if (!RHSEleType->isIntegerType()) { 10742 S.Diag(Loc, diag::err_typecheck_expect_int) 10743 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10744 return QualType(); 10745 } 10746 10747 if (!LHSVecTy) { 10748 assert(RHSVecTy); 10749 if (IsCompAssign) 10750 return RHSType; 10751 if (LHSEleType != RHSEleType) { 10752 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10753 LHSEleType = RHSEleType; 10754 } 10755 QualType VecTy = 10756 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10757 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10758 LHSType = VecTy; 10759 } else if (RHSVecTy) { 10760 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10761 // are applied component-wise. So if RHS is a vector, then ensure 10762 // that the number of elements is the same as LHS... 10763 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10764 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10765 << LHS.get()->getType() << RHS.get()->getType() 10766 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10767 return QualType(); 10768 } 10769 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10770 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10771 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10772 if (LHSBT != RHSBT && 10773 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10774 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10775 << LHS.get()->getType() << RHS.get()->getType() 10776 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10777 } 10778 } 10779 } else { 10780 // ...else expand RHS to match the number of elements in LHS. 10781 QualType VecTy = 10782 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10783 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10784 } 10785 10786 return LHSType; 10787 } 10788 10789 // C99 6.5.7 10790 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10791 SourceLocation Loc, BinaryOperatorKind Opc, 10792 bool IsCompAssign) { 10793 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10794 10795 // Vector shifts promote their scalar inputs to vector type. 10796 if (LHS.get()->getType()->isVectorType() || 10797 RHS.get()->getType()->isVectorType()) { 10798 if (LangOpts.ZVector) { 10799 // The shift operators for the z vector extensions work basically 10800 // like general shifts, except that neither the LHS nor the RHS is 10801 // allowed to be a "vector bool". 10802 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10803 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10804 return InvalidOperands(Loc, LHS, RHS); 10805 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10806 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10807 return InvalidOperands(Loc, LHS, RHS); 10808 } 10809 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10810 } 10811 10812 // Shifts don't perform usual arithmetic conversions, they just do integer 10813 // promotions on each operand. C99 6.5.7p3 10814 10815 // For the LHS, do usual unary conversions, but then reset them away 10816 // if this is a compound assignment. 10817 ExprResult OldLHS = LHS; 10818 LHS = UsualUnaryConversions(LHS.get()); 10819 if (LHS.isInvalid()) 10820 return QualType(); 10821 QualType LHSType = LHS.get()->getType(); 10822 if (IsCompAssign) LHS = OldLHS; 10823 10824 // The RHS is simpler. 10825 RHS = UsualUnaryConversions(RHS.get()); 10826 if (RHS.isInvalid()) 10827 return QualType(); 10828 QualType RHSType = RHS.get()->getType(); 10829 10830 // C99 6.5.7p2: Each of the operands shall have integer type. 10831 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10832 if ((!LHSType->isFixedPointOrIntegerType() && 10833 !LHSType->hasIntegerRepresentation()) || 10834 !RHSType->hasIntegerRepresentation()) 10835 return InvalidOperands(Loc, LHS, RHS); 10836 10837 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10838 // hasIntegerRepresentation() above instead of this. 10839 if (isScopedEnumerationType(LHSType) || 10840 isScopedEnumerationType(RHSType)) { 10841 return InvalidOperands(Loc, LHS, RHS); 10842 } 10843 // Sanity-check shift operands 10844 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10845 10846 // "The type of the result is that of the promoted left operand." 10847 return LHSType; 10848 } 10849 10850 /// Diagnose bad pointer comparisons. 10851 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10852 ExprResult &LHS, ExprResult &RHS, 10853 bool IsError) { 10854 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10855 : diag::ext_typecheck_comparison_of_distinct_pointers) 10856 << LHS.get()->getType() << RHS.get()->getType() 10857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10858 } 10859 10860 /// Returns false if the pointers are converted to a composite type, 10861 /// true otherwise. 10862 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10863 ExprResult &LHS, ExprResult &RHS) { 10864 // C++ [expr.rel]p2: 10865 // [...] Pointer conversions (4.10) and qualification 10866 // conversions (4.4) are performed on pointer operands (or on 10867 // a pointer operand and a null pointer constant) to bring 10868 // them to their composite pointer type. [...] 10869 // 10870 // C++ [expr.eq]p1 uses the same notion for (in)equality 10871 // comparisons of pointers. 10872 10873 QualType LHSType = LHS.get()->getType(); 10874 QualType RHSType = RHS.get()->getType(); 10875 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10876 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10877 10878 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10879 if (T.isNull()) { 10880 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10881 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10882 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10883 else 10884 S.InvalidOperands(Loc, LHS, RHS); 10885 return true; 10886 } 10887 10888 return false; 10889 } 10890 10891 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10892 ExprResult &LHS, 10893 ExprResult &RHS, 10894 bool IsError) { 10895 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10896 : diag::ext_typecheck_comparison_of_fptr_to_void) 10897 << LHS.get()->getType() << RHS.get()->getType() 10898 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10899 } 10900 10901 static bool isObjCObjectLiteral(ExprResult &E) { 10902 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10903 case Stmt::ObjCArrayLiteralClass: 10904 case Stmt::ObjCDictionaryLiteralClass: 10905 case Stmt::ObjCStringLiteralClass: 10906 case Stmt::ObjCBoxedExprClass: 10907 return true; 10908 default: 10909 // Note that ObjCBoolLiteral is NOT an object literal! 10910 return false; 10911 } 10912 } 10913 10914 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10915 const ObjCObjectPointerType *Type = 10916 LHS->getType()->getAs<ObjCObjectPointerType>(); 10917 10918 // If this is not actually an Objective-C object, bail out. 10919 if (!Type) 10920 return false; 10921 10922 // Get the LHS object's interface type. 10923 QualType InterfaceType = Type->getPointeeType(); 10924 10925 // If the RHS isn't an Objective-C object, bail out. 10926 if (!RHS->getType()->isObjCObjectPointerType()) 10927 return false; 10928 10929 // Try to find the -isEqual: method. 10930 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10931 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10932 InterfaceType, 10933 /*IsInstance=*/true); 10934 if (!Method) { 10935 if (Type->isObjCIdType()) { 10936 // For 'id', just check the global pool. 10937 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10938 /*receiverId=*/true); 10939 } else { 10940 // Check protocols. 10941 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10942 /*IsInstance=*/true); 10943 } 10944 } 10945 10946 if (!Method) 10947 return false; 10948 10949 QualType T = Method->parameters()[0]->getType(); 10950 if (!T->isObjCObjectPointerType()) 10951 return false; 10952 10953 QualType R = Method->getReturnType(); 10954 if (!R->isScalarType()) 10955 return false; 10956 10957 return true; 10958 } 10959 10960 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10961 FromE = FromE->IgnoreParenImpCasts(); 10962 switch (FromE->getStmtClass()) { 10963 default: 10964 break; 10965 case Stmt::ObjCStringLiteralClass: 10966 // "string literal" 10967 return LK_String; 10968 case Stmt::ObjCArrayLiteralClass: 10969 // "array literal" 10970 return LK_Array; 10971 case Stmt::ObjCDictionaryLiteralClass: 10972 // "dictionary literal" 10973 return LK_Dictionary; 10974 case Stmt::BlockExprClass: 10975 return LK_Block; 10976 case Stmt::ObjCBoxedExprClass: { 10977 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10978 switch (Inner->getStmtClass()) { 10979 case Stmt::IntegerLiteralClass: 10980 case Stmt::FloatingLiteralClass: 10981 case Stmt::CharacterLiteralClass: 10982 case Stmt::ObjCBoolLiteralExprClass: 10983 case Stmt::CXXBoolLiteralExprClass: 10984 // "numeric literal" 10985 return LK_Numeric; 10986 case Stmt::ImplicitCastExprClass: { 10987 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10988 // Boolean literals can be represented by implicit casts. 10989 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10990 return LK_Numeric; 10991 break; 10992 } 10993 default: 10994 break; 10995 } 10996 return LK_Boxed; 10997 } 10998 } 10999 return LK_None; 11000 } 11001 11002 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11003 ExprResult &LHS, ExprResult &RHS, 11004 BinaryOperator::Opcode Opc){ 11005 Expr *Literal; 11006 Expr *Other; 11007 if (isObjCObjectLiteral(LHS)) { 11008 Literal = LHS.get(); 11009 Other = RHS.get(); 11010 } else { 11011 Literal = RHS.get(); 11012 Other = LHS.get(); 11013 } 11014 11015 // Don't warn on comparisons against nil. 11016 Other = Other->IgnoreParenCasts(); 11017 if (Other->isNullPointerConstant(S.getASTContext(), 11018 Expr::NPC_ValueDependentIsNotNull)) 11019 return; 11020 11021 // This should be kept in sync with warn_objc_literal_comparison. 11022 // LK_String should always be after the other literals, since it has its own 11023 // warning flag. 11024 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11025 assert(LiteralKind != Sema::LK_Block); 11026 if (LiteralKind == Sema::LK_None) { 11027 llvm_unreachable("Unknown Objective-C object literal kind"); 11028 } 11029 11030 if (LiteralKind == Sema::LK_String) 11031 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11032 << Literal->getSourceRange(); 11033 else 11034 S.Diag(Loc, diag::warn_objc_literal_comparison) 11035 << LiteralKind << Literal->getSourceRange(); 11036 11037 if (BinaryOperator::isEqualityOp(Opc) && 11038 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11039 SourceLocation Start = LHS.get()->getBeginLoc(); 11040 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11041 CharSourceRange OpRange = 11042 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11043 11044 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11045 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11046 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11047 << FixItHint::CreateInsertion(End, "]"); 11048 } 11049 } 11050 11051 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11052 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11053 ExprResult &RHS, SourceLocation Loc, 11054 BinaryOperatorKind Opc) { 11055 // Check that left hand side is !something. 11056 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11057 if (!UO || UO->getOpcode() != UO_LNot) return; 11058 11059 // Only check if the right hand side is non-bool arithmetic type. 11060 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11061 11062 // Make sure that the something in !something is not bool. 11063 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11064 if (SubExpr->isKnownToHaveBooleanValue()) return; 11065 11066 // Emit warning. 11067 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11068 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11069 << Loc << IsBitwiseOp; 11070 11071 // First note suggest !(x < y) 11072 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11073 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11074 FirstClose = S.getLocForEndOfToken(FirstClose); 11075 if (FirstClose.isInvalid()) 11076 FirstOpen = SourceLocation(); 11077 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11078 << IsBitwiseOp 11079 << FixItHint::CreateInsertion(FirstOpen, "(") 11080 << FixItHint::CreateInsertion(FirstClose, ")"); 11081 11082 // Second note suggests (!x) < y 11083 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11084 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11085 SecondClose = S.getLocForEndOfToken(SecondClose); 11086 if (SecondClose.isInvalid()) 11087 SecondOpen = SourceLocation(); 11088 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11089 << FixItHint::CreateInsertion(SecondOpen, "(") 11090 << FixItHint::CreateInsertion(SecondClose, ")"); 11091 } 11092 11093 // Returns true if E refers to a non-weak array. 11094 static bool checkForArray(const Expr *E) { 11095 const ValueDecl *D = nullptr; 11096 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11097 D = DR->getDecl(); 11098 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11099 if (Mem->isImplicitAccess()) 11100 D = Mem->getMemberDecl(); 11101 } 11102 if (!D) 11103 return false; 11104 return D->getType()->isArrayType() && !D->isWeak(); 11105 } 11106 11107 /// Diagnose some forms of syntactically-obvious tautological comparison. 11108 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11109 Expr *LHS, Expr *RHS, 11110 BinaryOperatorKind Opc) { 11111 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11112 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11113 11114 QualType LHSType = LHS->getType(); 11115 QualType RHSType = RHS->getType(); 11116 if (LHSType->hasFloatingRepresentation() || 11117 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11118 S.inTemplateInstantiation()) 11119 return; 11120 11121 // Comparisons between two array types are ill-formed for operator<=>, so 11122 // we shouldn't emit any additional warnings about it. 11123 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11124 return; 11125 11126 // For non-floating point types, check for self-comparisons of the form 11127 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11128 // often indicate logic errors in the program. 11129 // 11130 // NOTE: Don't warn about comparison expressions resulting from macro 11131 // expansion. Also don't warn about comparisons which are only self 11132 // comparisons within a template instantiation. The warnings should catch 11133 // obvious cases in the definition of the template anyways. The idea is to 11134 // warn when the typed comparison operator will always evaluate to the same 11135 // result. 11136 11137 // Used for indexing into %select in warn_comparison_always 11138 enum { 11139 AlwaysConstant, 11140 AlwaysTrue, 11141 AlwaysFalse, 11142 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11143 }; 11144 11145 // C++2a [depr.array.comp]: 11146 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11147 // operands of array type are deprecated. 11148 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11149 RHSStripped->getType()->isArrayType()) { 11150 S.Diag(Loc, diag::warn_depr_array_comparison) 11151 << LHS->getSourceRange() << RHS->getSourceRange() 11152 << LHSStripped->getType() << RHSStripped->getType(); 11153 // Carry on to produce the tautological comparison warning, if this 11154 // expression is potentially-evaluated, we can resolve the array to a 11155 // non-weak declaration, and so on. 11156 } 11157 11158 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11159 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11160 unsigned Result; 11161 switch (Opc) { 11162 case BO_EQ: 11163 case BO_LE: 11164 case BO_GE: 11165 Result = AlwaysTrue; 11166 break; 11167 case BO_NE: 11168 case BO_LT: 11169 case BO_GT: 11170 Result = AlwaysFalse; 11171 break; 11172 case BO_Cmp: 11173 Result = AlwaysEqual; 11174 break; 11175 default: 11176 Result = AlwaysConstant; 11177 break; 11178 } 11179 S.DiagRuntimeBehavior(Loc, nullptr, 11180 S.PDiag(diag::warn_comparison_always) 11181 << 0 /*self-comparison*/ 11182 << Result); 11183 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11184 // What is it always going to evaluate to? 11185 unsigned Result; 11186 switch (Opc) { 11187 case BO_EQ: // e.g. array1 == array2 11188 Result = AlwaysFalse; 11189 break; 11190 case BO_NE: // e.g. array1 != array2 11191 Result = AlwaysTrue; 11192 break; 11193 default: // e.g. array1 <= array2 11194 // The best we can say is 'a constant' 11195 Result = AlwaysConstant; 11196 break; 11197 } 11198 S.DiagRuntimeBehavior(Loc, nullptr, 11199 S.PDiag(diag::warn_comparison_always) 11200 << 1 /*array comparison*/ 11201 << Result); 11202 } 11203 } 11204 11205 if (isa<CastExpr>(LHSStripped)) 11206 LHSStripped = LHSStripped->IgnoreParenCasts(); 11207 if (isa<CastExpr>(RHSStripped)) 11208 RHSStripped = RHSStripped->IgnoreParenCasts(); 11209 11210 // Warn about comparisons against a string constant (unless the other 11211 // operand is null); the user probably wants string comparison function. 11212 Expr *LiteralString = nullptr; 11213 Expr *LiteralStringStripped = nullptr; 11214 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11215 !RHSStripped->isNullPointerConstant(S.Context, 11216 Expr::NPC_ValueDependentIsNull)) { 11217 LiteralString = LHS; 11218 LiteralStringStripped = LHSStripped; 11219 } else if ((isa<StringLiteral>(RHSStripped) || 11220 isa<ObjCEncodeExpr>(RHSStripped)) && 11221 !LHSStripped->isNullPointerConstant(S.Context, 11222 Expr::NPC_ValueDependentIsNull)) { 11223 LiteralString = RHS; 11224 LiteralStringStripped = RHSStripped; 11225 } 11226 11227 if (LiteralString) { 11228 S.DiagRuntimeBehavior(Loc, nullptr, 11229 S.PDiag(diag::warn_stringcompare) 11230 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11231 << LiteralString->getSourceRange()); 11232 } 11233 } 11234 11235 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11236 switch (CK) { 11237 default: { 11238 #ifndef NDEBUG 11239 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11240 << "\n"; 11241 #endif 11242 llvm_unreachable("unhandled cast kind"); 11243 } 11244 case CK_UserDefinedConversion: 11245 return ICK_Identity; 11246 case CK_LValueToRValue: 11247 return ICK_Lvalue_To_Rvalue; 11248 case CK_ArrayToPointerDecay: 11249 return ICK_Array_To_Pointer; 11250 case CK_FunctionToPointerDecay: 11251 return ICK_Function_To_Pointer; 11252 case CK_IntegralCast: 11253 return ICK_Integral_Conversion; 11254 case CK_FloatingCast: 11255 return ICK_Floating_Conversion; 11256 case CK_IntegralToFloating: 11257 case CK_FloatingToIntegral: 11258 return ICK_Floating_Integral; 11259 case CK_IntegralComplexCast: 11260 case CK_FloatingComplexCast: 11261 case CK_FloatingComplexToIntegralComplex: 11262 case CK_IntegralComplexToFloatingComplex: 11263 return ICK_Complex_Conversion; 11264 case CK_FloatingComplexToReal: 11265 case CK_FloatingRealToComplex: 11266 case CK_IntegralComplexToReal: 11267 case CK_IntegralRealToComplex: 11268 return ICK_Complex_Real; 11269 } 11270 } 11271 11272 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11273 QualType FromType, 11274 SourceLocation Loc) { 11275 // Check for a narrowing implicit conversion. 11276 StandardConversionSequence SCS; 11277 SCS.setAsIdentityConversion(); 11278 SCS.setToType(0, FromType); 11279 SCS.setToType(1, ToType); 11280 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11281 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11282 11283 APValue PreNarrowingValue; 11284 QualType PreNarrowingType; 11285 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11286 PreNarrowingType, 11287 /*IgnoreFloatToIntegralConversion*/ true)) { 11288 case NK_Dependent_Narrowing: 11289 // Implicit conversion to a narrower type, but the expression is 11290 // value-dependent so we can't tell whether it's actually narrowing. 11291 case NK_Not_Narrowing: 11292 return false; 11293 11294 case NK_Constant_Narrowing: 11295 // Implicit conversion to a narrower type, and the value is not a constant 11296 // expression. 11297 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11298 << /*Constant*/ 1 11299 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11300 return true; 11301 11302 case NK_Variable_Narrowing: 11303 // Implicit conversion to a narrower type, and the value is not a constant 11304 // expression. 11305 case NK_Type_Narrowing: 11306 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11307 << /*Constant*/ 0 << FromType << ToType; 11308 // TODO: It's not a constant expression, but what if the user intended it 11309 // to be? Can we produce notes to help them figure out why it isn't? 11310 return true; 11311 } 11312 llvm_unreachable("unhandled case in switch"); 11313 } 11314 11315 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11316 ExprResult &LHS, 11317 ExprResult &RHS, 11318 SourceLocation Loc) { 11319 QualType LHSType = LHS.get()->getType(); 11320 QualType RHSType = RHS.get()->getType(); 11321 // Dig out the original argument type and expression before implicit casts 11322 // were applied. These are the types/expressions we need to check the 11323 // [expr.spaceship] requirements against. 11324 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11325 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11326 QualType LHSStrippedType = LHSStripped.get()->getType(); 11327 QualType RHSStrippedType = RHSStripped.get()->getType(); 11328 11329 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11330 // other is not, the program is ill-formed. 11331 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11332 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11333 return QualType(); 11334 } 11335 11336 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11337 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11338 RHSStrippedType->isEnumeralType(); 11339 if (NumEnumArgs == 1) { 11340 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11341 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11342 if (OtherTy->hasFloatingRepresentation()) { 11343 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11344 return QualType(); 11345 } 11346 } 11347 if (NumEnumArgs == 2) { 11348 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11349 // type E, the operator yields the result of converting the operands 11350 // to the underlying type of E and applying <=> to the converted operands. 11351 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11352 S.InvalidOperands(Loc, LHS, RHS); 11353 return QualType(); 11354 } 11355 QualType IntType = 11356 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11357 assert(IntType->isArithmeticType()); 11358 11359 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11360 // promote the boolean type, and all other promotable integer types, to 11361 // avoid this. 11362 if (IntType->isPromotableIntegerType()) 11363 IntType = S.Context.getPromotedIntegerType(IntType); 11364 11365 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11366 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11367 LHSType = RHSType = IntType; 11368 } 11369 11370 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11371 // usual arithmetic conversions are applied to the operands. 11372 QualType Type = 11373 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11374 if (LHS.isInvalid() || RHS.isInvalid()) 11375 return QualType(); 11376 if (Type.isNull()) 11377 return S.InvalidOperands(Loc, LHS, RHS); 11378 11379 Optional<ComparisonCategoryType> CCT = 11380 getComparisonCategoryForBuiltinCmp(Type); 11381 if (!CCT) 11382 return S.InvalidOperands(Loc, LHS, RHS); 11383 11384 bool HasNarrowing = checkThreeWayNarrowingConversion( 11385 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11386 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11387 RHS.get()->getBeginLoc()); 11388 if (HasNarrowing) 11389 return QualType(); 11390 11391 assert(!Type.isNull() && "composite type for <=> has not been set"); 11392 11393 return S.CheckComparisonCategoryType( 11394 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11395 } 11396 11397 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11398 ExprResult &RHS, 11399 SourceLocation Loc, 11400 BinaryOperatorKind Opc) { 11401 if (Opc == BO_Cmp) 11402 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11403 11404 // C99 6.5.8p3 / C99 6.5.9p4 11405 QualType Type = 11406 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11407 if (LHS.isInvalid() || RHS.isInvalid()) 11408 return QualType(); 11409 if (Type.isNull()) 11410 return S.InvalidOperands(Loc, LHS, RHS); 11411 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11412 11413 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11414 return S.InvalidOperands(Loc, LHS, RHS); 11415 11416 // Check for comparisons of floating point operands using != and ==. 11417 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11418 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11419 11420 // The result of comparisons is 'bool' in C++, 'int' in C. 11421 return S.Context.getLogicalOperationType(); 11422 } 11423 11424 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11425 if (!NullE.get()->getType()->isAnyPointerType()) 11426 return; 11427 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11428 if (!E.get()->getType()->isAnyPointerType() && 11429 E.get()->isNullPointerConstant(Context, 11430 Expr::NPC_ValueDependentIsNotNull) == 11431 Expr::NPCK_ZeroExpression) { 11432 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11433 if (CL->getValue() == 0) 11434 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11435 << NullValue 11436 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11437 NullValue ? "NULL" : "(void *)0"); 11438 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11439 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11440 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11441 if (T == Context.CharTy) 11442 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11443 << NullValue 11444 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11445 NullValue ? "NULL" : "(void *)0"); 11446 } 11447 } 11448 } 11449 11450 // C99 6.5.8, C++ [expr.rel] 11451 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11452 SourceLocation Loc, 11453 BinaryOperatorKind Opc) { 11454 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11455 bool IsThreeWay = Opc == BO_Cmp; 11456 bool IsOrdered = IsRelational || IsThreeWay; 11457 auto IsAnyPointerType = [](ExprResult E) { 11458 QualType Ty = E.get()->getType(); 11459 return Ty->isPointerType() || Ty->isMemberPointerType(); 11460 }; 11461 11462 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11463 // type, array-to-pointer, ..., conversions are performed on both operands to 11464 // bring them to their composite type. 11465 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11466 // any type-related checks. 11467 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11468 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11469 if (LHS.isInvalid()) 11470 return QualType(); 11471 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11472 if (RHS.isInvalid()) 11473 return QualType(); 11474 } else { 11475 LHS = DefaultLvalueConversion(LHS.get()); 11476 if (LHS.isInvalid()) 11477 return QualType(); 11478 RHS = DefaultLvalueConversion(RHS.get()); 11479 if (RHS.isInvalid()) 11480 return QualType(); 11481 } 11482 11483 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11484 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11485 CheckPtrComparisonWithNullChar(LHS, RHS); 11486 CheckPtrComparisonWithNullChar(RHS, LHS); 11487 } 11488 11489 // Handle vector comparisons separately. 11490 if (LHS.get()->getType()->isVectorType() || 11491 RHS.get()->getType()->isVectorType()) 11492 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11493 11494 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11495 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11496 11497 QualType LHSType = LHS.get()->getType(); 11498 QualType RHSType = RHS.get()->getType(); 11499 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11500 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11501 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11502 11503 const Expr::NullPointerConstantKind LHSNullKind = 11504 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11505 const Expr::NullPointerConstantKind RHSNullKind = 11506 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11507 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11508 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11509 11510 auto computeResultTy = [&]() { 11511 if (Opc != BO_Cmp) 11512 return Context.getLogicalOperationType(); 11513 assert(getLangOpts().CPlusPlus); 11514 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11515 11516 QualType CompositeTy = LHS.get()->getType(); 11517 assert(!CompositeTy->isReferenceType()); 11518 11519 Optional<ComparisonCategoryType> CCT = 11520 getComparisonCategoryForBuiltinCmp(CompositeTy); 11521 if (!CCT) 11522 return InvalidOperands(Loc, LHS, RHS); 11523 11524 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11525 // P0946R0: Comparisons between a null pointer constant and an object 11526 // pointer result in std::strong_equality, which is ill-formed under 11527 // P1959R0. 11528 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11529 << (LHSIsNull ? LHS.get()->getSourceRange() 11530 : RHS.get()->getSourceRange()); 11531 return QualType(); 11532 } 11533 11534 return CheckComparisonCategoryType( 11535 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11536 }; 11537 11538 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11539 bool IsEquality = Opc == BO_EQ; 11540 if (RHSIsNull) 11541 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11542 RHS.get()->getSourceRange()); 11543 else 11544 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11545 LHS.get()->getSourceRange()); 11546 } 11547 11548 if ((LHSType->isIntegerType() && !LHSIsNull) || 11549 (RHSType->isIntegerType() && !RHSIsNull)) { 11550 // Skip normal pointer conversion checks in this case; we have better 11551 // diagnostics for this below. 11552 } else if (getLangOpts().CPlusPlus) { 11553 // Equality comparison of a function pointer to a void pointer is invalid, 11554 // but we allow it as an extension. 11555 // FIXME: If we really want to allow this, should it be part of composite 11556 // pointer type computation so it works in conditionals too? 11557 if (!IsOrdered && 11558 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11559 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11560 // This is a gcc extension compatibility comparison. 11561 // In a SFINAE context, we treat this as a hard error to maintain 11562 // conformance with the C++ standard. 11563 diagnoseFunctionPointerToVoidComparison( 11564 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11565 11566 if (isSFINAEContext()) 11567 return QualType(); 11568 11569 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11570 return computeResultTy(); 11571 } 11572 11573 // C++ [expr.eq]p2: 11574 // If at least one operand is a pointer [...] bring them to their 11575 // composite pointer type. 11576 // C++ [expr.spaceship]p6 11577 // If at least one of the operands is of pointer type, [...] bring them 11578 // to their composite pointer type. 11579 // C++ [expr.rel]p2: 11580 // If both operands are pointers, [...] bring them to their composite 11581 // pointer type. 11582 // For <=>, the only valid non-pointer types are arrays and functions, and 11583 // we already decayed those, so this is really the same as the relational 11584 // comparison rule. 11585 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11586 (IsOrdered ? 2 : 1) && 11587 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11588 RHSType->isObjCObjectPointerType()))) { 11589 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11590 return QualType(); 11591 return computeResultTy(); 11592 } 11593 } else if (LHSType->isPointerType() && 11594 RHSType->isPointerType()) { // C99 6.5.8p2 11595 // All of the following pointer-related warnings are GCC extensions, except 11596 // when handling null pointer constants. 11597 QualType LCanPointeeTy = 11598 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11599 QualType RCanPointeeTy = 11600 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11601 11602 // C99 6.5.9p2 and C99 6.5.8p2 11603 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11604 RCanPointeeTy.getUnqualifiedType())) { 11605 if (IsRelational) { 11606 // Pointers both need to point to complete or incomplete types 11607 if ((LCanPointeeTy->isIncompleteType() != 11608 RCanPointeeTy->isIncompleteType()) && 11609 !getLangOpts().C11) { 11610 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11611 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11612 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11613 << RCanPointeeTy->isIncompleteType(); 11614 } 11615 if (LCanPointeeTy->isFunctionType()) { 11616 // Valid unless a relational comparison of function pointers 11617 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11618 << LHSType << RHSType << LHS.get()->getSourceRange() 11619 << RHS.get()->getSourceRange(); 11620 } 11621 } 11622 } else if (!IsRelational && 11623 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11624 // Valid unless comparison between non-null pointer and function pointer 11625 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11626 && !LHSIsNull && !RHSIsNull) 11627 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11628 /*isError*/false); 11629 } else { 11630 // Invalid 11631 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11632 } 11633 if (LCanPointeeTy != RCanPointeeTy) { 11634 // Treat NULL constant as a special case in OpenCL. 11635 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11636 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11637 Diag(Loc, 11638 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11639 << LHSType << RHSType << 0 /* comparison */ 11640 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11641 } 11642 } 11643 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11644 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11645 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11646 : CK_BitCast; 11647 if (LHSIsNull && !RHSIsNull) 11648 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11649 else 11650 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11651 } 11652 return computeResultTy(); 11653 } 11654 11655 if (getLangOpts().CPlusPlus) { 11656 // C++ [expr.eq]p4: 11657 // Two operands of type std::nullptr_t or one operand of type 11658 // std::nullptr_t and the other a null pointer constant compare equal. 11659 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11660 if (LHSType->isNullPtrType()) { 11661 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11662 return computeResultTy(); 11663 } 11664 if (RHSType->isNullPtrType()) { 11665 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11666 return computeResultTy(); 11667 } 11668 } 11669 11670 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11671 // These aren't covered by the composite pointer type rules. 11672 if (!IsOrdered && RHSType->isNullPtrType() && 11673 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11674 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11675 return computeResultTy(); 11676 } 11677 if (!IsOrdered && LHSType->isNullPtrType() && 11678 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11679 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11680 return computeResultTy(); 11681 } 11682 11683 if (IsRelational && 11684 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11685 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11686 // HACK: Relational comparison of nullptr_t against a pointer type is 11687 // invalid per DR583, but we allow it within std::less<> and friends, 11688 // since otherwise common uses of it break. 11689 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11690 // friends to have std::nullptr_t overload candidates. 11691 DeclContext *DC = CurContext; 11692 if (isa<FunctionDecl>(DC)) 11693 DC = DC->getParent(); 11694 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11695 if (CTSD->isInStdNamespace() && 11696 llvm::StringSwitch<bool>(CTSD->getName()) 11697 .Cases("less", "less_equal", "greater", "greater_equal", true) 11698 .Default(false)) { 11699 if (RHSType->isNullPtrType()) 11700 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11701 else 11702 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11703 return computeResultTy(); 11704 } 11705 } 11706 } 11707 11708 // C++ [expr.eq]p2: 11709 // If at least one operand is a pointer to member, [...] bring them to 11710 // their composite pointer type. 11711 if (!IsOrdered && 11712 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11713 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11714 return QualType(); 11715 else 11716 return computeResultTy(); 11717 } 11718 } 11719 11720 // Handle block pointer types. 11721 if (!IsOrdered && LHSType->isBlockPointerType() && 11722 RHSType->isBlockPointerType()) { 11723 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11724 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11725 11726 if (!LHSIsNull && !RHSIsNull && 11727 !Context.typesAreCompatible(lpointee, rpointee)) { 11728 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11729 << LHSType << RHSType << LHS.get()->getSourceRange() 11730 << RHS.get()->getSourceRange(); 11731 } 11732 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11733 return computeResultTy(); 11734 } 11735 11736 // Allow block pointers to be compared with null pointer constants. 11737 if (!IsOrdered 11738 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11739 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11740 if (!LHSIsNull && !RHSIsNull) { 11741 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11742 ->getPointeeType()->isVoidType()) 11743 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11744 ->getPointeeType()->isVoidType()))) 11745 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11746 << LHSType << RHSType << LHS.get()->getSourceRange() 11747 << RHS.get()->getSourceRange(); 11748 } 11749 if (LHSIsNull && !RHSIsNull) 11750 LHS = ImpCastExprToType(LHS.get(), RHSType, 11751 RHSType->isPointerType() ? CK_BitCast 11752 : CK_AnyPointerToBlockPointerCast); 11753 else 11754 RHS = ImpCastExprToType(RHS.get(), LHSType, 11755 LHSType->isPointerType() ? CK_BitCast 11756 : CK_AnyPointerToBlockPointerCast); 11757 return computeResultTy(); 11758 } 11759 11760 if (LHSType->isObjCObjectPointerType() || 11761 RHSType->isObjCObjectPointerType()) { 11762 const PointerType *LPT = LHSType->getAs<PointerType>(); 11763 const PointerType *RPT = RHSType->getAs<PointerType>(); 11764 if (LPT || RPT) { 11765 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11766 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11767 11768 if (!LPtrToVoid && !RPtrToVoid && 11769 !Context.typesAreCompatible(LHSType, RHSType)) { 11770 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11771 /*isError*/false); 11772 } 11773 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11774 // the RHS, but we have test coverage for this behavior. 11775 // FIXME: Consider using convertPointersToCompositeType in C++. 11776 if (LHSIsNull && !RHSIsNull) { 11777 Expr *E = LHS.get(); 11778 if (getLangOpts().ObjCAutoRefCount) 11779 CheckObjCConversion(SourceRange(), RHSType, E, 11780 CCK_ImplicitConversion); 11781 LHS = ImpCastExprToType(E, RHSType, 11782 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11783 } 11784 else { 11785 Expr *E = RHS.get(); 11786 if (getLangOpts().ObjCAutoRefCount) 11787 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11788 /*Diagnose=*/true, 11789 /*DiagnoseCFAudited=*/false, Opc); 11790 RHS = ImpCastExprToType(E, LHSType, 11791 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11792 } 11793 return computeResultTy(); 11794 } 11795 if (LHSType->isObjCObjectPointerType() && 11796 RHSType->isObjCObjectPointerType()) { 11797 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11798 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11799 /*isError*/false); 11800 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11801 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11802 11803 if (LHSIsNull && !RHSIsNull) 11804 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11805 else 11806 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11807 return computeResultTy(); 11808 } 11809 11810 if (!IsOrdered && LHSType->isBlockPointerType() && 11811 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11812 LHS = ImpCastExprToType(LHS.get(), RHSType, 11813 CK_BlockPointerToObjCPointerCast); 11814 return computeResultTy(); 11815 } else if (!IsOrdered && 11816 LHSType->isBlockCompatibleObjCPointerType(Context) && 11817 RHSType->isBlockPointerType()) { 11818 RHS = ImpCastExprToType(RHS.get(), LHSType, 11819 CK_BlockPointerToObjCPointerCast); 11820 return computeResultTy(); 11821 } 11822 } 11823 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11824 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11825 unsigned DiagID = 0; 11826 bool isError = false; 11827 if (LangOpts.DebuggerSupport) { 11828 // Under a debugger, allow the comparison of pointers to integers, 11829 // since users tend to want to compare addresses. 11830 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11831 (RHSIsNull && RHSType->isIntegerType())) { 11832 if (IsOrdered) { 11833 isError = getLangOpts().CPlusPlus; 11834 DiagID = 11835 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11836 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11837 } 11838 } else if (getLangOpts().CPlusPlus) { 11839 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11840 isError = true; 11841 } else if (IsOrdered) 11842 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11843 else 11844 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11845 11846 if (DiagID) { 11847 Diag(Loc, DiagID) 11848 << LHSType << RHSType << LHS.get()->getSourceRange() 11849 << RHS.get()->getSourceRange(); 11850 if (isError) 11851 return QualType(); 11852 } 11853 11854 if (LHSType->isIntegerType()) 11855 LHS = ImpCastExprToType(LHS.get(), RHSType, 11856 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11857 else 11858 RHS = ImpCastExprToType(RHS.get(), LHSType, 11859 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11860 return computeResultTy(); 11861 } 11862 11863 // Handle block pointers. 11864 if (!IsOrdered && RHSIsNull 11865 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11866 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11867 return computeResultTy(); 11868 } 11869 if (!IsOrdered && LHSIsNull 11870 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11871 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11872 return computeResultTy(); 11873 } 11874 11875 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11876 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11877 return computeResultTy(); 11878 } 11879 11880 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11881 return computeResultTy(); 11882 } 11883 11884 if (LHSIsNull && RHSType->isQueueT()) { 11885 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11886 return computeResultTy(); 11887 } 11888 11889 if (LHSType->isQueueT() && RHSIsNull) { 11890 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11891 return computeResultTy(); 11892 } 11893 } 11894 11895 return InvalidOperands(Loc, LHS, RHS); 11896 } 11897 11898 // Return a signed ext_vector_type that is of identical size and number of 11899 // elements. For floating point vectors, return an integer type of identical 11900 // size and number of elements. In the non ext_vector_type case, search from 11901 // the largest type to the smallest type to avoid cases where long long == long, 11902 // where long gets picked over long long. 11903 QualType Sema::GetSignedVectorType(QualType V) { 11904 const VectorType *VTy = V->castAs<VectorType>(); 11905 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11906 11907 if (isa<ExtVectorType>(VTy)) { 11908 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11909 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11910 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11911 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11912 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11913 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11914 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11915 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11916 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11917 "Unhandled vector element size in vector compare"); 11918 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11919 } 11920 11921 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11922 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11923 VectorType::GenericVector); 11924 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11925 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11926 VectorType::GenericVector); 11927 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11928 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11929 VectorType::GenericVector); 11930 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11931 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11932 VectorType::GenericVector); 11933 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11934 "Unhandled vector element size in vector compare"); 11935 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11936 VectorType::GenericVector); 11937 } 11938 11939 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11940 /// operates on extended vector types. Instead of producing an IntTy result, 11941 /// like a scalar comparison, a vector comparison produces a vector of integer 11942 /// types. 11943 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11944 SourceLocation Loc, 11945 BinaryOperatorKind Opc) { 11946 if (Opc == BO_Cmp) { 11947 Diag(Loc, diag::err_three_way_vector_comparison); 11948 return QualType(); 11949 } 11950 11951 // Check to make sure we're operating on vectors of the same type and width, 11952 // Allowing one side to be a scalar of element type. 11953 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11954 /*AllowBothBool*/true, 11955 /*AllowBoolConversions*/getLangOpts().ZVector); 11956 if (vType.isNull()) 11957 return vType; 11958 11959 QualType LHSType = LHS.get()->getType(); 11960 11961 // If AltiVec, the comparison results in a numeric type, i.e. 11962 // bool for C++, int for C 11963 if (getLangOpts().AltiVec && 11964 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11965 return Context.getLogicalOperationType(); 11966 11967 // For non-floating point types, check for self-comparisons of the form 11968 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11969 // often indicate logic errors in the program. 11970 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11971 11972 // Check for comparisons of floating point operands using != and ==. 11973 if (BinaryOperator::isEqualityOp(Opc) && 11974 LHSType->hasFloatingRepresentation()) { 11975 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11976 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11977 } 11978 11979 // Return a signed type for the vector. 11980 return GetSignedVectorType(vType); 11981 } 11982 11983 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11984 const ExprResult &XorRHS, 11985 const SourceLocation Loc) { 11986 // Do not diagnose macros. 11987 if (Loc.isMacroID()) 11988 return; 11989 11990 bool Negative = false; 11991 bool ExplicitPlus = false; 11992 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11993 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11994 11995 if (!LHSInt) 11996 return; 11997 if (!RHSInt) { 11998 // Check negative literals. 11999 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12000 UnaryOperatorKind Opc = UO->getOpcode(); 12001 if (Opc != UO_Minus && Opc != UO_Plus) 12002 return; 12003 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12004 if (!RHSInt) 12005 return; 12006 Negative = (Opc == UO_Minus); 12007 ExplicitPlus = !Negative; 12008 } else { 12009 return; 12010 } 12011 } 12012 12013 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12014 llvm::APInt RightSideValue = RHSInt->getValue(); 12015 if (LeftSideValue != 2 && LeftSideValue != 10) 12016 return; 12017 12018 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12019 return; 12020 12021 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12022 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12023 llvm::StringRef ExprStr = 12024 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12025 12026 CharSourceRange XorRange = 12027 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12028 llvm::StringRef XorStr = 12029 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12030 // Do not diagnose if xor keyword/macro is used. 12031 if (XorStr == "xor") 12032 return; 12033 12034 std::string LHSStr = std::string(Lexer::getSourceText( 12035 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12036 S.getSourceManager(), S.getLangOpts())); 12037 std::string RHSStr = std::string(Lexer::getSourceText( 12038 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12039 S.getSourceManager(), S.getLangOpts())); 12040 12041 if (Negative) { 12042 RightSideValue = -RightSideValue; 12043 RHSStr = "-" + RHSStr; 12044 } else if (ExplicitPlus) { 12045 RHSStr = "+" + RHSStr; 12046 } 12047 12048 StringRef LHSStrRef = LHSStr; 12049 StringRef RHSStrRef = RHSStr; 12050 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12051 // literals. 12052 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12053 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12054 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12055 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12056 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12057 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12058 LHSStrRef.find('\'') != StringRef::npos || 12059 RHSStrRef.find('\'') != StringRef::npos) 12060 return; 12061 12062 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12063 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12064 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12065 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12066 std::string SuggestedExpr = "1 << " + RHSStr; 12067 bool Overflow = false; 12068 llvm::APInt One = (LeftSideValue - 1); 12069 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12070 if (Overflow) { 12071 if (RightSideIntValue < 64) 12072 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12073 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12074 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12075 else if (RightSideIntValue == 64) 12076 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12077 else 12078 return; 12079 } else { 12080 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12081 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12082 << PowValue.toString(10, true) 12083 << FixItHint::CreateReplacement( 12084 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12085 } 12086 12087 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12088 } else if (LeftSideValue == 10) { 12089 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12090 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12091 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12092 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12093 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12094 } 12095 } 12096 12097 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12098 SourceLocation Loc) { 12099 // Ensure that either both operands are of the same vector type, or 12100 // one operand is of a vector type and the other is of its element type. 12101 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12102 /*AllowBothBool*/true, 12103 /*AllowBoolConversions*/false); 12104 if (vType.isNull()) 12105 return InvalidOperands(Loc, LHS, RHS); 12106 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12107 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12108 return InvalidOperands(Loc, LHS, RHS); 12109 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12110 // usage of the logical operators && and || with vectors in C. This 12111 // check could be notionally dropped. 12112 if (!getLangOpts().CPlusPlus && 12113 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12114 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12115 12116 return GetSignedVectorType(LHS.get()->getType()); 12117 } 12118 12119 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12120 SourceLocation Loc, 12121 bool IsCompAssign) { 12122 if (!IsCompAssign) { 12123 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12124 if (LHS.isInvalid()) 12125 return QualType(); 12126 } 12127 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12128 if (RHS.isInvalid()) 12129 return QualType(); 12130 12131 // For conversion purposes, we ignore any qualifiers. 12132 // For example, "const float" and "float" are equivalent. 12133 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12134 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12135 12136 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12137 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12138 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12139 12140 if (Context.hasSameType(LHSType, RHSType)) 12141 return LHSType; 12142 12143 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12144 // case we have to return InvalidOperands. 12145 ExprResult OriginalLHS = LHS; 12146 ExprResult OriginalRHS = RHS; 12147 if (LHSMatType && !RHSMatType) { 12148 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12149 if (!RHS.isInvalid()) 12150 return LHSType; 12151 12152 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12153 } 12154 12155 if (!LHSMatType && RHSMatType) { 12156 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12157 if (!LHS.isInvalid()) 12158 return RHSType; 12159 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12160 } 12161 12162 return InvalidOperands(Loc, LHS, RHS); 12163 } 12164 12165 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12166 SourceLocation Loc, 12167 bool IsCompAssign) { 12168 if (!IsCompAssign) { 12169 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12170 if (LHS.isInvalid()) 12171 return QualType(); 12172 } 12173 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12174 if (RHS.isInvalid()) 12175 return QualType(); 12176 12177 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12178 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12179 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12180 12181 if (LHSMatType && RHSMatType) { 12182 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12183 return InvalidOperands(Loc, LHS, RHS); 12184 12185 if (!Context.hasSameType(LHSMatType->getElementType(), 12186 RHSMatType->getElementType())) 12187 return InvalidOperands(Loc, LHS, RHS); 12188 12189 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12190 LHSMatType->getNumRows(), 12191 RHSMatType->getNumColumns()); 12192 } 12193 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12194 } 12195 12196 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12197 SourceLocation Loc, 12198 BinaryOperatorKind Opc) { 12199 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12200 12201 bool IsCompAssign = 12202 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12203 12204 if (LHS.get()->getType()->isVectorType() || 12205 RHS.get()->getType()->isVectorType()) { 12206 if (LHS.get()->getType()->hasIntegerRepresentation() && 12207 RHS.get()->getType()->hasIntegerRepresentation()) 12208 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12209 /*AllowBothBool*/true, 12210 /*AllowBoolConversions*/getLangOpts().ZVector); 12211 return InvalidOperands(Loc, LHS, RHS); 12212 } 12213 12214 if (Opc == BO_And) 12215 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12216 12217 if (LHS.get()->getType()->hasFloatingRepresentation() || 12218 RHS.get()->getType()->hasFloatingRepresentation()) 12219 return InvalidOperands(Loc, LHS, RHS); 12220 12221 ExprResult LHSResult = LHS, RHSResult = RHS; 12222 QualType compType = UsualArithmeticConversions( 12223 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12224 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12225 return QualType(); 12226 LHS = LHSResult.get(); 12227 RHS = RHSResult.get(); 12228 12229 if (Opc == BO_Xor) 12230 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12231 12232 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12233 return compType; 12234 return InvalidOperands(Loc, LHS, RHS); 12235 } 12236 12237 // C99 6.5.[13,14] 12238 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12239 SourceLocation Loc, 12240 BinaryOperatorKind Opc) { 12241 // Check vector operands differently. 12242 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12243 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12244 12245 bool EnumConstantInBoolContext = false; 12246 for (const ExprResult &HS : {LHS, RHS}) { 12247 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12248 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12249 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12250 EnumConstantInBoolContext = true; 12251 } 12252 } 12253 12254 if (EnumConstantInBoolContext) 12255 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12256 12257 // Diagnose cases where the user write a logical and/or but probably meant a 12258 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12259 // is a constant. 12260 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12261 !LHS.get()->getType()->isBooleanType() && 12262 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12263 // Don't warn in macros or template instantiations. 12264 !Loc.isMacroID() && !inTemplateInstantiation()) { 12265 // If the RHS can be constant folded, and if it constant folds to something 12266 // that isn't 0 or 1 (which indicate a potential logical operation that 12267 // happened to fold to true/false) then warn. 12268 // Parens on the RHS are ignored. 12269 Expr::EvalResult EVResult; 12270 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12271 llvm::APSInt Result = EVResult.Val.getInt(); 12272 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12273 !RHS.get()->getExprLoc().isMacroID()) || 12274 (Result != 0 && Result != 1)) { 12275 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12276 << RHS.get()->getSourceRange() 12277 << (Opc == BO_LAnd ? "&&" : "||"); 12278 // Suggest replacing the logical operator with the bitwise version 12279 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12280 << (Opc == BO_LAnd ? "&" : "|") 12281 << FixItHint::CreateReplacement(SourceRange( 12282 Loc, getLocForEndOfToken(Loc)), 12283 Opc == BO_LAnd ? "&" : "|"); 12284 if (Opc == BO_LAnd) 12285 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12286 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12287 << FixItHint::CreateRemoval( 12288 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12289 RHS.get()->getEndLoc())); 12290 } 12291 } 12292 } 12293 12294 if (!Context.getLangOpts().CPlusPlus) { 12295 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12296 // not operate on the built-in scalar and vector float types. 12297 if (Context.getLangOpts().OpenCL && 12298 Context.getLangOpts().OpenCLVersion < 120) { 12299 if (LHS.get()->getType()->isFloatingType() || 12300 RHS.get()->getType()->isFloatingType()) 12301 return InvalidOperands(Loc, LHS, RHS); 12302 } 12303 12304 LHS = UsualUnaryConversions(LHS.get()); 12305 if (LHS.isInvalid()) 12306 return QualType(); 12307 12308 RHS = UsualUnaryConversions(RHS.get()); 12309 if (RHS.isInvalid()) 12310 return QualType(); 12311 12312 if (!LHS.get()->getType()->isScalarType() || 12313 !RHS.get()->getType()->isScalarType()) 12314 return InvalidOperands(Loc, LHS, RHS); 12315 12316 return Context.IntTy; 12317 } 12318 12319 // The following is safe because we only use this method for 12320 // non-overloadable operands. 12321 12322 // C++ [expr.log.and]p1 12323 // C++ [expr.log.or]p1 12324 // The operands are both contextually converted to type bool. 12325 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12326 if (LHSRes.isInvalid()) 12327 return InvalidOperands(Loc, LHS, RHS); 12328 LHS = LHSRes; 12329 12330 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12331 if (RHSRes.isInvalid()) 12332 return InvalidOperands(Loc, LHS, RHS); 12333 RHS = RHSRes; 12334 12335 // C++ [expr.log.and]p2 12336 // C++ [expr.log.or]p2 12337 // The result is a bool. 12338 return Context.BoolTy; 12339 } 12340 12341 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12342 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12343 if (!ME) return false; 12344 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12345 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12346 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12347 if (!Base) return false; 12348 return Base->getMethodDecl() != nullptr; 12349 } 12350 12351 /// Is the given expression (which must be 'const') a reference to a 12352 /// variable which was originally non-const, but which has become 12353 /// 'const' due to being captured within a block? 12354 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12355 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12356 assert(E->isLValue() && E->getType().isConstQualified()); 12357 E = E->IgnoreParens(); 12358 12359 // Must be a reference to a declaration from an enclosing scope. 12360 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12361 if (!DRE) return NCCK_None; 12362 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12363 12364 // The declaration must be a variable which is not declared 'const'. 12365 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12366 if (!var) return NCCK_None; 12367 if (var->getType().isConstQualified()) return NCCK_None; 12368 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12369 12370 // Decide whether the first capture was for a block or a lambda. 12371 DeclContext *DC = S.CurContext, *Prev = nullptr; 12372 // Decide whether the first capture was for a block or a lambda. 12373 while (DC) { 12374 // For init-capture, it is possible that the variable belongs to the 12375 // template pattern of the current context. 12376 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12377 if (var->isInitCapture() && 12378 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12379 break; 12380 if (DC == var->getDeclContext()) 12381 break; 12382 Prev = DC; 12383 DC = DC->getParent(); 12384 } 12385 // Unless we have an init-capture, we've gone one step too far. 12386 if (!var->isInitCapture()) 12387 DC = Prev; 12388 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12389 } 12390 12391 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12392 Ty = Ty.getNonReferenceType(); 12393 if (IsDereference && Ty->isPointerType()) 12394 Ty = Ty->getPointeeType(); 12395 return !Ty.isConstQualified(); 12396 } 12397 12398 // Update err_typecheck_assign_const and note_typecheck_assign_const 12399 // when this enum is changed. 12400 enum { 12401 ConstFunction, 12402 ConstVariable, 12403 ConstMember, 12404 ConstMethod, 12405 NestedConstMember, 12406 ConstUnknown, // Keep as last element 12407 }; 12408 12409 /// Emit the "read-only variable not assignable" error and print notes to give 12410 /// more information about why the variable is not assignable, such as pointing 12411 /// to the declaration of a const variable, showing that a method is const, or 12412 /// that the function is returning a const reference. 12413 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12414 SourceLocation Loc) { 12415 SourceRange ExprRange = E->getSourceRange(); 12416 12417 // Only emit one error on the first const found. All other consts will emit 12418 // a note to the error. 12419 bool DiagnosticEmitted = false; 12420 12421 // Track if the current expression is the result of a dereference, and if the 12422 // next checked expression is the result of a dereference. 12423 bool IsDereference = false; 12424 bool NextIsDereference = false; 12425 12426 // Loop to process MemberExpr chains. 12427 while (true) { 12428 IsDereference = NextIsDereference; 12429 12430 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12431 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12432 NextIsDereference = ME->isArrow(); 12433 const ValueDecl *VD = ME->getMemberDecl(); 12434 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12435 // Mutable fields can be modified even if the class is const. 12436 if (Field->isMutable()) { 12437 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12438 break; 12439 } 12440 12441 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12442 if (!DiagnosticEmitted) { 12443 S.Diag(Loc, diag::err_typecheck_assign_const) 12444 << ExprRange << ConstMember << false /*static*/ << Field 12445 << Field->getType(); 12446 DiagnosticEmitted = true; 12447 } 12448 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12449 << ConstMember << false /*static*/ << Field << Field->getType() 12450 << Field->getSourceRange(); 12451 } 12452 E = ME->getBase(); 12453 continue; 12454 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12455 if (VDecl->getType().isConstQualified()) { 12456 if (!DiagnosticEmitted) { 12457 S.Diag(Loc, diag::err_typecheck_assign_const) 12458 << ExprRange << ConstMember << true /*static*/ << VDecl 12459 << VDecl->getType(); 12460 DiagnosticEmitted = true; 12461 } 12462 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12463 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12464 << VDecl->getSourceRange(); 12465 } 12466 // Static fields do not inherit constness from parents. 12467 break; 12468 } 12469 break; // End MemberExpr 12470 } else if (const ArraySubscriptExpr *ASE = 12471 dyn_cast<ArraySubscriptExpr>(E)) { 12472 E = ASE->getBase()->IgnoreParenImpCasts(); 12473 continue; 12474 } else if (const ExtVectorElementExpr *EVE = 12475 dyn_cast<ExtVectorElementExpr>(E)) { 12476 E = EVE->getBase()->IgnoreParenImpCasts(); 12477 continue; 12478 } 12479 break; 12480 } 12481 12482 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12483 // Function calls 12484 const FunctionDecl *FD = CE->getDirectCallee(); 12485 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12486 if (!DiagnosticEmitted) { 12487 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12488 << ConstFunction << FD; 12489 DiagnosticEmitted = true; 12490 } 12491 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12492 diag::note_typecheck_assign_const) 12493 << ConstFunction << FD << FD->getReturnType() 12494 << FD->getReturnTypeSourceRange(); 12495 } 12496 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12497 // Point to variable declaration. 12498 if (const ValueDecl *VD = DRE->getDecl()) { 12499 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12500 if (!DiagnosticEmitted) { 12501 S.Diag(Loc, diag::err_typecheck_assign_const) 12502 << ExprRange << ConstVariable << VD << VD->getType(); 12503 DiagnosticEmitted = true; 12504 } 12505 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12506 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12507 } 12508 } 12509 } else if (isa<CXXThisExpr>(E)) { 12510 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12511 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12512 if (MD->isConst()) { 12513 if (!DiagnosticEmitted) { 12514 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12515 << ConstMethod << MD; 12516 DiagnosticEmitted = true; 12517 } 12518 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12519 << ConstMethod << MD << MD->getSourceRange(); 12520 } 12521 } 12522 } 12523 } 12524 12525 if (DiagnosticEmitted) 12526 return; 12527 12528 // Can't determine a more specific message, so display the generic error. 12529 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12530 } 12531 12532 enum OriginalExprKind { 12533 OEK_Variable, 12534 OEK_Member, 12535 OEK_LValue 12536 }; 12537 12538 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12539 const RecordType *Ty, 12540 SourceLocation Loc, SourceRange Range, 12541 OriginalExprKind OEK, 12542 bool &DiagnosticEmitted) { 12543 std::vector<const RecordType *> RecordTypeList; 12544 RecordTypeList.push_back(Ty); 12545 unsigned NextToCheckIndex = 0; 12546 // We walk the record hierarchy breadth-first to ensure that we print 12547 // diagnostics in field nesting order. 12548 while (RecordTypeList.size() > NextToCheckIndex) { 12549 bool IsNested = NextToCheckIndex > 0; 12550 for (const FieldDecl *Field : 12551 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12552 // First, check every field for constness. 12553 QualType FieldTy = Field->getType(); 12554 if (FieldTy.isConstQualified()) { 12555 if (!DiagnosticEmitted) { 12556 S.Diag(Loc, diag::err_typecheck_assign_const) 12557 << Range << NestedConstMember << OEK << VD 12558 << IsNested << Field; 12559 DiagnosticEmitted = true; 12560 } 12561 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12562 << NestedConstMember << IsNested << Field 12563 << FieldTy << Field->getSourceRange(); 12564 } 12565 12566 // Then we append it to the list to check next in order. 12567 FieldTy = FieldTy.getCanonicalType(); 12568 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12569 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12570 RecordTypeList.push_back(FieldRecTy); 12571 } 12572 } 12573 ++NextToCheckIndex; 12574 } 12575 } 12576 12577 /// Emit an error for the case where a record we are trying to assign to has a 12578 /// const-qualified field somewhere in its hierarchy. 12579 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12580 SourceLocation Loc) { 12581 QualType Ty = E->getType(); 12582 assert(Ty->isRecordType() && "lvalue was not record?"); 12583 SourceRange Range = E->getSourceRange(); 12584 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12585 bool DiagEmitted = false; 12586 12587 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12588 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12589 Range, OEK_Member, DiagEmitted); 12590 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12591 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12592 Range, OEK_Variable, DiagEmitted); 12593 else 12594 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12595 Range, OEK_LValue, DiagEmitted); 12596 if (!DiagEmitted) 12597 DiagnoseConstAssignment(S, E, Loc); 12598 } 12599 12600 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12601 /// emit an error and return true. If so, return false. 12602 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12603 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12604 12605 S.CheckShadowingDeclModification(E, Loc); 12606 12607 SourceLocation OrigLoc = Loc; 12608 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12609 &Loc); 12610 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12611 IsLV = Expr::MLV_InvalidMessageExpression; 12612 if (IsLV == Expr::MLV_Valid) 12613 return false; 12614 12615 unsigned DiagID = 0; 12616 bool NeedType = false; 12617 switch (IsLV) { // C99 6.5.16p2 12618 case Expr::MLV_ConstQualified: 12619 // Use a specialized diagnostic when we're assigning to an object 12620 // from an enclosing function or block. 12621 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12622 if (NCCK == NCCK_Block) 12623 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12624 else 12625 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12626 break; 12627 } 12628 12629 // In ARC, use some specialized diagnostics for occasions where we 12630 // infer 'const'. These are always pseudo-strong variables. 12631 if (S.getLangOpts().ObjCAutoRefCount) { 12632 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12633 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12634 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12635 12636 // Use the normal diagnostic if it's pseudo-__strong but the 12637 // user actually wrote 'const'. 12638 if (var->isARCPseudoStrong() && 12639 (!var->getTypeSourceInfo() || 12640 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12641 // There are three pseudo-strong cases: 12642 // - self 12643 ObjCMethodDecl *method = S.getCurMethodDecl(); 12644 if (method && var == method->getSelfDecl()) { 12645 DiagID = method->isClassMethod() 12646 ? diag::err_typecheck_arc_assign_self_class_method 12647 : diag::err_typecheck_arc_assign_self; 12648 12649 // - Objective-C externally_retained attribute. 12650 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12651 isa<ParmVarDecl>(var)) { 12652 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12653 12654 // - fast enumeration variables 12655 } else { 12656 DiagID = diag::err_typecheck_arr_assign_enumeration; 12657 } 12658 12659 SourceRange Assign; 12660 if (Loc != OrigLoc) 12661 Assign = SourceRange(OrigLoc, OrigLoc); 12662 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12663 // We need to preserve the AST regardless, so migration tool 12664 // can do its job. 12665 return false; 12666 } 12667 } 12668 } 12669 12670 // If none of the special cases above are triggered, then this is a 12671 // simple const assignment. 12672 if (DiagID == 0) { 12673 DiagnoseConstAssignment(S, E, Loc); 12674 return true; 12675 } 12676 12677 break; 12678 case Expr::MLV_ConstAddrSpace: 12679 DiagnoseConstAssignment(S, E, Loc); 12680 return true; 12681 case Expr::MLV_ConstQualifiedField: 12682 DiagnoseRecursiveConstFields(S, E, Loc); 12683 return true; 12684 case Expr::MLV_ArrayType: 12685 case Expr::MLV_ArrayTemporary: 12686 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12687 NeedType = true; 12688 break; 12689 case Expr::MLV_NotObjectType: 12690 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12691 NeedType = true; 12692 break; 12693 case Expr::MLV_LValueCast: 12694 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12695 break; 12696 case Expr::MLV_Valid: 12697 llvm_unreachable("did not take early return for MLV_Valid"); 12698 case Expr::MLV_InvalidExpression: 12699 case Expr::MLV_MemberFunction: 12700 case Expr::MLV_ClassTemporary: 12701 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12702 break; 12703 case Expr::MLV_IncompleteType: 12704 case Expr::MLV_IncompleteVoidType: 12705 return S.RequireCompleteType(Loc, E->getType(), 12706 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12707 case Expr::MLV_DuplicateVectorComponents: 12708 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12709 break; 12710 case Expr::MLV_NoSetterProperty: 12711 llvm_unreachable("readonly properties should be processed differently"); 12712 case Expr::MLV_InvalidMessageExpression: 12713 DiagID = diag::err_readonly_message_assignment; 12714 break; 12715 case Expr::MLV_SubObjCPropertySetting: 12716 DiagID = diag::err_no_subobject_property_setting; 12717 break; 12718 } 12719 12720 SourceRange Assign; 12721 if (Loc != OrigLoc) 12722 Assign = SourceRange(OrigLoc, OrigLoc); 12723 if (NeedType) 12724 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12725 else 12726 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12727 return true; 12728 } 12729 12730 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12731 SourceLocation Loc, 12732 Sema &Sema) { 12733 if (Sema.inTemplateInstantiation()) 12734 return; 12735 if (Sema.isUnevaluatedContext()) 12736 return; 12737 if (Loc.isInvalid() || Loc.isMacroID()) 12738 return; 12739 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12740 return; 12741 12742 // C / C++ fields 12743 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12744 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12745 if (ML && MR) { 12746 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12747 return; 12748 const ValueDecl *LHSDecl = 12749 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12750 const ValueDecl *RHSDecl = 12751 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12752 if (LHSDecl != RHSDecl) 12753 return; 12754 if (LHSDecl->getType().isVolatileQualified()) 12755 return; 12756 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12757 if (RefTy->getPointeeType().isVolatileQualified()) 12758 return; 12759 12760 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12761 } 12762 12763 // Objective-C instance variables 12764 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12765 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12766 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12767 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12768 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12769 if (RL && RR && RL->getDecl() == RR->getDecl()) 12770 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12771 } 12772 } 12773 12774 // C99 6.5.16.1 12775 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12776 SourceLocation Loc, 12777 QualType CompoundType) { 12778 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12779 12780 // Verify that LHS is a modifiable lvalue, and emit error if not. 12781 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12782 return QualType(); 12783 12784 QualType LHSType = LHSExpr->getType(); 12785 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12786 CompoundType; 12787 // OpenCL v1.2 s6.1.1.1 p2: 12788 // The half data type can only be used to declare a pointer to a buffer that 12789 // contains half values 12790 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12791 LHSType->isHalfType()) { 12792 Diag(Loc, diag::err_opencl_half_load_store) << 1 12793 << LHSType.getUnqualifiedType(); 12794 return QualType(); 12795 } 12796 12797 AssignConvertType ConvTy; 12798 if (CompoundType.isNull()) { 12799 Expr *RHSCheck = RHS.get(); 12800 12801 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12802 12803 QualType LHSTy(LHSType); 12804 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12805 if (RHS.isInvalid()) 12806 return QualType(); 12807 // Special case of NSObject attributes on c-style pointer types. 12808 if (ConvTy == IncompatiblePointer && 12809 ((Context.isObjCNSObjectType(LHSType) && 12810 RHSType->isObjCObjectPointerType()) || 12811 (Context.isObjCNSObjectType(RHSType) && 12812 LHSType->isObjCObjectPointerType()))) 12813 ConvTy = Compatible; 12814 12815 if (ConvTy == Compatible && 12816 LHSType->isObjCObjectType()) 12817 Diag(Loc, diag::err_objc_object_assignment) 12818 << LHSType; 12819 12820 // If the RHS is a unary plus or minus, check to see if they = and + are 12821 // right next to each other. If so, the user may have typo'd "x =+ 4" 12822 // instead of "x += 4". 12823 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12824 RHSCheck = ICE->getSubExpr(); 12825 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12826 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12827 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12828 // Only if the two operators are exactly adjacent. 12829 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12830 // And there is a space or other character before the subexpr of the 12831 // unary +/-. We don't want to warn on "x=-1". 12832 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12833 UO->getSubExpr()->getBeginLoc().isFileID()) { 12834 Diag(Loc, diag::warn_not_compound_assign) 12835 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12836 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12837 } 12838 } 12839 12840 if (ConvTy == Compatible) { 12841 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12842 // Warn about retain cycles where a block captures the LHS, but 12843 // not if the LHS is a simple variable into which the block is 12844 // being stored...unless that variable can be captured by reference! 12845 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12846 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12847 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12848 checkRetainCycles(LHSExpr, RHS.get()); 12849 } 12850 12851 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12852 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12853 // It is safe to assign a weak reference into a strong variable. 12854 // Although this code can still have problems: 12855 // id x = self.weakProp; 12856 // id y = self.weakProp; 12857 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12858 // paths through the function. This should be revisited if 12859 // -Wrepeated-use-of-weak is made flow-sensitive. 12860 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12861 // variable, which will be valid for the current autorelease scope. 12862 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12863 RHS.get()->getBeginLoc())) 12864 getCurFunction()->markSafeWeakUse(RHS.get()); 12865 12866 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12867 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12868 } 12869 } 12870 } else { 12871 // Compound assignment "x += y" 12872 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12873 } 12874 12875 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12876 RHS.get(), AA_Assigning)) 12877 return QualType(); 12878 12879 CheckForNullPointerDereference(*this, LHSExpr); 12880 12881 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12882 if (CompoundType.isNull()) { 12883 // C++2a [expr.ass]p5: 12884 // A simple-assignment whose left operand is of a volatile-qualified 12885 // type is deprecated unless the assignment is either a discarded-value 12886 // expression or an unevaluated operand 12887 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12888 } else { 12889 // C++2a [expr.ass]p6: 12890 // [Compound-assignment] expressions are deprecated if E1 has 12891 // volatile-qualified type 12892 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12893 } 12894 } 12895 12896 // C99 6.5.16p3: The type of an assignment expression is the type of the 12897 // left operand unless the left operand has qualified type, in which case 12898 // it is the unqualified version of the type of the left operand. 12899 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12900 // is converted to the type of the assignment expression (above). 12901 // C++ 5.17p1: the type of the assignment expression is that of its left 12902 // operand. 12903 return (getLangOpts().CPlusPlus 12904 ? LHSType : LHSType.getUnqualifiedType()); 12905 } 12906 12907 // Only ignore explicit casts to void. 12908 static bool IgnoreCommaOperand(const Expr *E) { 12909 E = E->IgnoreParens(); 12910 12911 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12912 if (CE->getCastKind() == CK_ToVoid) { 12913 return true; 12914 } 12915 12916 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12917 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12918 CE->getSubExpr()->getType()->isDependentType()) { 12919 return true; 12920 } 12921 } 12922 12923 return false; 12924 } 12925 12926 // Look for instances where it is likely the comma operator is confused with 12927 // another operator. There is an explicit list of acceptable expressions for 12928 // the left hand side of the comma operator, otherwise emit a warning. 12929 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12930 // No warnings in macros 12931 if (Loc.isMacroID()) 12932 return; 12933 12934 // Don't warn in template instantiations. 12935 if (inTemplateInstantiation()) 12936 return; 12937 12938 // Scope isn't fine-grained enough to explicitly list the specific cases, so 12939 // instead, skip more than needed, then call back into here with the 12940 // CommaVisitor in SemaStmt.cpp. 12941 // The listed locations are the initialization and increment portions 12942 // of a for loop. The additional checks are on the condition of 12943 // if statements, do/while loops, and for loops. 12944 // Differences in scope flags for C89 mode requires the extra logic. 12945 const unsigned ForIncrementFlags = 12946 getLangOpts().C99 || getLangOpts().CPlusPlus 12947 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12948 : Scope::ContinueScope | Scope::BreakScope; 12949 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12950 const unsigned ScopeFlags = getCurScope()->getFlags(); 12951 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12952 (ScopeFlags & ForInitFlags) == ForInitFlags) 12953 return; 12954 12955 // If there are multiple comma operators used together, get the RHS of the 12956 // of the comma operator as the LHS. 12957 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12958 if (BO->getOpcode() != BO_Comma) 12959 break; 12960 LHS = BO->getRHS(); 12961 } 12962 12963 // Only allow some expressions on LHS to not warn. 12964 if (IgnoreCommaOperand(LHS)) 12965 return; 12966 12967 Diag(Loc, diag::warn_comma_operator); 12968 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12969 << LHS->getSourceRange() 12970 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12971 LangOpts.CPlusPlus ? "static_cast<void>(" 12972 : "(void)(") 12973 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12974 ")"); 12975 } 12976 12977 // C99 6.5.17 12978 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12979 SourceLocation Loc) { 12980 LHS = S.CheckPlaceholderExpr(LHS.get()); 12981 RHS = S.CheckPlaceholderExpr(RHS.get()); 12982 if (LHS.isInvalid() || RHS.isInvalid()) 12983 return QualType(); 12984 12985 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12986 // operands, but not unary promotions. 12987 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12988 12989 // So we treat the LHS as a ignored value, and in C++ we allow the 12990 // containing site to determine what should be done with the RHS. 12991 LHS = S.IgnoredValueConversions(LHS.get()); 12992 if (LHS.isInvalid()) 12993 return QualType(); 12994 12995 S.DiagnoseUnusedExprResult(LHS.get()); 12996 12997 if (!S.getLangOpts().CPlusPlus) { 12998 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12999 if (RHS.isInvalid()) 13000 return QualType(); 13001 if (!RHS.get()->getType()->isVoidType()) 13002 S.RequireCompleteType(Loc, RHS.get()->getType(), 13003 diag::err_incomplete_type); 13004 } 13005 13006 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13007 S.DiagnoseCommaOperator(LHS.get(), Loc); 13008 13009 return RHS.get()->getType(); 13010 } 13011 13012 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13013 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13014 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13015 ExprValueKind &VK, 13016 ExprObjectKind &OK, 13017 SourceLocation OpLoc, 13018 bool IsInc, bool IsPrefix) { 13019 if (Op->isTypeDependent()) 13020 return S.Context.DependentTy; 13021 13022 QualType ResType = Op->getType(); 13023 // Atomic types can be used for increment / decrement where the non-atomic 13024 // versions can, so ignore the _Atomic() specifier for the purpose of 13025 // checking. 13026 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13027 ResType = ResAtomicType->getValueType(); 13028 13029 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13030 13031 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13032 // Decrement of bool is not allowed. 13033 if (!IsInc) { 13034 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13035 return QualType(); 13036 } 13037 // Increment of bool sets it to true, but is deprecated. 13038 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13039 : diag::warn_increment_bool) 13040 << Op->getSourceRange(); 13041 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13042 // Error on enum increments and decrements in C++ mode 13043 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13044 return QualType(); 13045 } else if (ResType->isRealType()) { 13046 // OK! 13047 } else if (ResType->isPointerType()) { 13048 // C99 6.5.2.4p2, 6.5.6p2 13049 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13050 return QualType(); 13051 } else if (ResType->isObjCObjectPointerType()) { 13052 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13053 // Otherwise, we just need a complete type. 13054 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13055 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13056 return QualType(); 13057 } else if (ResType->isAnyComplexType()) { 13058 // C99 does not support ++/-- on complex types, we allow as an extension. 13059 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13060 << ResType << Op->getSourceRange(); 13061 } else if (ResType->isPlaceholderType()) { 13062 ExprResult PR = S.CheckPlaceholderExpr(Op); 13063 if (PR.isInvalid()) return QualType(); 13064 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13065 IsInc, IsPrefix); 13066 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13067 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13068 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13069 (ResType->castAs<VectorType>()->getVectorKind() != 13070 VectorType::AltiVecBool)) { 13071 // The z vector extensions allow ++ and -- for non-bool vectors. 13072 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13073 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13074 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13075 } else { 13076 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13077 << ResType << int(IsInc) << Op->getSourceRange(); 13078 return QualType(); 13079 } 13080 // At this point, we know we have a real, complex or pointer type. 13081 // Now make sure the operand is a modifiable lvalue. 13082 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13083 return QualType(); 13084 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13085 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13086 // An operand with volatile-qualified type is deprecated 13087 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13088 << IsInc << ResType; 13089 } 13090 // In C++, a prefix increment is the same type as the operand. Otherwise 13091 // (in C or with postfix), the increment is the unqualified type of the 13092 // operand. 13093 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13094 VK = VK_LValue; 13095 OK = Op->getObjectKind(); 13096 return ResType; 13097 } else { 13098 VK = VK_RValue; 13099 return ResType.getUnqualifiedType(); 13100 } 13101 } 13102 13103 13104 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13105 /// This routine allows us to typecheck complex/recursive expressions 13106 /// where the declaration is needed for type checking. We only need to 13107 /// handle cases when the expression references a function designator 13108 /// or is an lvalue. Here are some examples: 13109 /// - &(x) => x 13110 /// - &*****f => f for f a function designator. 13111 /// - &s.xx => s 13112 /// - &s.zz[1].yy -> s, if zz is an array 13113 /// - *(x + 1) -> x, if x is an array 13114 /// - &"123"[2] -> 0 13115 /// - & __real__ x -> x 13116 /// 13117 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13118 /// members. 13119 static ValueDecl *getPrimaryDecl(Expr *E) { 13120 switch (E->getStmtClass()) { 13121 case Stmt::DeclRefExprClass: 13122 return cast<DeclRefExpr>(E)->getDecl(); 13123 case Stmt::MemberExprClass: 13124 // If this is an arrow operator, the address is an offset from 13125 // the base's value, so the object the base refers to is 13126 // irrelevant. 13127 if (cast<MemberExpr>(E)->isArrow()) 13128 return nullptr; 13129 // Otherwise, the expression refers to a part of the base 13130 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13131 case Stmt::ArraySubscriptExprClass: { 13132 // FIXME: This code shouldn't be necessary! We should catch the implicit 13133 // promotion of register arrays earlier. 13134 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13135 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13136 if (ICE->getSubExpr()->getType()->isArrayType()) 13137 return getPrimaryDecl(ICE->getSubExpr()); 13138 } 13139 return nullptr; 13140 } 13141 case Stmt::UnaryOperatorClass: { 13142 UnaryOperator *UO = cast<UnaryOperator>(E); 13143 13144 switch(UO->getOpcode()) { 13145 case UO_Real: 13146 case UO_Imag: 13147 case UO_Extension: 13148 return getPrimaryDecl(UO->getSubExpr()); 13149 default: 13150 return nullptr; 13151 } 13152 } 13153 case Stmt::ParenExprClass: 13154 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13155 case Stmt::ImplicitCastExprClass: 13156 // If the result of an implicit cast is an l-value, we care about 13157 // the sub-expression; otherwise, the result here doesn't matter. 13158 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13159 case Stmt::CXXUuidofExprClass: 13160 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13161 default: 13162 return nullptr; 13163 } 13164 } 13165 13166 namespace { 13167 enum { 13168 AO_Bit_Field = 0, 13169 AO_Vector_Element = 1, 13170 AO_Property_Expansion = 2, 13171 AO_Register_Variable = 3, 13172 AO_Matrix_Element = 4, 13173 AO_No_Error = 5 13174 }; 13175 } 13176 /// Diagnose invalid operand for address of operations. 13177 /// 13178 /// \param Type The type of operand which cannot have its address taken. 13179 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13180 Expr *E, unsigned Type) { 13181 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13182 } 13183 13184 /// CheckAddressOfOperand - The operand of & must be either a function 13185 /// designator or an lvalue designating an object. If it is an lvalue, the 13186 /// object cannot be declared with storage class register or be a bit field. 13187 /// Note: The usual conversions are *not* applied to the operand of the & 13188 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13189 /// In C++, the operand might be an overloaded function name, in which case 13190 /// we allow the '&' but retain the overloaded-function type. 13191 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13192 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13193 if (PTy->getKind() == BuiltinType::Overload) { 13194 Expr *E = OrigOp.get()->IgnoreParens(); 13195 if (!isa<OverloadExpr>(E)) { 13196 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13197 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13198 << OrigOp.get()->getSourceRange(); 13199 return QualType(); 13200 } 13201 13202 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13203 if (isa<UnresolvedMemberExpr>(Ovl)) 13204 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13205 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13206 << OrigOp.get()->getSourceRange(); 13207 return QualType(); 13208 } 13209 13210 return Context.OverloadTy; 13211 } 13212 13213 if (PTy->getKind() == BuiltinType::UnknownAny) 13214 return Context.UnknownAnyTy; 13215 13216 if (PTy->getKind() == BuiltinType::BoundMember) { 13217 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13218 << OrigOp.get()->getSourceRange(); 13219 return QualType(); 13220 } 13221 13222 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13223 if (OrigOp.isInvalid()) return QualType(); 13224 } 13225 13226 if (OrigOp.get()->isTypeDependent()) 13227 return Context.DependentTy; 13228 13229 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13230 13231 // Make sure to ignore parentheses in subsequent checks 13232 Expr *op = OrigOp.get()->IgnoreParens(); 13233 13234 // In OpenCL captures for blocks called as lambda functions 13235 // are located in the private address space. Blocks used in 13236 // enqueue_kernel can be located in a different address space 13237 // depending on a vendor implementation. Thus preventing 13238 // taking an address of the capture to avoid invalid AS casts. 13239 if (LangOpts.OpenCL) { 13240 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13241 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13242 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13243 return QualType(); 13244 } 13245 } 13246 13247 if (getLangOpts().C99) { 13248 // Implement C99-only parts of addressof rules. 13249 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13250 if (uOp->getOpcode() == UO_Deref) 13251 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13252 // (assuming the deref expression is valid). 13253 return uOp->getSubExpr()->getType(); 13254 } 13255 // Technically, there should be a check for array subscript 13256 // expressions here, but the result of one is always an lvalue anyway. 13257 } 13258 ValueDecl *dcl = getPrimaryDecl(op); 13259 13260 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13261 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13262 op->getBeginLoc())) 13263 return QualType(); 13264 13265 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13266 unsigned AddressOfError = AO_No_Error; 13267 13268 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13269 bool sfinae = (bool)isSFINAEContext(); 13270 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13271 : diag::ext_typecheck_addrof_temporary) 13272 << op->getType() << op->getSourceRange(); 13273 if (sfinae) 13274 return QualType(); 13275 // Materialize the temporary as an lvalue so that we can take its address. 13276 OrigOp = op = 13277 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13278 } else if (isa<ObjCSelectorExpr>(op)) { 13279 return Context.getPointerType(op->getType()); 13280 } else if (lval == Expr::LV_MemberFunction) { 13281 // If it's an instance method, make a member pointer. 13282 // The expression must have exactly the form &A::foo. 13283 13284 // If the underlying expression isn't a decl ref, give up. 13285 if (!isa<DeclRefExpr>(op)) { 13286 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13287 << OrigOp.get()->getSourceRange(); 13288 return QualType(); 13289 } 13290 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13291 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13292 13293 // The id-expression was parenthesized. 13294 if (OrigOp.get() != DRE) { 13295 Diag(OpLoc, diag::err_parens_pointer_member_function) 13296 << OrigOp.get()->getSourceRange(); 13297 13298 // The method was named without a qualifier. 13299 } else if (!DRE->getQualifier()) { 13300 if (MD->getParent()->getName().empty()) 13301 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13302 << op->getSourceRange(); 13303 else { 13304 SmallString<32> Str; 13305 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13306 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13307 << op->getSourceRange() 13308 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13309 } 13310 } 13311 13312 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13313 if (isa<CXXDestructorDecl>(MD)) 13314 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13315 13316 QualType MPTy = Context.getMemberPointerType( 13317 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13318 // Under the MS ABI, lock down the inheritance model now. 13319 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13320 (void)isCompleteType(OpLoc, MPTy); 13321 return MPTy; 13322 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13323 // C99 6.5.3.2p1 13324 // The operand must be either an l-value or a function designator 13325 if (!op->getType()->isFunctionType()) { 13326 // Use a special diagnostic for loads from property references. 13327 if (isa<PseudoObjectExpr>(op)) { 13328 AddressOfError = AO_Property_Expansion; 13329 } else { 13330 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13331 << op->getType() << op->getSourceRange(); 13332 return QualType(); 13333 } 13334 } 13335 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13336 // The operand cannot be a bit-field 13337 AddressOfError = AO_Bit_Field; 13338 } else if (op->getObjectKind() == OK_VectorComponent) { 13339 // The operand cannot be an element of a vector 13340 AddressOfError = AO_Vector_Element; 13341 } else if (op->getObjectKind() == OK_MatrixComponent) { 13342 // The operand cannot be an element of a matrix. 13343 AddressOfError = AO_Matrix_Element; 13344 } else if (dcl) { // C99 6.5.3.2p1 13345 // We have an lvalue with a decl. Make sure the decl is not declared 13346 // with the register storage-class specifier. 13347 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13348 // in C++ it is not error to take address of a register 13349 // variable (c++03 7.1.1P3) 13350 if (vd->getStorageClass() == SC_Register && 13351 !getLangOpts().CPlusPlus) { 13352 AddressOfError = AO_Register_Variable; 13353 } 13354 } else if (isa<MSPropertyDecl>(dcl)) { 13355 AddressOfError = AO_Property_Expansion; 13356 } else if (isa<FunctionTemplateDecl>(dcl)) { 13357 return Context.OverloadTy; 13358 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13359 // Okay: we can take the address of a field. 13360 // Could be a pointer to member, though, if there is an explicit 13361 // scope qualifier for the class. 13362 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13363 DeclContext *Ctx = dcl->getDeclContext(); 13364 if (Ctx && Ctx->isRecord()) { 13365 if (dcl->getType()->isReferenceType()) { 13366 Diag(OpLoc, 13367 diag::err_cannot_form_pointer_to_member_of_reference_type) 13368 << dcl->getDeclName() << dcl->getType(); 13369 return QualType(); 13370 } 13371 13372 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13373 Ctx = Ctx->getParent(); 13374 13375 QualType MPTy = Context.getMemberPointerType( 13376 op->getType(), 13377 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13378 // Under the MS ABI, lock down the inheritance model now. 13379 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13380 (void)isCompleteType(OpLoc, MPTy); 13381 return MPTy; 13382 } 13383 } 13384 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13385 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13386 llvm_unreachable("Unknown/unexpected decl type"); 13387 } 13388 13389 if (AddressOfError != AO_No_Error) { 13390 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13391 return QualType(); 13392 } 13393 13394 if (lval == Expr::LV_IncompleteVoidType) { 13395 // Taking the address of a void variable is technically illegal, but we 13396 // allow it in cases which are otherwise valid. 13397 // Example: "extern void x; void* y = &x;". 13398 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13399 } 13400 13401 // If the operand has type "type", the result has type "pointer to type". 13402 if (op->getType()->isObjCObjectType()) 13403 return Context.getObjCObjectPointerType(op->getType()); 13404 13405 CheckAddressOfPackedMember(op); 13406 13407 return Context.getPointerType(op->getType()); 13408 } 13409 13410 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13411 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13412 if (!DRE) 13413 return; 13414 const Decl *D = DRE->getDecl(); 13415 if (!D) 13416 return; 13417 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13418 if (!Param) 13419 return; 13420 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13421 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13422 return; 13423 if (FunctionScopeInfo *FD = S.getCurFunction()) 13424 if (!FD->ModifiedNonNullParams.count(Param)) 13425 FD->ModifiedNonNullParams.insert(Param); 13426 } 13427 13428 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13429 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13430 SourceLocation OpLoc) { 13431 if (Op->isTypeDependent()) 13432 return S.Context.DependentTy; 13433 13434 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13435 if (ConvResult.isInvalid()) 13436 return QualType(); 13437 Op = ConvResult.get(); 13438 QualType OpTy = Op->getType(); 13439 QualType Result; 13440 13441 if (isa<CXXReinterpretCastExpr>(Op)) { 13442 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13443 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13444 Op->getSourceRange()); 13445 } 13446 13447 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13448 { 13449 Result = PT->getPointeeType(); 13450 } 13451 else if (const ObjCObjectPointerType *OPT = 13452 OpTy->getAs<ObjCObjectPointerType>()) 13453 Result = OPT->getPointeeType(); 13454 else { 13455 ExprResult PR = S.CheckPlaceholderExpr(Op); 13456 if (PR.isInvalid()) return QualType(); 13457 if (PR.get() != Op) 13458 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13459 } 13460 13461 if (Result.isNull()) { 13462 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13463 << OpTy << Op->getSourceRange(); 13464 return QualType(); 13465 } 13466 13467 // Note that per both C89 and C99, indirection is always legal, even if Result 13468 // is an incomplete type or void. It would be possible to warn about 13469 // dereferencing a void pointer, but it's completely well-defined, and such a 13470 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13471 // for pointers to 'void' but is fine for any other pointer type: 13472 // 13473 // C++ [expr.unary.op]p1: 13474 // [...] the expression to which [the unary * operator] is applied shall 13475 // be a pointer to an object type, or a pointer to a function type 13476 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13477 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13478 << OpTy << Op->getSourceRange(); 13479 13480 // Dereferences are usually l-values... 13481 VK = VK_LValue; 13482 13483 // ...except that certain expressions are never l-values in C. 13484 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13485 VK = VK_RValue; 13486 13487 return Result; 13488 } 13489 13490 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13491 BinaryOperatorKind Opc; 13492 switch (Kind) { 13493 default: llvm_unreachable("Unknown binop!"); 13494 case tok::periodstar: Opc = BO_PtrMemD; break; 13495 case tok::arrowstar: Opc = BO_PtrMemI; break; 13496 case tok::star: Opc = BO_Mul; break; 13497 case tok::slash: Opc = BO_Div; break; 13498 case tok::percent: Opc = BO_Rem; break; 13499 case tok::plus: Opc = BO_Add; break; 13500 case tok::minus: Opc = BO_Sub; break; 13501 case tok::lessless: Opc = BO_Shl; break; 13502 case tok::greatergreater: Opc = BO_Shr; break; 13503 case tok::lessequal: Opc = BO_LE; break; 13504 case tok::less: Opc = BO_LT; break; 13505 case tok::greaterequal: Opc = BO_GE; break; 13506 case tok::greater: Opc = BO_GT; break; 13507 case tok::exclaimequal: Opc = BO_NE; break; 13508 case tok::equalequal: Opc = BO_EQ; break; 13509 case tok::spaceship: Opc = BO_Cmp; break; 13510 case tok::amp: Opc = BO_And; break; 13511 case tok::caret: Opc = BO_Xor; break; 13512 case tok::pipe: Opc = BO_Or; break; 13513 case tok::ampamp: Opc = BO_LAnd; break; 13514 case tok::pipepipe: Opc = BO_LOr; break; 13515 case tok::equal: Opc = BO_Assign; break; 13516 case tok::starequal: Opc = BO_MulAssign; break; 13517 case tok::slashequal: Opc = BO_DivAssign; break; 13518 case tok::percentequal: Opc = BO_RemAssign; break; 13519 case tok::plusequal: Opc = BO_AddAssign; break; 13520 case tok::minusequal: Opc = BO_SubAssign; break; 13521 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13522 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13523 case tok::ampequal: Opc = BO_AndAssign; break; 13524 case tok::caretequal: Opc = BO_XorAssign; break; 13525 case tok::pipeequal: Opc = BO_OrAssign; break; 13526 case tok::comma: Opc = BO_Comma; break; 13527 } 13528 return Opc; 13529 } 13530 13531 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13532 tok::TokenKind Kind) { 13533 UnaryOperatorKind Opc; 13534 switch (Kind) { 13535 default: llvm_unreachable("Unknown unary op!"); 13536 case tok::plusplus: Opc = UO_PreInc; break; 13537 case tok::minusminus: Opc = UO_PreDec; break; 13538 case tok::amp: Opc = UO_AddrOf; break; 13539 case tok::star: Opc = UO_Deref; break; 13540 case tok::plus: Opc = UO_Plus; break; 13541 case tok::minus: Opc = UO_Minus; break; 13542 case tok::tilde: Opc = UO_Not; break; 13543 case tok::exclaim: Opc = UO_LNot; break; 13544 case tok::kw___real: Opc = UO_Real; break; 13545 case tok::kw___imag: Opc = UO_Imag; break; 13546 case tok::kw___extension__: Opc = UO_Extension; break; 13547 } 13548 return Opc; 13549 } 13550 13551 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13552 /// This warning suppressed in the event of macro expansions. 13553 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13554 SourceLocation OpLoc, bool IsBuiltin) { 13555 if (S.inTemplateInstantiation()) 13556 return; 13557 if (S.isUnevaluatedContext()) 13558 return; 13559 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13560 return; 13561 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13562 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13563 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13564 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13565 if (!LHSDeclRef || !RHSDeclRef || 13566 LHSDeclRef->getLocation().isMacroID() || 13567 RHSDeclRef->getLocation().isMacroID()) 13568 return; 13569 const ValueDecl *LHSDecl = 13570 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13571 const ValueDecl *RHSDecl = 13572 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13573 if (LHSDecl != RHSDecl) 13574 return; 13575 if (LHSDecl->getType().isVolatileQualified()) 13576 return; 13577 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13578 if (RefTy->getPointeeType().isVolatileQualified()) 13579 return; 13580 13581 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13582 : diag::warn_self_assignment_overloaded) 13583 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13584 << RHSExpr->getSourceRange(); 13585 } 13586 13587 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13588 /// is usually indicative of introspection within the Objective-C pointer. 13589 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13590 SourceLocation OpLoc) { 13591 if (!S.getLangOpts().ObjC) 13592 return; 13593 13594 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13595 const Expr *LHS = L.get(); 13596 const Expr *RHS = R.get(); 13597 13598 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13599 ObjCPointerExpr = LHS; 13600 OtherExpr = RHS; 13601 } 13602 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13603 ObjCPointerExpr = RHS; 13604 OtherExpr = LHS; 13605 } 13606 13607 // This warning is deliberately made very specific to reduce false 13608 // positives with logic that uses '&' for hashing. This logic mainly 13609 // looks for code trying to introspect into tagged pointers, which 13610 // code should generally never do. 13611 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13612 unsigned Diag = diag::warn_objc_pointer_masking; 13613 // Determine if we are introspecting the result of performSelectorXXX. 13614 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13615 // Special case messages to -performSelector and friends, which 13616 // can return non-pointer values boxed in a pointer value. 13617 // Some clients may wish to silence warnings in this subcase. 13618 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13619 Selector S = ME->getSelector(); 13620 StringRef SelArg0 = S.getNameForSlot(0); 13621 if (SelArg0.startswith("performSelector")) 13622 Diag = diag::warn_objc_pointer_masking_performSelector; 13623 } 13624 13625 S.Diag(OpLoc, Diag) 13626 << ObjCPointerExpr->getSourceRange(); 13627 } 13628 } 13629 13630 static NamedDecl *getDeclFromExpr(Expr *E) { 13631 if (!E) 13632 return nullptr; 13633 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13634 return DRE->getDecl(); 13635 if (auto *ME = dyn_cast<MemberExpr>(E)) 13636 return ME->getMemberDecl(); 13637 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13638 return IRE->getDecl(); 13639 return nullptr; 13640 } 13641 13642 // This helper function promotes a binary operator's operands (which are of a 13643 // half vector type) to a vector of floats and then truncates the result to 13644 // a vector of either half or short. 13645 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13646 BinaryOperatorKind Opc, QualType ResultTy, 13647 ExprValueKind VK, ExprObjectKind OK, 13648 bool IsCompAssign, SourceLocation OpLoc, 13649 FPOptionsOverride FPFeatures) { 13650 auto &Context = S.getASTContext(); 13651 assert((isVector(ResultTy, Context.HalfTy) || 13652 isVector(ResultTy, Context.ShortTy)) && 13653 "Result must be a vector of half or short"); 13654 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13655 isVector(RHS.get()->getType(), Context.HalfTy) && 13656 "both operands expected to be a half vector"); 13657 13658 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13659 QualType BinOpResTy = RHS.get()->getType(); 13660 13661 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13662 // change BinOpResTy to a vector of ints. 13663 if (isVector(ResultTy, Context.ShortTy)) 13664 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13665 13666 if (IsCompAssign) 13667 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13668 ResultTy, VK, OK, OpLoc, FPFeatures, 13669 BinOpResTy, BinOpResTy); 13670 13671 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13672 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13673 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13674 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13675 } 13676 13677 static std::pair<ExprResult, ExprResult> 13678 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13679 Expr *RHSExpr) { 13680 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13681 if (!S.getLangOpts().CPlusPlus) { 13682 // C cannot handle TypoExpr nodes on either side of a binop because it 13683 // doesn't handle dependent types properly, so make sure any TypoExprs have 13684 // been dealt with before checking the operands. 13685 LHS = S.CorrectDelayedTyposInExpr(LHS); 13686 RHS = S.CorrectDelayedTyposInExpr( 13687 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13688 [Opc, LHS](Expr *E) { 13689 if (Opc != BO_Assign) 13690 return ExprResult(E); 13691 // Avoid correcting the RHS to the same Expr as the LHS. 13692 Decl *D = getDeclFromExpr(E); 13693 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13694 }); 13695 } 13696 return std::make_pair(LHS, RHS); 13697 } 13698 13699 /// Returns true if conversion between vectors of halfs and vectors of floats 13700 /// is needed. 13701 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13702 Expr *E0, Expr *E1 = nullptr) { 13703 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13704 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13705 return false; 13706 13707 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13708 QualType Ty = E->IgnoreImplicit()->getType(); 13709 13710 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13711 // to vectors of floats. Although the element type of the vectors is __fp16, 13712 // the vectors shouldn't be treated as storage-only types. See the 13713 // discussion here: https://reviews.llvm.org/rG825235c140e7 13714 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13715 if (VT->getVectorKind() == VectorType::NeonVector) 13716 return false; 13717 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13718 } 13719 return false; 13720 }; 13721 13722 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13723 } 13724 13725 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13726 /// operator @p Opc at location @c TokLoc. This routine only supports 13727 /// built-in operations; ActOnBinOp handles overloaded operators. 13728 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13729 BinaryOperatorKind Opc, 13730 Expr *LHSExpr, Expr *RHSExpr) { 13731 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13732 // The syntax only allows initializer lists on the RHS of assignment, 13733 // so we don't need to worry about accepting invalid code for 13734 // non-assignment operators. 13735 // C++11 5.17p9: 13736 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13737 // of x = {} is x = T(). 13738 InitializationKind Kind = InitializationKind::CreateDirectList( 13739 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13740 InitializedEntity Entity = 13741 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13742 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13743 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13744 if (Init.isInvalid()) 13745 return Init; 13746 RHSExpr = Init.get(); 13747 } 13748 13749 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13750 QualType ResultTy; // Result type of the binary operator. 13751 // The following two variables are used for compound assignment operators 13752 QualType CompLHSTy; // Type of LHS after promotions for computation 13753 QualType CompResultTy; // Type of computation result 13754 ExprValueKind VK = VK_RValue; 13755 ExprObjectKind OK = OK_Ordinary; 13756 bool ConvertHalfVec = false; 13757 13758 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13759 if (!LHS.isUsable() || !RHS.isUsable()) 13760 return ExprError(); 13761 13762 if (getLangOpts().OpenCL) { 13763 QualType LHSTy = LHSExpr->getType(); 13764 QualType RHSTy = RHSExpr->getType(); 13765 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13766 // the ATOMIC_VAR_INIT macro. 13767 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13768 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13769 if (BO_Assign == Opc) 13770 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13771 else 13772 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13773 return ExprError(); 13774 } 13775 13776 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13777 // only with a builtin functions and therefore should be disallowed here. 13778 if (LHSTy->isImageType() || RHSTy->isImageType() || 13779 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13780 LHSTy->isPipeType() || RHSTy->isPipeType() || 13781 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13782 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13783 return ExprError(); 13784 } 13785 } 13786 13787 switch (Opc) { 13788 case BO_Assign: 13789 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13790 if (getLangOpts().CPlusPlus && 13791 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13792 VK = LHS.get()->getValueKind(); 13793 OK = LHS.get()->getObjectKind(); 13794 } 13795 if (!ResultTy.isNull()) { 13796 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13797 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13798 13799 // Avoid copying a block to the heap if the block is assigned to a local 13800 // auto variable that is declared in the same scope as the block. This 13801 // optimization is unsafe if the local variable is declared in an outer 13802 // scope. For example: 13803 // 13804 // BlockTy b; 13805 // { 13806 // b = ^{...}; 13807 // } 13808 // // It is unsafe to invoke the block here if it wasn't copied to the 13809 // // heap. 13810 // b(); 13811 13812 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13813 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13814 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13815 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13816 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13817 13818 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13819 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13820 NTCUC_Assignment, NTCUK_Copy); 13821 } 13822 RecordModifiableNonNullParam(*this, LHS.get()); 13823 break; 13824 case BO_PtrMemD: 13825 case BO_PtrMemI: 13826 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13827 Opc == BO_PtrMemI); 13828 break; 13829 case BO_Mul: 13830 case BO_Div: 13831 ConvertHalfVec = true; 13832 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13833 Opc == BO_Div); 13834 break; 13835 case BO_Rem: 13836 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13837 break; 13838 case BO_Add: 13839 ConvertHalfVec = true; 13840 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13841 break; 13842 case BO_Sub: 13843 ConvertHalfVec = true; 13844 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13845 break; 13846 case BO_Shl: 13847 case BO_Shr: 13848 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13849 break; 13850 case BO_LE: 13851 case BO_LT: 13852 case BO_GE: 13853 case BO_GT: 13854 ConvertHalfVec = true; 13855 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13856 break; 13857 case BO_EQ: 13858 case BO_NE: 13859 ConvertHalfVec = true; 13860 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13861 break; 13862 case BO_Cmp: 13863 ConvertHalfVec = true; 13864 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13865 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13866 break; 13867 case BO_And: 13868 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13869 LLVM_FALLTHROUGH; 13870 case BO_Xor: 13871 case BO_Or: 13872 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13873 break; 13874 case BO_LAnd: 13875 case BO_LOr: 13876 ConvertHalfVec = true; 13877 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13878 break; 13879 case BO_MulAssign: 13880 case BO_DivAssign: 13881 ConvertHalfVec = true; 13882 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13883 Opc == BO_DivAssign); 13884 CompLHSTy = CompResultTy; 13885 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13886 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13887 break; 13888 case BO_RemAssign: 13889 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13890 CompLHSTy = CompResultTy; 13891 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13892 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13893 break; 13894 case BO_AddAssign: 13895 ConvertHalfVec = true; 13896 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13897 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13898 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13899 break; 13900 case BO_SubAssign: 13901 ConvertHalfVec = true; 13902 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13903 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13904 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13905 break; 13906 case BO_ShlAssign: 13907 case BO_ShrAssign: 13908 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13909 CompLHSTy = CompResultTy; 13910 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13911 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13912 break; 13913 case BO_AndAssign: 13914 case BO_OrAssign: // fallthrough 13915 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13916 LLVM_FALLTHROUGH; 13917 case BO_XorAssign: 13918 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13919 CompLHSTy = CompResultTy; 13920 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13921 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13922 break; 13923 case BO_Comma: 13924 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13925 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13926 VK = RHS.get()->getValueKind(); 13927 OK = RHS.get()->getObjectKind(); 13928 } 13929 break; 13930 } 13931 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13932 return ExprError(); 13933 13934 // Some of the binary operations require promoting operands of half vector to 13935 // float vectors and truncating the result back to half vector. For now, we do 13936 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13937 // arm64). 13938 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13939 isVector(LHS.get()->getType(), Context.HalfTy) && 13940 "both sides are half vectors or neither sides are"); 13941 ConvertHalfVec = 13942 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13943 13944 // Check for array bounds violations for both sides of the BinaryOperator 13945 CheckArrayAccess(LHS.get()); 13946 CheckArrayAccess(RHS.get()); 13947 13948 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13949 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13950 &Context.Idents.get("object_setClass"), 13951 SourceLocation(), LookupOrdinaryName); 13952 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13953 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13954 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13955 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13956 "object_setClass(") 13957 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13958 ",") 13959 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13960 } 13961 else 13962 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13963 } 13964 else if (const ObjCIvarRefExpr *OIRE = 13965 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13966 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13967 13968 // Opc is not a compound assignment if CompResultTy is null. 13969 if (CompResultTy.isNull()) { 13970 if (ConvertHalfVec) 13971 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13972 OpLoc, CurFPFeatureOverrides()); 13973 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13974 VK, OK, OpLoc, CurFPFeatureOverrides()); 13975 } 13976 13977 // Handle compound assignments. 13978 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13979 OK_ObjCProperty) { 13980 VK = VK_LValue; 13981 OK = LHS.get()->getObjectKind(); 13982 } 13983 13984 // The LHS is not converted to the result type for fixed-point compound 13985 // assignment as the common type is computed on demand. Reset the CompLHSTy 13986 // to the LHS type we would have gotten after unary conversions. 13987 if (CompResultTy->isFixedPointType()) 13988 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13989 13990 if (ConvertHalfVec) 13991 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13992 OpLoc, CurFPFeatureOverrides()); 13993 13994 return CompoundAssignOperator::Create( 13995 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 13996 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 13997 } 13998 13999 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14000 /// operators are mixed in a way that suggests that the programmer forgot that 14001 /// comparison operators have higher precedence. The most typical example of 14002 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14003 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14004 SourceLocation OpLoc, Expr *LHSExpr, 14005 Expr *RHSExpr) { 14006 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14007 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14008 14009 // Check that one of the sides is a comparison operator and the other isn't. 14010 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14011 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14012 if (isLeftComp == isRightComp) 14013 return; 14014 14015 // Bitwise operations are sometimes used as eager logical ops. 14016 // Don't diagnose this. 14017 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14018 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14019 if (isLeftBitwise || isRightBitwise) 14020 return; 14021 14022 SourceRange DiagRange = isLeftComp 14023 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14024 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14025 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14026 SourceRange ParensRange = 14027 isLeftComp 14028 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14029 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14030 14031 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14032 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14033 SuggestParentheses(Self, OpLoc, 14034 Self.PDiag(diag::note_precedence_silence) << OpStr, 14035 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14036 SuggestParentheses(Self, OpLoc, 14037 Self.PDiag(diag::note_precedence_bitwise_first) 14038 << BinaryOperator::getOpcodeStr(Opc), 14039 ParensRange); 14040 } 14041 14042 /// It accepts a '&&' expr that is inside a '||' one. 14043 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14044 /// in parentheses. 14045 static void 14046 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14047 BinaryOperator *Bop) { 14048 assert(Bop->getOpcode() == BO_LAnd); 14049 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14050 << Bop->getSourceRange() << OpLoc; 14051 SuggestParentheses(Self, Bop->getOperatorLoc(), 14052 Self.PDiag(diag::note_precedence_silence) 14053 << Bop->getOpcodeStr(), 14054 Bop->getSourceRange()); 14055 } 14056 14057 /// Returns true if the given expression can be evaluated as a constant 14058 /// 'true'. 14059 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14060 bool Res; 14061 return !E->isValueDependent() && 14062 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14063 } 14064 14065 /// Returns true if the given expression can be evaluated as a constant 14066 /// 'false'. 14067 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14068 bool Res; 14069 return !E->isValueDependent() && 14070 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14071 } 14072 14073 /// Look for '&&' in the left hand of a '||' expr. 14074 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14075 Expr *LHSExpr, Expr *RHSExpr) { 14076 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14077 if (Bop->getOpcode() == BO_LAnd) { 14078 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14079 if (EvaluatesAsFalse(S, RHSExpr)) 14080 return; 14081 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14082 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14083 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14084 } else if (Bop->getOpcode() == BO_LOr) { 14085 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14086 // If it's "a || b && 1 || c" we didn't warn earlier for 14087 // "a || b && 1", but warn now. 14088 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14089 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14090 } 14091 } 14092 } 14093 } 14094 14095 /// Look for '&&' in the right hand of a '||' expr. 14096 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14097 Expr *LHSExpr, Expr *RHSExpr) { 14098 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14099 if (Bop->getOpcode() == BO_LAnd) { 14100 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14101 if (EvaluatesAsFalse(S, LHSExpr)) 14102 return; 14103 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14104 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14105 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14106 } 14107 } 14108 } 14109 14110 /// Look for bitwise op in the left or right hand of a bitwise op with 14111 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14112 /// the '&' expression in parentheses. 14113 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14114 SourceLocation OpLoc, Expr *SubExpr) { 14115 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14116 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14117 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14118 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14119 << Bop->getSourceRange() << OpLoc; 14120 SuggestParentheses(S, Bop->getOperatorLoc(), 14121 S.PDiag(diag::note_precedence_silence) 14122 << Bop->getOpcodeStr(), 14123 Bop->getSourceRange()); 14124 } 14125 } 14126 } 14127 14128 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14129 Expr *SubExpr, StringRef Shift) { 14130 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14131 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14132 StringRef Op = Bop->getOpcodeStr(); 14133 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14134 << Bop->getSourceRange() << OpLoc << Shift << Op; 14135 SuggestParentheses(S, Bop->getOperatorLoc(), 14136 S.PDiag(diag::note_precedence_silence) << Op, 14137 Bop->getSourceRange()); 14138 } 14139 } 14140 } 14141 14142 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14143 Expr *LHSExpr, Expr *RHSExpr) { 14144 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14145 if (!OCE) 14146 return; 14147 14148 FunctionDecl *FD = OCE->getDirectCallee(); 14149 if (!FD || !FD->isOverloadedOperator()) 14150 return; 14151 14152 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14153 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14154 return; 14155 14156 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14157 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14158 << (Kind == OO_LessLess); 14159 SuggestParentheses(S, OCE->getOperatorLoc(), 14160 S.PDiag(diag::note_precedence_silence) 14161 << (Kind == OO_LessLess ? "<<" : ">>"), 14162 OCE->getSourceRange()); 14163 SuggestParentheses( 14164 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14165 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14166 } 14167 14168 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14169 /// precedence. 14170 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14171 SourceLocation OpLoc, Expr *LHSExpr, 14172 Expr *RHSExpr){ 14173 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14174 if (BinaryOperator::isBitwiseOp(Opc)) 14175 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14176 14177 // Diagnose "arg1 & arg2 | arg3" 14178 if ((Opc == BO_Or || Opc == BO_Xor) && 14179 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14180 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14181 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14182 } 14183 14184 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14185 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14186 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14187 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14188 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14189 } 14190 14191 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14192 || Opc == BO_Shr) { 14193 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14194 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14195 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14196 } 14197 14198 // Warn on overloaded shift operators and comparisons, such as: 14199 // cout << 5 == 4; 14200 if (BinaryOperator::isComparisonOp(Opc)) 14201 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14202 } 14203 14204 // Binary Operators. 'Tok' is the token for the operator. 14205 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14206 tok::TokenKind Kind, 14207 Expr *LHSExpr, Expr *RHSExpr) { 14208 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14209 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14210 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14211 14212 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14213 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14214 14215 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14216 } 14217 14218 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14219 UnresolvedSetImpl &Functions) { 14220 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14221 if (OverOp != OO_None && OverOp != OO_Equal) 14222 LookupOverloadedOperatorName(OverOp, S, Functions); 14223 14224 // In C++20 onwards, we may have a second operator to look up. 14225 if (getLangOpts().CPlusPlus20) { 14226 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14227 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14228 } 14229 } 14230 14231 /// Build an overloaded binary operator expression in the given scope. 14232 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14233 BinaryOperatorKind Opc, 14234 Expr *LHS, Expr *RHS) { 14235 switch (Opc) { 14236 case BO_Assign: 14237 case BO_DivAssign: 14238 case BO_RemAssign: 14239 case BO_SubAssign: 14240 case BO_AndAssign: 14241 case BO_OrAssign: 14242 case BO_XorAssign: 14243 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14244 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14245 break; 14246 default: 14247 break; 14248 } 14249 14250 // Find all of the overloaded operators visible from this point. 14251 UnresolvedSet<16> Functions; 14252 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14253 14254 // Build the (potentially-overloaded, potentially-dependent) 14255 // binary operation. 14256 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14257 } 14258 14259 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14260 BinaryOperatorKind Opc, 14261 Expr *LHSExpr, Expr *RHSExpr) { 14262 ExprResult LHS, RHS; 14263 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14264 if (!LHS.isUsable() || !RHS.isUsable()) 14265 return ExprError(); 14266 LHSExpr = LHS.get(); 14267 RHSExpr = RHS.get(); 14268 14269 // We want to end up calling one of checkPseudoObjectAssignment 14270 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14271 // both expressions are overloadable or either is type-dependent), 14272 // or CreateBuiltinBinOp (in any other case). We also want to get 14273 // any placeholder types out of the way. 14274 14275 // Handle pseudo-objects in the LHS. 14276 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14277 // Assignments with a pseudo-object l-value need special analysis. 14278 if (pty->getKind() == BuiltinType::PseudoObject && 14279 BinaryOperator::isAssignmentOp(Opc)) 14280 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14281 14282 // Don't resolve overloads if the other type is overloadable. 14283 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14284 // We can't actually test that if we still have a placeholder, 14285 // though. Fortunately, none of the exceptions we see in that 14286 // code below are valid when the LHS is an overload set. Note 14287 // that an overload set can be dependently-typed, but it never 14288 // instantiates to having an overloadable type. 14289 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14290 if (resolvedRHS.isInvalid()) return ExprError(); 14291 RHSExpr = resolvedRHS.get(); 14292 14293 if (RHSExpr->isTypeDependent() || 14294 RHSExpr->getType()->isOverloadableType()) 14295 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14296 } 14297 14298 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14299 // template, diagnose the missing 'template' keyword instead of diagnosing 14300 // an invalid use of a bound member function. 14301 // 14302 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14303 // to C++1z [over.over]/1.4, but we already checked for that case above. 14304 if (Opc == BO_LT && inTemplateInstantiation() && 14305 (pty->getKind() == BuiltinType::BoundMember || 14306 pty->getKind() == BuiltinType::Overload)) { 14307 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14308 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14309 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14310 return isa<FunctionTemplateDecl>(ND); 14311 })) { 14312 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14313 : OE->getNameLoc(), 14314 diag::err_template_kw_missing) 14315 << OE->getName().getAsString() << ""; 14316 return ExprError(); 14317 } 14318 } 14319 14320 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14321 if (LHS.isInvalid()) return ExprError(); 14322 LHSExpr = LHS.get(); 14323 } 14324 14325 // Handle pseudo-objects in the RHS. 14326 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14327 // An overload in the RHS can potentially be resolved by the type 14328 // being assigned to. 14329 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14330 if (getLangOpts().CPlusPlus && 14331 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14332 LHSExpr->getType()->isOverloadableType())) 14333 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14334 14335 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14336 } 14337 14338 // Don't resolve overloads if the other type is overloadable. 14339 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14340 LHSExpr->getType()->isOverloadableType()) 14341 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14342 14343 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14344 if (!resolvedRHS.isUsable()) return ExprError(); 14345 RHSExpr = resolvedRHS.get(); 14346 } 14347 14348 if (getLangOpts().CPlusPlus) { 14349 // If either expression is type-dependent, always build an 14350 // overloaded op. 14351 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14352 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14353 14354 // Otherwise, build an overloaded op if either expression has an 14355 // overloadable type. 14356 if (LHSExpr->getType()->isOverloadableType() || 14357 RHSExpr->getType()->isOverloadableType()) 14358 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14359 } 14360 14361 // Build a built-in binary operation. 14362 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14363 } 14364 14365 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14366 if (T.isNull() || T->isDependentType()) 14367 return false; 14368 14369 if (!T->isPromotableIntegerType()) 14370 return true; 14371 14372 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14373 } 14374 14375 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14376 UnaryOperatorKind Opc, 14377 Expr *InputExpr) { 14378 ExprResult Input = InputExpr; 14379 ExprValueKind VK = VK_RValue; 14380 ExprObjectKind OK = OK_Ordinary; 14381 QualType resultType; 14382 bool CanOverflow = false; 14383 14384 bool ConvertHalfVec = false; 14385 if (getLangOpts().OpenCL) { 14386 QualType Ty = InputExpr->getType(); 14387 // The only legal unary operation for atomics is '&'. 14388 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14389 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14390 // only with a builtin functions and therefore should be disallowed here. 14391 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14392 || Ty->isBlockPointerType())) { 14393 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14394 << InputExpr->getType() 14395 << Input.get()->getSourceRange()); 14396 } 14397 } 14398 14399 switch (Opc) { 14400 case UO_PreInc: 14401 case UO_PreDec: 14402 case UO_PostInc: 14403 case UO_PostDec: 14404 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14405 OpLoc, 14406 Opc == UO_PreInc || 14407 Opc == UO_PostInc, 14408 Opc == UO_PreInc || 14409 Opc == UO_PreDec); 14410 CanOverflow = isOverflowingIntegerType(Context, resultType); 14411 break; 14412 case UO_AddrOf: 14413 resultType = CheckAddressOfOperand(Input, OpLoc); 14414 CheckAddressOfNoDeref(InputExpr); 14415 RecordModifiableNonNullParam(*this, InputExpr); 14416 break; 14417 case UO_Deref: { 14418 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14419 if (Input.isInvalid()) return ExprError(); 14420 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14421 break; 14422 } 14423 case UO_Plus: 14424 case UO_Minus: 14425 CanOverflow = Opc == UO_Minus && 14426 isOverflowingIntegerType(Context, Input.get()->getType()); 14427 Input = UsualUnaryConversions(Input.get()); 14428 if (Input.isInvalid()) return ExprError(); 14429 // Unary plus and minus require promoting an operand of half vector to a 14430 // float vector and truncating the result back to a half vector. For now, we 14431 // do this only when HalfArgsAndReturns is set (that is, when the target is 14432 // arm or arm64). 14433 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14434 14435 // If the operand is a half vector, promote it to a float vector. 14436 if (ConvertHalfVec) 14437 Input = convertVector(Input.get(), Context.FloatTy, *this); 14438 resultType = Input.get()->getType(); 14439 if (resultType->isDependentType()) 14440 break; 14441 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14442 break; 14443 else if (resultType->isVectorType() && 14444 // The z vector extensions don't allow + or - with bool vectors. 14445 (!Context.getLangOpts().ZVector || 14446 resultType->castAs<VectorType>()->getVectorKind() != 14447 VectorType::AltiVecBool)) 14448 break; 14449 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14450 Opc == UO_Plus && 14451 resultType->isPointerType()) 14452 break; 14453 14454 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14455 << resultType << Input.get()->getSourceRange()); 14456 14457 case UO_Not: // bitwise complement 14458 Input = UsualUnaryConversions(Input.get()); 14459 if (Input.isInvalid()) 14460 return ExprError(); 14461 resultType = Input.get()->getType(); 14462 if (resultType->isDependentType()) 14463 break; 14464 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14465 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14466 // C99 does not support '~' for complex conjugation. 14467 Diag(OpLoc, diag::ext_integer_complement_complex) 14468 << resultType << Input.get()->getSourceRange(); 14469 else if (resultType->hasIntegerRepresentation()) 14470 break; 14471 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14472 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14473 // on vector float types. 14474 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14475 if (!T->isIntegerType()) 14476 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14477 << resultType << Input.get()->getSourceRange()); 14478 } else { 14479 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14480 << resultType << Input.get()->getSourceRange()); 14481 } 14482 break; 14483 14484 case UO_LNot: // logical negation 14485 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14486 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14487 if (Input.isInvalid()) return ExprError(); 14488 resultType = Input.get()->getType(); 14489 14490 // Though we still have to promote half FP to float... 14491 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14492 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14493 resultType = Context.FloatTy; 14494 } 14495 14496 if (resultType->isDependentType()) 14497 break; 14498 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14499 // C99 6.5.3.3p1: ok, fallthrough; 14500 if (Context.getLangOpts().CPlusPlus) { 14501 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14502 // operand contextually converted to bool. 14503 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14504 ScalarTypeToBooleanCastKind(resultType)); 14505 } else if (Context.getLangOpts().OpenCL && 14506 Context.getLangOpts().OpenCLVersion < 120) { 14507 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14508 // operate on scalar float types. 14509 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14510 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14511 << resultType << Input.get()->getSourceRange()); 14512 } 14513 } else if (resultType->isExtVectorType()) { 14514 if (Context.getLangOpts().OpenCL && 14515 Context.getLangOpts().OpenCLVersion < 120 && 14516 !Context.getLangOpts().OpenCLCPlusPlus) { 14517 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14518 // operate on vector float types. 14519 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14520 if (!T->isIntegerType()) 14521 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14522 << resultType << Input.get()->getSourceRange()); 14523 } 14524 // Vector logical not returns the signed variant of the operand type. 14525 resultType = GetSignedVectorType(resultType); 14526 break; 14527 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14528 const VectorType *VTy = resultType->castAs<VectorType>(); 14529 if (VTy->getVectorKind() != VectorType::GenericVector) 14530 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14531 << resultType << Input.get()->getSourceRange()); 14532 14533 // Vector logical not returns the signed variant of the operand type. 14534 resultType = GetSignedVectorType(resultType); 14535 break; 14536 } else { 14537 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14538 << resultType << Input.get()->getSourceRange()); 14539 } 14540 14541 // LNot always has type int. C99 6.5.3.3p5. 14542 // In C++, it's bool. C++ 5.3.1p8 14543 resultType = Context.getLogicalOperationType(); 14544 break; 14545 case UO_Real: 14546 case UO_Imag: 14547 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14548 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14549 // complex l-values to ordinary l-values and all other values to r-values. 14550 if (Input.isInvalid()) return ExprError(); 14551 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14552 if (Input.get()->getValueKind() != VK_RValue && 14553 Input.get()->getObjectKind() == OK_Ordinary) 14554 VK = Input.get()->getValueKind(); 14555 } else if (!getLangOpts().CPlusPlus) { 14556 // In C, a volatile scalar is read by __imag. In C++, it is not. 14557 Input = DefaultLvalueConversion(Input.get()); 14558 } 14559 break; 14560 case UO_Extension: 14561 resultType = Input.get()->getType(); 14562 VK = Input.get()->getValueKind(); 14563 OK = Input.get()->getObjectKind(); 14564 break; 14565 case UO_Coawait: 14566 // It's unnecessary to represent the pass-through operator co_await in the 14567 // AST; just return the input expression instead. 14568 assert(!Input.get()->getType()->isDependentType() && 14569 "the co_await expression must be non-dependant before " 14570 "building operator co_await"); 14571 return Input; 14572 } 14573 if (resultType.isNull() || Input.isInvalid()) 14574 return ExprError(); 14575 14576 // Check for array bounds violations in the operand of the UnaryOperator, 14577 // except for the '*' and '&' operators that have to be handled specially 14578 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14579 // that are explicitly defined as valid by the standard). 14580 if (Opc != UO_AddrOf && Opc != UO_Deref) 14581 CheckArrayAccess(Input.get()); 14582 14583 auto *UO = 14584 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14585 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14586 14587 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14588 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14589 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14590 14591 // Convert the result back to a half vector. 14592 if (ConvertHalfVec) 14593 return convertVector(UO, Context.HalfTy, *this); 14594 return UO; 14595 } 14596 14597 /// Determine whether the given expression is a qualified member 14598 /// access expression, of a form that could be turned into a pointer to member 14599 /// with the address-of operator. 14600 bool Sema::isQualifiedMemberAccess(Expr *E) { 14601 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14602 if (!DRE->getQualifier()) 14603 return false; 14604 14605 ValueDecl *VD = DRE->getDecl(); 14606 if (!VD->isCXXClassMember()) 14607 return false; 14608 14609 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14610 return true; 14611 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14612 return Method->isInstance(); 14613 14614 return false; 14615 } 14616 14617 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14618 if (!ULE->getQualifier()) 14619 return false; 14620 14621 for (NamedDecl *D : ULE->decls()) { 14622 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14623 if (Method->isInstance()) 14624 return true; 14625 } else { 14626 // Overload set does not contain methods. 14627 break; 14628 } 14629 } 14630 14631 return false; 14632 } 14633 14634 return false; 14635 } 14636 14637 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14638 UnaryOperatorKind Opc, Expr *Input) { 14639 // First things first: handle placeholders so that the 14640 // overloaded-operator check considers the right type. 14641 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14642 // Increment and decrement of pseudo-object references. 14643 if (pty->getKind() == BuiltinType::PseudoObject && 14644 UnaryOperator::isIncrementDecrementOp(Opc)) 14645 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14646 14647 // extension is always a builtin operator. 14648 if (Opc == UO_Extension) 14649 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14650 14651 // & gets special logic for several kinds of placeholder. 14652 // The builtin code knows what to do. 14653 if (Opc == UO_AddrOf && 14654 (pty->getKind() == BuiltinType::Overload || 14655 pty->getKind() == BuiltinType::UnknownAny || 14656 pty->getKind() == BuiltinType::BoundMember)) 14657 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14658 14659 // Anything else needs to be handled now. 14660 ExprResult Result = CheckPlaceholderExpr(Input); 14661 if (Result.isInvalid()) return ExprError(); 14662 Input = Result.get(); 14663 } 14664 14665 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14666 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14667 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14668 // Find all of the overloaded operators visible from this point. 14669 UnresolvedSet<16> Functions; 14670 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14671 if (S && OverOp != OO_None) 14672 LookupOverloadedOperatorName(OverOp, S, Functions); 14673 14674 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14675 } 14676 14677 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14678 } 14679 14680 // Unary Operators. 'Tok' is the token for the operator. 14681 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14682 tok::TokenKind Op, Expr *Input) { 14683 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14684 } 14685 14686 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14687 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14688 LabelDecl *TheDecl) { 14689 TheDecl->markUsed(Context); 14690 // Create the AST node. The address of a label always has type 'void*'. 14691 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14692 Context.getPointerType(Context.VoidTy)); 14693 } 14694 14695 void Sema::ActOnStartStmtExpr() { 14696 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14697 } 14698 14699 void Sema::ActOnStmtExprError() { 14700 // Note that function is also called by TreeTransform when leaving a 14701 // StmtExpr scope without rebuilding anything. 14702 14703 DiscardCleanupsInEvaluationContext(); 14704 PopExpressionEvaluationContext(); 14705 } 14706 14707 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14708 SourceLocation RPLoc) { 14709 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14710 } 14711 14712 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14713 SourceLocation RPLoc, unsigned TemplateDepth) { 14714 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14715 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14716 14717 if (hasAnyUnrecoverableErrorsInThisFunction()) 14718 DiscardCleanupsInEvaluationContext(); 14719 assert(!Cleanup.exprNeedsCleanups() && 14720 "cleanups within StmtExpr not correctly bound!"); 14721 PopExpressionEvaluationContext(); 14722 14723 // FIXME: there are a variety of strange constraints to enforce here, for 14724 // example, it is not possible to goto into a stmt expression apparently. 14725 // More semantic analysis is needed. 14726 14727 // If there are sub-stmts in the compound stmt, take the type of the last one 14728 // as the type of the stmtexpr. 14729 QualType Ty = Context.VoidTy; 14730 bool StmtExprMayBindToTemp = false; 14731 if (!Compound->body_empty()) { 14732 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14733 if (const auto *LastStmt = 14734 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14735 if (const Expr *Value = LastStmt->getExprStmt()) { 14736 StmtExprMayBindToTemp = true; 14737 Ty = Value->getType(); 14738 } 14739 } 14740 } 14741 14742 // FIXME: Check that expression type is complete/non-abstract; statement 14743 // expressions are not lvalues. 14744 Expr *ResStmtExpr = 14745 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14746 if (StmtExprMayBindToTemp) 14747 return MaybeBindToTemporary(ResStmtExpr); 14748 return ResStmtExpr; 14749 } 14750 14751 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14752 if (ER.isInvalid()) 14753 return ExprError(); 14754 14755 // Do function/array conversion on the last expression, but not 14756 // lvalue-to-rvalue. However, initialize an unqualified type. 14757 ER = DefaultFunctionArrayConversion(ER.get()); 14758 if (ER.isInvalid()) 14759 return ExprError(); 14760 Expr *E = ER.get(); 14761 14762 if (E->isTypeDependent()) 14763 return E; 14764 14765 // In ARC, if the final expression ends in a consume, splice 14766 // the consume out and bind it later. In the alternate case 14767 // (when dealing with a retainable type), the result 14768 // initialization will create a produce. In both cases the 14769 // result will be +1, and we'll need to balance that out with 14770 // a bind. 14771 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14772 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14773 return Cast->getSubExpr(); 14774 14775 // FIXME: Provide a better location for the initialization. 14776 return PerformCopyInitialization( 14777 InitializedEntity::InitializeStmtExprResult( 14778 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14779 SourceLocation(), E); 14780 } 14781 14782 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14783 TypeSourceInfo *TInfo, 14784 ArrayRef<OffsetOfComponent> Components, 14785 SourceLocation RParenLoc) { 14786 QualType ArgTy = TInfo->getType(); 14787 bool Dependent = ArgTy->isDependentType(); 14788 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14789 14790 // We must have at least one component that refers to the type, and the first 14791 // one is known to be a field designator. Verify that the ArgTy represents 14792 // a struct/union/class. 14793 if (!Dependent && !ArgTy->isRecordType()) 14794 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14795 << ArgTy << TypeRange); 14796 14797 // Type must be complete per C99 7.17p3 because a declaring a variable 14798 // with an incomplete type would be ill-formed. 14799 if (!Dependent 14800 && RequireCompleteType(BuiltinLoc, ArgTy, 14801 diag::err_offsetof_incomplete_type, TypeRange)) 14802 return ExprError(); 14803 14804 bool DidWarnAboutNonPOD = false; 14805 QualType CurrentType = ArgTy; 14806 SmallVector<OffsetOfNode, 4> Comps; 14807 SmallVector<Expr*, 4> Exprs; 14808 for (const OffsetOfComponent &OC : Components) { 14809 if (OC.isBrackets) { 14810 // Offset of an array sub-field. TODO: Should we allow vector elements? 14811 if (!CurrentType->isDependentType()) { 14812 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14813 if(!AT) 14814 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14815 << CurrentType); 14816 CurrentType = AT->getElementType(); 14817 } else 14818 CurrentType = Context.DependentTy; 14819 14820 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14821 if (IdxRval.isInvalid()) 14822 return ExprError(); 14823 Expr *Idx = IdxRval.get(); 14824 14825 // The expression must be an integral expression. 14826 // FIXME: An integral constant expression? 14827 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14828 !Idx->getType()->isIntegerType()) 14829 return ExprError( 14830 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14831 << Idx->getSourceRange()); 14832 14833 // Record this array index. 14834 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14835 Exprs.push_back(Idx); 14836 continue; 14837 } 14838 14839 // Offset of a field. 14840 if (CurrentType->isDependentType()) { 14841 // We have the offset of a field, but we can't look into the dependent 14842 // type. Just record the identifier of the field. 14843 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14844 CurrentType = Context.DependentTy; 14845 continue; 14846 } 14847 14848 // We need to have a complete type to look into. 14849 if (RequireCompleteType(OC.LocStart, CurrentType, 14850 diag::err_offsetof_incomplete_type)) 14851 return ExprError(); 14852 14853 // Look for the designated field. 14854 const RecordType *RC = CurrentType->getAs<RecordType>(); 14855 if (!RC) 14856 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14857 << CurrentType); 14858 RecordDecl *RD = RC->getDecl(); 14859 14860 // C++ [lib.support.types]p5: 14861 // The macro offsetof accepts a restricted set of type arguments in this 14862 // International Standard. type shall be a POD structure or a POD union 14863 // (clause 9). 14864 // C++11 [support.types]p4: 14865 // If type is not a standard-layout class (Clause 9), the results are 14866 // undefined. 14867 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14868 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14869 unsigned DiagID = 14870 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14871 : diag::ext_offsetof_non_pod_type; 14872 14873 if (!IsSafe && !DidWarnAboutNonPOD && 14874 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14875 PDiag(DiagID) 14876 << SourceRange(Components[0].LocStart, OC.LocEnd) 14877 << CurrentType)) 14878 DidWarnAboutNonPOD = true; 14879 } 14880 14881 // Look for the field. 14882 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14883 LookupQualifiedName(R, RD); 14884 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14885 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14886 if (!MemberDecl) { 14887 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14888 MemberDecl = IndirectMemberDecl->getAnonField(); 14889 } 14890 14891 if (!MemberDecl) 14892 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14893 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14894 OC.LocEnd)); 14895 14896 // C99 7.17p3: 14897 // (If the specified member is a bit-field, the behavior is undefined.) 14898 // 14899 // We diagnose this as an error. 14900 if (MemberDecl->isBitField()) { 14901 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14902 << MemberDecl->getDeclName() 14903 << SourceRange(BuiltinLoc, RParenLoc); 14904 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14905 return ExprError(); 14906 } 14907 14908 RecordDecl *Parent = MemberDecl->getParent(); 14909 if (IndirectMemberDecl) 14910 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14911 14912 // If the member was found in a base class, introduce OffsetOfNodes for 14913 // the base class indirections. 14914 CXXBasePaths Paths; 14915 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14916 Paths)) { 14917 if (Paths.getDetectedVirtual()) { 14918 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14919 << MemberDecl->getDeclName() 14920 << SourceRange(BuiltinLoc, RParenLoc); 14921 return ExprError(); 14922 } 14923 14924 CXXBasePath &Path = Paths.front(); 14925 for (const CXXBasePathElement &B : Path) 14926 Comps.push_back(OffsetOfNode(B.Base)); 14927 } 14928 14929 if (IndirectMemberDecl) { 14930 for (auto *FI : IndirectMemberDecl->chain()) { 14931 assert(isa<FieldDecl>(FI)); 14932 Comps.push_back(OffsetOfNode(OC.LocStart, 14933 cast<FieldDecl>(FI), OC.LocEnd)); 14934 } 14935 } else 14936 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14937 14938 CurrentType = MemberDecl->getType().getNonReferenceType(); 14939 } 14940 14941 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14942 Comps, Exprs, RParenLoc); 14943 } 14944 14945 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14946 SourceLocation BuiltinLoc, 14947 SourceLocation TypeLoc, 14948 ParsedType ParsedArgTy, 14949 ArrayRef<OffsetOfComponent> Components, 14950 SourceLocation RParenLoc) { 14951 14952 TypeSourceInfo *ArgTInfo; 14953 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14954 if (ArgTy.isNull()) 14955 return ExprError(); 14956 14957 if (!ArgTInfo) 14958 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14959 14960 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14961 } 14962 14963 14964 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14965 Expr *CondExpr, 14966 Expr *LHSExpr, Expr *RHSExpr, 14967 SourceLocation RPLoc) { 14968 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14969 14970 ExprValueKind VK = VK_RValue; 14971 ExprObjectKind OK = OK_Ordinary; 14972 QualType resType; 14973 bool CondIsTrue = false; 14974 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14975 resType = Context.DependentTy; 14976 } else { 14977 // The conditional expression is required to be a constant expression. 14978 llvm::APSInt condEval(32); 14979 ExprResult CondICE 14980 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14981 diag::err_typecheck_choose_expr_requires_constant, false); 14982 if (CondICE.isInvalid()) 14983 return ExprError(); 14984 CondExpr = CondICE.get(); 14985 CondIsTrue = condEval.getZExtValue(); 14986 14987 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14988 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14989 14990 resType = ActiveExpr->getType(); 14991 VK = ActiveExpr->getValueKind(); 14992 OK = ActiveExpr->getObjectKind(); 14993 } 14994 14995 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14996 resType, VK, OK, RPLoc, CondIsTrue); 14997 } 14998 14999 //===----------------------------------------------------------------------===// 15000 // Clang Extensions. 15001 //===----------------------------------------------------------------------===// 15002 15003 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15004 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15005 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15006 15007 if (LangOpts.CPlusPlus) { 15008 MangleNumberingContext *MCtx; 15009 Decl *ManglingContextDecl; 15010 std::tie(MCtx, ManglingContextDecl) = 15011 getCurrentMangleNumberContext(Block->getDeclContext()); 15012 if (MCtx) { 15013 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15014 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15015 } 15016 } 15017 15018 PushBlockScope(CurScope, Block); 15019 CurContext->addDecl(Block); 15020 if (CurScope) 15021 PushDeclContext(CurScope, Block); 15022 else 15023 CurContext = Block; 15024 15025 getCurBlock()->HasImplicitReturnType = true; 15026 15027 // Enter a new evaluation context to insulate the block from any 15028 // cleanups from the enclosing full-expression. 15029 PushExpressionEvaluationContext( 15030 ExpressionEvaluationContext::PotentiallyEvaluated); 15031 } 15032 15033 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15034 Scope *CurScope) { 15035 assert(ParamInfo.getIdentifier() == nullptr && 15036 "block-id should have no identifier!"); 15037 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 15038 BlockScopeInfo *CurBlock = getCurBlock(); 15039 15040 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15041 QualType T = Sig->getType(); 15042 15043 // FIXME: We should allow unexpanded parameter packs here, but that would, 15044 // in turn, make the block expression contain unexpanded parameter packs. 15045 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15046 // Drop the parameters. 15047 FunctionProtoType::ExtProtoInfo EPI; 15048 EPI.HasTrailingReturn = false; 15049 EPI.TypeQuals.addConst(); 15050 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15051 Sig = Context.getTrivialTypeSourceInfo(T); 15052 } 15053 15054 // GetTypeForDeclarator always produces a function type for a block 15055 // literal signature. Furthermore, it is always a FunctionProtoType 15056 // unless the function was written with a typedef. 15057 assert(T->isFunctionType() && 15058 "GetTypeForDeclarator made a non-function block signature"); 15059 15060 // Look for an explicit signature in that function type. 15061 FunctionProtoTypeLoc ExplicitSignature; 15062 15063 if ((ExplicitSignature = Sig->getTypeLoc() 15064 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15065 15066 // Check whether that explicit signature was synthesized by 15067 // GetTypeForDeclarator. If so, don't save that as part of the 15068 // written signature. 15069 if (ExplicitSignature.getLocalRangeBegin() == 15070 ExplicitSignature.getLocalRangeEnd()) { 15071 // This would be much cheaper if we stored TypeLocs instead of 15072 // TypeSourceInfos. 15073 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15074 unsigned Size = Result.getFullDataSize(); 15075 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15076 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15077 15078 ExplicitSignature = FunctionProtoTypeLoc(); 15079 } 15080 } 15081 15082 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15083 CurBlock->FunctionType = T; 15084 15085 const FunctionType *Fn = T->getAs<FunctionType>(); 15086 QualType RetTy = Fn->getReturnType(); 15087 bool isVariadic = 15088 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15089 15090 CurBlock->TheDecl->setIsVariadic(isVariadic); 15091 15092 // Context.DependentTy is used as a placeholder for a missing block 15093 // return type. TODO: what should we do with declarators like: 15094 // ^ * { ... } 15095 // If the answer is "apply template argument deduction".... 15096 if (RetTy != Context.DependentTy) { 15097 CurBlock->ReturnType = RetTy; 15098 CurBlock->TheDecl->setBlockMissingReturnType(false); 15099 CurBlock->HasImplicitReturnType = false; 15100 } 15101 15102 // Push block parameters from the declarator if we had them. 15103 SmallVector<ParmVarDecl*, 8> Params; 15104 if (ExplicitSignature) { 15105 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15106 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15107 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15108 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15109 // Diagnose this as an extension in C17 and earlier. 15110 if (!getLangOpts().C2x) 15111 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15112 } 15113 Params.push_back(Param); 15114 } 15115 15116 // Fake up parameter variables if we have a typedef, like 15117 // ^ fntype { ... } 15118 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15119 for (const auto &I : Fn->param_types()) { 15120 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15121 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15122 Params.push_back(Param); 15123 } 15124 } 15125 15126 // Set the parameters on the block decl. 15127 if (!Params.empty()) { 15128 CurBlock->TheDecl->setParams(Params); 15129 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15130 /*CheckParameterNames=*/false); 15131 } 15132 15133 // Finally we can process decl attributes. 15134 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15135 15136 // Put the parameter variables in scope. 15137 for (auto AI : CurBlock->TheDecl->parameters()) { 15138 AI->setOwningFunction(CurBlock->TheDecl); 15139 15140 // If this has an identifier, add it to the scope stack. 15141 if (AI->getIdentifier()) { 15142 CheckShadow(CurBlock->TheScope, AI); 15143 15144 PushOnScopeChains(AI, CurBlock->TheScope); 15145 } 15146 } 15147 } 15148 15149 /// ActOnBlockError - If there is an error parsing a block, this callback 15150 /// is invoked to pop the information about the block from the action impl. 15151 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15152 // Leave the expression-evaluation context. 15153 DiscardCleanupsInEvaluationContext(); 15154 PopExpressionEvaluationContext(); 15155 15156 // Pop off CurBlock, handle nested blocks. 15157 PopDeclContext(); 15158 PopFunctionScopeInfo(); 15159 } 15160 15161 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15162 /// literal was successfully completed. ^(int x){...} 15163 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15164 Stmt *Body, Scope *CurScope) { 15165 // If blocks are disabled, emit an error. 15166 if (!LangOpts.Blocks) 15167 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15168 15169 // Leave the expression-evaluation context. 15170 if (hasAnyUnrecoverableErrorsInThisFunction()) 15171 DiscardCleanupsInEvaluationContext(); 15172 assert(!Cleanup.exprNeedsCleanups() && 15173 "cleanups within block not correctly bound!"); 15174 PopExpressionEvaluationContext(); 15175 15176 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15177 BlockDecl *BD = BSI->TheDecl; 15178 15179 if (BSI->HasImplicitReturnType) 15180 deduceClosureReturnType(*BSI); 15181 15182 QualType RetTy = Context.VoidTy; 15183 if (!BSI->ReturnType.isNull()) 15184 RetTy = BSI->ReturnType; 15185 15186 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15187 QualType BlockTy; 15188 15189 // If the user wrote a function type in some form, try to use that. 15190 if (!BSI->FunctionType.isNull()) { 15191 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15192 15193 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15194 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15195 15196 // Turn protoless block types into nullary block types. 15197 if (isa<FunctionNoProtoType>(FTy)) { 15198 FunctionProtoType::ExtProtoInfo EPI; 15199 EPI.ExtInfo = Ext; 15200 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15201 15202 // Otherwise, if we don't need to change anything about the function type, 15203 // preserve its sugar structure. 15204 } else if (FTy->getReturnType() == RetTy && 15205 (!NoReturn || FTy->getNoReturnAttr())) { 15206 BlockTy = BSI->FunctionType; 15207 15208 // Otherwise, make the minimal modifications to the function type. 15209 } else { 15210 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15211 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15212 EPI.TypeQuals = Qualifiers(); 15213 EPI.ExtInfo = Ext; 15214 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15215 } 15216 15217 // If we don't have a function type, just build one from nothing. 15218 } else { 15219 FunctionProtoType::ExtProtoInfo EPI; 15220 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15221 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15222 } 15223 15224 DiagnoseUnusedParameters(BD->parameters()); 15225 BlockTy = Context.getBlockPointerType(BlockTy); 15226 15227 // If needed, diagnose invalid gotos and switches in the block. 15228 if (getCurFunction()->NeedsScopeChecking() && 15229 !PP.isCodeCompletionEnabled()) 15230 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15231 15232 BD->setBody(cast<CompoundStmt>(Body)); 15233 15234 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15235 DiagnoseUnguardedAvailabilityViolations(BD); 15236 15237 // Try to apply the named return value optimization. We have to check again 15238 // if we can do this, though, because blocks keep return statements around 15239 // to deduce an implicit return type. 15240 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15241 !BD->isDependentContext()) 15242 computeNRVO(Body, BSI); 15243 15244 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15245 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15246 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15247 NTCUK_Destruct|NTCUK_Copy); 15248 15249 PopDeclContext(); 15250 15251 // Pop the block scope now but keep it alive to the end of this function. 15252 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15253 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15254 15255 // Set the captured variables on the block. 15256 SmallVector<BlockDecl::Capture, 4> Captures; 15257 for (Capture &Cap : BSI->Captures) { 15258 if (Cap.isInvalid() || Cap.isThisCapture()) 15259 continue; 15260 15261 VarDecl *Var = Cap.getVariable(); 15262 Expr *CopyExpr = nullptr; 15263 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15264 if (const RecordType *Record = 15265 Cap.getCaptureType()->getAs<RecordType>()) { 15266 // The capture logic needs the destructor, so make sure we mark it. 15267 // Usually this is unnecessary because most local variables have 15268 // their destructors marked at declaration time, but parameters are 15269 // an exception because it's technically only the call site that 15270 // actually requires the destructor. 15271 if (isa<ParmVarDecl>(Var)) 15272 FinalizeVarWithDestructor(Var, Record); 15273 15274 // Enter a separate potentially-evaluated context while building block 15275 // initializers to isolate their cleanups from those of the block 15276 // itself. 15277 // FIXME: Is this appropriate even when the block itself occurs in an 15278 // unevaluated operand? 15279 EnterExpressionEvaluationContext EvalContext( 15280 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15281 15282 SourceLocation Loc = Cap.getLocation(); 15283 15284 ExprResult Result = BuildDeclarationNameExpr( 15285 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15286 15287 // According to the blocks spec, the capture of a variable from 15288 // the stack requires a const copy constructor. This is not true 15289 // of the copy/move done to move a __block variable to the heap. 15290 if (!Result.isInvalid() && 15291 !Result.get()->getType().isConstQualified()) { 15292 Result = ImpCastExprToType(Result.get(), 15293 Result.get()->getType().withConst(), 15294 CK_NoOp, VK_LValue); 15295 } 15296 15297 if (!Result.isInvalid()) { 15298 Result = PerformCopyInitialization( 15299 InitializedEntity::InitializeBlock(Var->getLocation(), 15300 Cap.getCaptureType(), false), 15301 Loc, Result.get()); 15302 } 15303 15304 // Build a full-expression copy expression if initialization 15305 // succeeded and used a non-trivial constructor. Recover from 15306 // errors by pretending that the copy isn't necessary. 15307 if (!Result.isInvalid() && 15308 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15309 ->isTrivial()) { 15310 Result = MaybeCreateExprWithCleanups(Result); 15311 CopyExpr = Result.get(); 15312 } 15313 } 15314 } 15315 15316 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15317 CopyExpr); 15318 Captures.push_back(NewCap); 15319 } 15320 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15321 15322 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15323 15324 // If the block isn't obviously global, i.e. it captures anything at 15325 // all, then we need to do a few things in the surrounding context: 15326 if (Result->getBlockDecl()->hasCaptures()) { 15327 // First, this expression has a new cleanup object. 15328 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15329 Cleanup.setExprNeedsCleanups(true); 15330 15331 // It also gets a branch-protected scope if any of the captured 15332 // variables needs destruction. 15333 for (const auto &CI : Result->getBlockDecl()->captures()) { 15334 const VarDecl *var = CI.getVariable(); 15335 if (var->getType().isDestructedType() != QualType::DK_none) { 15336 setFunctionHasBranchProtectedScope(); 15337 break; 15338 } 15339 } 15340 } 15341 15342 if (getCurFunction()) 15343 getCurFunction()->addBlock(BD); 15344 15345 return Result; 15346 } 15347 15348 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15349 SourceLocation RPLoc) { 15350 TypeSourceInfo *TInfo; 15351 GetTypeFromParser(Ty, &TInfo); 15352 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15353 } 15354 15355 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15356 Expr *E, TypeSourceInfo *TInfo, 15357 SourceLocation RPLoc) { 15358 Expr *OrigExpr = E; 15359 bool IsMS = false; 15360 15361 // CUDA device code does not support varargs. 15362 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15363 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15364 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15365 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15366 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15367 } 15368 } 15369 15370 // NVPTX does not support va_arg expression. 15371 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15372 Context.getTargetInfo().getTriple().isNVPTX()) 15373 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15374 15375 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15376 // as Microsoft ABI on an actual Microsoft platform, where 15377 // __builtin_ms_va_list and __builtin_va_list are the same.) 15378 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15379 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15380 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15381 if (Context.hasSameType(MSVaListType, E->getType())) { 15382 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15383 return ExprError(); 15384 IsMS = true; 15385 } 15386 } 15387 15388 // Get the va_list type 15389 QualType VaListType = Context.getBuiltinVaListType(); 15390 if (!IsMS) { 15391 if (VaListType->isArrayType()) { 15392 // Deal with implicit array decay; for example, on x86-64, 15393 // va_list is an array, but it's supposed to decay to 15394 // a pointer for va_arg. 15395 VaListType = Context.getArrayDecayedType(VaListType); 15396 // Make sure the input expression also decays appropriately. 15397 ExprResult Result = UsualUnaryConversions(E); 15398 if (Result.isInvalid()) 15399 return ExprError(); 15400 E = Result.get(); 15401 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15402 // If va_list is a record type and we are compiling in C++ mode, 15403 // check the argument using reference binding. 15404 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15405 Context, Context.getLValueReferenceType(VaListType), false); 15406 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15407 if (Init.isInvalid()) 15408 return ExprError(); 15409 E = Init.getAs<Expr>(); 15410 } else { 15411 // Otherwise, the va_list argument must be an l-value because 15412 // it is modified by va_arg. 15413 if (!E->isTypeDependent() && 15414 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15415 return ExprError(); 15416 } 15417 } 15418 15419 if (!IsMS && !E->isTypeDependent() && 15420 !Context.hasSameType(VaListType, E->getType())) 15421 return ExprError( 15422 Diag(E->getBeginLoc(), 15423 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15424 << OrigExpr->getType() << E->getSourceRange()); 15425 15426 if (!TInfo->getType()->isDependentType()) { 15427 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15428 diag::err_second_parameter_to_va_arg_incomplete, 15429 TInfo->getTypeLoc())) 15430 return ExprError(); 15431 15432 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15433 TInfo->getType(), 15434 diag::err_second_parameter_to_va_arg_abstract, 15435 TInfo->getTypeLoc())) 15436 return ExprError(); 15437 15438 if (!TInfo->getType().isPODType(Context)) { 15439 Diag(TInfo->getTypeLoc().getBeginLoc(), 15440 TInfo->getType()->isObjCLifetimeType() 15441 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15442 : diag::warn_second_parameter_to_va_arg_not_pod) 15443 << TInfo->getType() 15444 << TInfo->getTypeLoc().getSourceRange(); 15445 } 15446 15447 // Check for va_arg where arguments of the given type will be promoted 15448 // (i.e. this va_arg is guaranteed to have undefined behavior). 15449 QualType PromoteType; 15450 if (TInfo->getType()->isPromotableIntegerType()) { 15451 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15452 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15453 PromoteType = QualType(); 15454 } 15455 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15456 PromoteType = Context.DoubleTy; 15457 if (!PromoteType.isNull()) 15458 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15459 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15460 << TInfo->getType() 15461 << PromoteType 15462 << TInfo->getTypeLoc().getSourceRange()); 15463 } 15464 15465 QualType T = TInfo->getType().getNonLValueExprType(Context); 15466 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15467 } 15468 15469 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15470 // The type of __null will be int or long, depending on the size of 15471 // pointers on the target. 15472 QualType Ty; 15473 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15474 if (pw == Context.getTargetInfo().getIntWidth()) 15475 Ty = Context.IntTy; 15476 else if (pw == Context.getTargetInfo().getLongWidth()) 15477 Ty = Context.LongTy; 15478 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15479 Ty = Context.LongLongTy; 15480 else { 15481 llvm_unreachable("I don't know size of pointer!"); 15482 } 15483 15484 return new (Context) GNUNullExpr(Ty, TokenLoc); 15485 } 15486 15487 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15488 SourceLocation BuiltinLoc, 15489 SourceLocation RPLoc) { 15490 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15491 } 15492 15493 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15494 SourceLocation BuiltinLoc, 15495 SourceLocation RPLoc, 15496 DeclContext *ParentContext) { 15497 return new (Context) 15498 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15499 } 15500 15501 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15502 bool Diagnose) { 15503 if (!getLangOpts().ObjC) 15504 return false; 15505 15506 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15507 if (!PT) 15508 return false; 15509 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15510 15511 // Ignore any parens, implicit casts (should only be 15512 // array-to-pointer decays), and not-so-opaque values. The last is 15513 // important for making this trigger for property assignments. 15514 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15515 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15516 if (OV->getSourceExpr()) 15517 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15518 15519 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15520 if (!PT->isObjCIdType() && 15521 !(ID && ID->getIdentifier()->isStr("NSString"))) 15522 return false; 15523 if (!SL->isAscii()) 15524 return false; 15525 15526 if (Diagnose) { 15527 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15528 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15529 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15530 } 15531 return true; 15532 } 15533 15534 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15535 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15536 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15537 !SrcExpr->isNullPointerConstant( 15538 getASTContext(), Expr::NPC_NeverValueDependent)) { 15539 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15540 return false; 15541 if (Diagnose) { 15542 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15543 << /*number*/1 15544 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15545 Expr *NumLit = 15546 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15547 if (NumLit) 15548 Exp = NumLit; 15549 } 15550 return true; 15551 } 15552 15553 return false; 15554 } 15555 15556 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15557 const Expr *SrcExpr) { 15558 if (!DstType->isFunctionPointerType() || 15559 !SrcExpr->getType()->isFunctionType()) 15560 return false; 15561 15562 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15563 if (!DRE) 15564 return false; 15565 15566 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15567 if (!FD) 15568 return false; 15569 15570 return !S.checkAddressOfFunctionIsAvailable(FD, 15571 /*Complain=*/true, 15572 SrcExpr->getBeginLoc()); 15573 } 15574 15575 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15576 SourceLocation Loc, 15577 QualType DstType, QualType SrcType, 15578 Expr *SrcExpr, AssignmentAction Action, 15579 bool *Complained) { 15580 if (Complained) 15581 *Complained = false; 15582 15583 // Decode the result (notice that AST's are still created for extensions). 15584 bool CheckInferredResultType = false; 15585 bool isInvalid = false; 15586 unsigned DiagKind = 0; 15587 ConversionFixItGenerator ConvHints; 15588 bool MayHaveConvFixit = false; 15589 bool MayHaveFunctionDiff = false; 15590 const ObjCInterfaceDecl *IFace = nullptr; 15591 const ObjCProtocolDecl *PDecl = nullptr; 15592 15593 switch (ConvTy) { 15594 case Compatible: 15595 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15596 return false; 15597 15598 case PointerToInt: 15599 if (getLangOpts().CPlusPlus) { 15600 DiagKind = diag::err_typecheck_convert_pointer_int; 15601 isInvalid = true; 15602 } else { 15603 DiagKind = diag::ext_typecheck_convert_pointer_int; 15604 } 15605 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15606 MayHaveConvFixit = true; 15607 break; 15608 case IntToPointer: 15609 if (getLangOpts().CPlusPlus) { 15610 DiagKind = diag::err_typecheck_convert_int_pointer; 15611 isInvalid = true; 15612 } else { 15613 DiagKind = diag::ext_typecheck_convert_int_pointer; 15614 } 15615 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15616 MayHaveConvFixit = true; 15617 break; 15618 case IncompatibleFunctionPointer: 15619 if (getLangOpts().CPlusPlus) { 15620 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15621 isInvalid = true; 15622 } else { 15623 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15624 } 15625 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15626 MayHaveConvFixit = true; 15627 break; 15628 case IncompatiblePointer: 15629 if (Action == AA_Passing_CFAudited) { 15630 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15631 } else if (getLangOpts().CPlusPlus) { 15632 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15633 isInvalid = true; 15634 } else { 15635 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15636 } 15637 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15638 SrcType->isObjCObjectPointerType(); 15639 if (!CheckInferredResultType) { 15640 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15641 } else if (CheckInferredResultType) { 15642 SrcType = SrcType.getUnqualifiedType(); 15643 DstType = DstType.getUnqualifiedType(); 15644 } 15645 MayHaveConvFixit = true; 15646 break; 15647 case IncompatiblePointerSign: 15648 if (getLangOpts().CPlusPlus) { 15649 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15650 isInvalid = true; 15651 } else { 15652 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15653 } 15654 break; 15655 case FunctionVoidPointer: 15656 if (getLangOpts().CPlusPlus) { 15657 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15658 isInvalid = true; 15659 } else { 15660 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15661 } 15662 break; 15663 case IncompatiblePointerDiscardsQualifiers: { 15664 // Perform array-to-pointer decay if necessary. 15665 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15666 15667 isInvalid = true; 15668 15669 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15670 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15671 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15672 DiagKind = diag::err_typecheck_incompatible_address_space; 15673 break; 15674 15675 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15676 DiagKind = diag::err_typecheck_incompatible_ownership; 15677 break; 15678 } 15679 15680 llvm_unreachable("unknown error case for discarding qualifiers!"); 15681 // fallthrough 15682 } 15683 case CompatiblePointerDiscardsQualifiers: 15684 // If the qualifiers lost were because we were applying the 15685 // (deprecated) C++ conversion from a string literal to a char* 15686 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15687 // Ideally, this check would be performed in 15688 // checkPointerTypesForAssignment. However, that would require a 15689 // bit of refactoring (so that the second argument is an 15690 // expression, rather than a type), which should be done as part 15691 // of a larger effort to fix checkPointerTypesForAssignment for 15692 // C++ semantics. 15693 if (getLangOpts().CPlusPlus && 15694 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15695 return false; 15696 if (getLangOpts().CPlusPlus) { 15697 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15698 isInvalid = true; 15699 } else { 15700 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15701 } 15702 15703 break; 15704 case IncompatibleNestedPointerQualifiers: 15705 if (getLangOpts().CPlusPlus) { 15706 isInvalid = true; 15707 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15708 } else { 15709 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15710 } 15711 break; 15712 case IncompatibleNestedPointerAddressSpaceMismatch: 15713 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15714 isInvalid = true; 15715 break; 15716 case IntToBlockPointer: 15717 DiagKind = diag::err_int_to_block_pointer; 15718 isInvalid = true; 15719 break; 15720 case IncompatibleBlockPointer: 15721 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15722 isInvalid = true; 15723 break; 15724 case IncompatibleObjCQualifiedId: { 15725 if (SrcType->isObjCQualifiedIdType()) { 15726 const ObjCObjectPointerType *srcOPT = 15727 SrcType->castAs<ObjCObjectPointerType>(); 15728 for (auto *srcProto : srcOPT->quals()) { 15729 PDecl = srcProto; 15730 break; 15731 } 15732 if (const ObjCInterfaceType *IFaceT = 15733 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15734 IFace = IFaceT->getDecl(); 15735 } 15736 else if (DstType->isObjCQualifiedIdType()) { 15737 const ObjCObjectPointerType *dstOPT = 15738 DstType->castAs<ObjCObjectPointerType>(); 15739 for (auto *dstProto : dstOPT->quals()) { 15740 PDecl = dstProto; 15741 break; 15742 } 15743 if (const ObjCInterfaceType *IFaceT = 15744 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15745 IFace = IFaceT->getDecl(); 15746 } 15747 if (getLangOpts().CPlusPlus) { 15748 DiagKind = diag::err_incompatible_qualified_id; 15749 isInvalid = true; 15750 } else { 15751 DiagKind = diag::warn_incompatible_qualified_id; 15752 } 15753 break; 15754 } 15755 case IncompatibleVectors: 15756 if (getLangOpts().CPlusPlus) { 15757 DiagKind = diag::err_incompatible_vectors; 15758 isInvalid = true; 15759 } else { 15760 DiagKind = diag::warn_incompatible_vectors; 15761 } 15762 break; 15763 case IncompatibleObjCWeakRef: 15764 DiagKind = diag::err_arc_weak_unavailable_assign; 15765 isInvalid = true; 15766 break; 15767 case Incompatible: 15768 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15769 if (Complained) 15770 *Complained = true; 15771 return true; 15772 } 15773 15774 DiagKind = diag::err_typecheck_convert_incompatible; 15775 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15776 MayHaveConvFixit = true; 15777 isInvalid = true; 15778 MayHaveFunctionDiff = true; 15779 break; 15780 } 15781 15782 QualType FirstType, SecondType; 15783 switch (Action) { 15784 case AA_Assigning: 15785 case AA_Initializing: 15786 // The destination type comes first. 15787 FirstType = DstType; 15788 SecondType = SrcType; 15789 break; 15790 15791 case AA_Returning: 15792 case AA_Passing: 15793 case AA_Passing_CFAudited: 15794 case AA_Converting: 15795 case AA_Sending: 15796 case AA_Casting: 15797 // The source type comes first. 15798 FirstType = SrcType; 15799 SecondType = DstType; 15800 break; 15801 } 15802 15803 PartialDiagnostic FDiag = PDiag(DiagKind); 15804 if (Action == AA_Passing_CFAudited) 15805 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15806 else 15807 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15808 15809 // If we can fix the conversion, suggest the FixIts. 15810 if (!ConvHints.isNull()) { 15811 for (FixItHint &H : ConvHints.Hints) 15812 FDiag << H; 15813 } 15814 15815 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15816 15817 if (MayHaveFunctionDiff) 15818 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15819 15820 Diag(Loc, FDiag); 15821 if ((DiagKind == diag::warn_incompatible_qualified_id || 15822 DiagKind == diag::err_incompatible_qualified_id) && 15823 PDecl && IFace && !IFace->hasDefinition()) 15824 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15825 << IFace << PDecl; 15826 15827 if (SecondType == Context.OverloadTy) 15828 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15829 FirstType, /*TakingAddress=*/true); 15830 15831 if (CheckInferredResultType) 15832 EmitRelatedResultTypeNote(SrcExpr); 15833 15834 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15835 EmitRelatedResultTypeNoteForReturn(DstType); 15836 15837 if (Complained) 15838 *Complained = true; 15839 return isInvalid; 15840 } 15841 15842 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15843 llvm::APSInt *Result) { 15844 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15845 public: 15846 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 15847 QualType T) override { 15848 return S.Diag(Loc, diag::err_ice_not_integral) 15849 << T << S.LangOpts.CPlusPlus; 15850 } 15851 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 15852 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 15853 } 15854 } Diagnoser; 15855 15856 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15857 } 15858 15859 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15860 llvm::APSInt *Result, 15861 unsigned DiagID, 15862 bool AllowFold) { 15863 class IDDiagnoser : public VerifyICEDiagnoser { 15864 unsigned DiagID; 15865 15866 public: 15867 IDDiagnoser(unsigned DiagID) 15868 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15869 15870 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 15871 return S.Diag(Loc, DiagID); 15872 } 15873 } Diagnoser(DiagID); 15874 15875 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15876 } 15877 15878 Sema::SemaDiagnosticBuilder 15879 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 15880 QualType T) { 15881 return diagnoseNotICE(S, Loc); 15882 } 15883 15884 Sema::SemaDiagnosticBuilder 15885 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 15886 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 15887 } 15888 15889 ExprResult 15890 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15891 VerifyICEDiagnoser &Diagnoser, 15892 bool AllowFold) { 15893 SourceLocation DiagLoc = E->getBeginLoc(); 15894 15895 if (getLangOpts().CPlusPlus11) { 15896 // C++11 [expr.const]p5: 15897 // If an expression of literal class type is used in a context where an 15898 // integral constant expression is required, then that class type shall 15899 // have a single non-explicit conversion function to an integral or 15900 // unscoped enumeration type 15901 ExprResult Converted; 15902 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15903 VerifyICEDiagnoser &BaseDiagnoser; 15904 public: 15905 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 15906 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 15907 BaseDiagnoser.Suppress, true), 15908 BaseDiagnoser(BaseDiagnoser) {} 15909 15910 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15911 QualType T) override { 15912 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 15913 } 15914 15915 SemaDiagnosticBuilder diagnoseIncomplete( 15916 Sema &S, SourceLocation Loc, QualType T) override { 15917 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15918 } 15919 15920 SemaDiagnosticBuilder diagnoseExplicitConv( 15921 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15922 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15923 } 15924 15925 SemaDiagnosticBuilder noteExplicitConv( 15926 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15927 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15928 << ConvTy->isEnumeralType() << ConvTy; 15929 } 15930 15931 SemaDiagnosticBuilder diagnoseAmbiguous( 15932 Sema &S, SourceLocation Loc, QualType T) override { 15933 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15934 } 15935 15936 SemaDiagnosticBuilder noteAmbiguous( 15937 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15938 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15939 << ConvTy->isEnumeralType() << ConvTy; 15940 } 15941 15942 SemaDiagnosticBuilder diagnoseConversion( 15943 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15944 llvm_unreachable("conversion functions are permitted"); 15945 } 15946 } ConvertDiagnoser(Diagnoser); 15947 15948 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15949 ConvertDiagnoser); 15950 if (Converted.isInvalid()) 15951 return Converted; 15952 E = Converted.get(); 15953 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15954 return ExprError(); 15955 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15956 // An ICE must be of integral or unscoped enumeration type. 15957 if (!Diagnoser.Suppress) 15958 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 15959 << E->getSourceRange(); 15960 return ExprError(); 15961 } 15962 15963 ExprResult RValueExpr = DefaultLvalueConversion(E); 15964 if (RValueExpr.isInvalid()) 15965 return ExprError(); 15966 15967 E = RValueExpr.get(); 15968 15969 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15970 // in the non-ICE case. 15971 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15972 if (Result) 15973 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15974 if (!isa<ConstantExpr>(E)) 15975 E = ConstantExpr::Create(Context, E); 15976 return E; 15977 } 15978 15979 Expr::EvalResult EvalResult; 15980 SmallVector<PartialDiagnosticAt, 8> Notes; 15981 EvalResult.Diag = &Notes; 15982 15983 // Try to evaluate the expression, and produce diagnostics explaining why it's 15984 // not a constant expression as a side-effect. 15985 bool Folded = 15986 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15987 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15988 15989 if (!isa<ConstantExpr>(E)) 15990 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15991 15992 // In C++11, we can rely on diagnostics being produced for any expression 15993 // which is not a constant expression. If no diagnostics were produced, then 15994 // this is a constant expression. 15995 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15996 if (Result) 15997 *Result = EvalResult.Val.getInt(); 15998 return E; 15999 } 16000 16001 // If our only note is the usual "invalid subexpression" note, just point 16002 // the caret at its location rather than producing an essentially 16003 // redundant note. 16004 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16005 diag::note_invalid_subexpr_in_const_expr) { 16006 DiagLoc = Notes[0].first; 16007 Notes.clear(); 16008 } 16009 16010 if (!Folded || !AllowFold) { 16011 if (!Diagnoser.Suppress) { 16012 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16013 for (const PartialDiagnosticAt &Note : Notes) 16014 Diag(Note.first, Note.second); 16015 } 16016 16017 return ExprError(); 16018 } 16019 16020 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16021 for (const PartialDiagnosticAt &Note : Notes) 16022 Diag(Note.first, Note.second); 16023 16024 if (Result) 16025 *Result = EvalResult.Val.getInt(); 16026 return E; 16027 } 16028 16029 namespace { 16030 // Handle the case where we conclude a expression which we speculatively 16031 // considered to be unevaluated is actually evaluated. 16032 class TransformToPE : public TreeTransform<TransformToPE> { 16033 typedef TreeTransform<TransformToPE> BaseTransform; 16034 16035 public: 16036 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16037 16038 // Make sure we redo semantic analysis 16039 bool AlwaysRebuild() { return true; } 16040 bool ReplacingOriginal() { return true; } 16041 16042 // We need to special-case DeclRefExprs referring to FieldDecls which 16043 // are not part of a member pointer formation; normal TreeTransforming 16044 // doesn't catch this case because of the way we represent them in the AST. 16045 // FIXME: This is a bit ugly; is it really the best way to handle this 16046 // case? 16047 // 16048 // Error on DeclRefExprs referring to FieldDecls. 16049 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16050 if (isa<FieldDecl>(E->getDecl()) && 16051 !SemaRef.isUnevaluatedContext()) 16052 return SemaRef.Diag(E->getLocation(), 16053 diag::err_invalid_non_static_member_use) 16054 << E->getDecl() << E->getSourceRange(); 16055 16056 return BaseTransform::TransformDeclRefExpr(E); 16057 } 16058 16059 // Exception: filter out member pointer formation 16060 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16061 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16062 return E; 16063 16064 return BaseTransform::TransformUnaryOperator(E); 16065 } 16066 16067 // The body of a lambda-expression is in a separate expression evaluation 16068 // context so never needs to be transformed. 16069 // FIXME: Ideally we wouldn't transform the closure type either, and would 16070 // just recreate the capture expressions and lambda expression. 16071 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16072 return SkipLambdaBody(E, Body); 16073 } 16074 }; 16075 } 16076 16077 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16078 assert(isUnevaluatedContext() && 16079 "Should only transform unevaluated expressions"); 16080 ExprEvalContexts.back().Context = 16081 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16082 if (isUnevaluatedContext()) 16083 return E; 16084 return TransformToPE(*this).TransformExpr(E); 16085 } 16086 16087 void 16088 Sema::PushExpressionEvaluationContext( 16089 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16090 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16091 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16092 LambdaContextDecl, ExprContext); 16093 Cleanup.reset(); 16094 if (!MaybeODRUseExprs.empty()) 16095 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16096 } 16097 16098 void 16099 Sema::PushExpressionEvaluationContext( 16100 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16101 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16102 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16103 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16104 } 16105 16106 namespace { 16107 16108 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16109 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16110 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16111 if (E->getOpcode() == UO_Deref) 16112 return CheckPossibleDeref(S, E->getSubExpr()); 16113 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16114 return CheckPossibleDeref(S, E->getBase()); 16115 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16116 return CheckPossibleDeref(S, E->getBase()); 16117 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16118 QualType Inner; 16119 QualType Ty = E->getType(); 16120 if (const auto *Ptr = Ty->getAs<PointerType>()) 16121 Inner = Ptr->getPointeeType(); 16122 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16123 Inner = Arr->getElementType(); 16124 else 16125 return nullptr; 16126 16127 if (Inner->hasAttr(attr::NoDeref)) 16128 return E; 16129 } 16130 return nullptr; 16131 } 16132 16133 } // namespace 16134 16135 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16136 for (const Expr *E : Rec.PossibleDerefs) { 16137 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16138 if (DeclRef) { 16139 const ValueDecl *Decl = DeclRef->getDecl(); 16140 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16141 << Decl->getName() << E->getSourceRange(); 16142 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16143 } else { 16144 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16145 << E->getSourceRange(); 16146 } 16147 } 16148 Rec.PossibleDerefs.clear(); 16149 } 16150 16151 /// Check whether E, which is either a discarded-value expression or an 16152 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16153 /// and if so, remove it from the list of volatile-qualified assignments that 16154 /// we are going to warn are deprecated. 16155 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16156 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16157 return; 16158 16159 // Note: ignoring parens here is not justified by the standard rules, but 16160 // ignoring parentheses seems like a more reasonable approach, and this only 16161 // drives a deprecation warning so doesn't affect conformance. 16162 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16163 if (BO->getOpcode() == BO_Assign) { 16164 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16165 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16166 LHSs.end()); 16167 } 16168 } 16169 } 16170 16171 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16172 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16173 RebuildingImmediateInvocation) 16174 return E; 16175 16176 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16177 /// It's OK if this fails; we'll also remove this in 16178 /// HandleImmediateInvocations, but catching it here allows us to avoid 16179 /// walking the AST looking for it in simple cases. 16180 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16181 if (auto *DeclRef = 16182 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16183 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16184 16185 E = MaybeCreateExprWithCleanups(E); 16186 16187 ConstantExpr *Res = ConstantExpr::Create( 16188 getASTContext(), E.get(), 16189 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16190 getASTContext()), 16191 /*IsImmediateInvocation*/ true); 16192 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16193 return Res; 16194 } 16195 16196 static void EvaluateAndDiagnoseImmediateInvocation( 16197 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16198 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16199 Expr::EvalResult Eval; 16200 Eval.Diag = &Notes; 16201 ConstantExpr *CE = Candidate.getPointer(); 16202 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 16203 SemaRef.getASTContext(), true); 16204 if (!Result || !Notes.empty()) { 16205 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16206 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16207 InnerExpr = FunctionalCast->getSubExpr(); 16208 FunctionDecl *FD = nullptr; 16209 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16210 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16211 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16212 FD = Call->getConstructor(); 16213 else 16214 llvm_unreachable("unhandled decl kind"); 16215 assert(FD->isConsteval()); 16216 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16217 for (auto &Note : Notes) 16218 SemaRef.Diag(Note.first, Note.second); 16219 return; 16220 } 16221 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16222 } 16223 16224 static void RemoveNestedImmediateInvocation( 16225 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16226 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16227 struct ComplexRemove : TreeTransform<ComplexRemove> { 16228 using Base = TreeTransform<ComplexRemove>; 16229 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16230 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16231 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16232 CurrentII; 16233 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16234 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16235 SmallVector<Sema::ImmediateInvocationCandidate, 16236 4>::reverse_iterator Current) 16237 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16238 void RemoveImmediateInvocation(ConstantExpr* E) { 16239 auto It = std::find_if(CurrentII, IISet.rend(), 16240 [E](Sema::ImmediateInvocationCandidate Elem) { 16241 return Elem.getPointer() == E; 16242 }); 16243 assert(It != IISet.rend() && 16244 "ConstantExpr marked IsImmediateInvocation should " 16245 "be present"); 16246 It->setInt(1); // Mark as deleted 16247 } 16248 ExprResult TransformConstantExpr(ConstantExpr *E) { 16249 if (!E->isImmediateInvocation()) 16250 return Base::TransformConstantExpr(E); 16251 RemoveImmediateInvocation(E); 16252 return Base::TransformExpr(E->getSubExpr()); 16253 } 16254 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16255 /// we need to remove its DeclRefExpr from the DRSet. 16256 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16257 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16258 return Base::TransformCXXOperatorCallExpr(E); 16259 } 16260 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16261 /// here. 16262 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16263 if (!Init) 16264 return Init; 16265 /// ConstantExpr are the first layer of implicit node to be removed so if 16266 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16267 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16268 if (CE->isImmediateInvocation()) 16269 RemoveImmediateInvocation(CE); 16270 return Base::TransformInitializer(Init, NotCopyInit); 16271 } 16272 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16273 DRSet.erase(E); 16274 return E; 16275 } 16276 bool AlwaysRebuild() { return false; } 16277 bool ReplacingOriginal() { return true; } 16278 bool AllowSkippingCXXConstructExpr() { 16279 bool Res = AllowSkippingFirstCXXConstructExpr; 16280 AllowSkippingFirstCXXConstructExpr = true; 16281 return Res; 16282 } 16283 bool AllowSkippingFirstCXXConstructExpr = true; 16284 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16285 Rec.ImmediateInvocationCandidates, It); 16286 16287 /// CXXConstructExpr with a single argument are getting skipped by 16288 /// TreeTransform in some situtation because they could be implicit. This 16289 /// can only occur for the top-level CXXConstructExpr because it is used 16290 /// nowhere in the expression being transformed therefore will not be rebuilt. 16291 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16292 /// skipping the first CXXConstructExpr. 16293 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16294 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16295 16296 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16297 assert(Res.isUsable()); 16298 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16299 It->getPointer()->setSubExpr(Res.get()); 16300 } 16301 16302 static void 16303 HandleImmediateInvocations(Sema &SemaRef, 16304 Sema::ExpressionEvaluationContextRecord &Rec) { 16305 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16306 Rec.ReferenceToConsteval.size() == 0) || 16307 SemaRef.RebuildingImmediateInvocation) 16308 return; 16309 16310 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16311 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16312 /// need to remove ReferenceToConsteval in the immediate invocation. 16313 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16314 16315 /// Prevent sema calls during the tree transform from adding pointers that 16316 /// are already in the sets. 16317 llvm::SaveAndRestore<bool> DisableIITracking( 16318 SemaRef.RebuildingImmediateInvocation, true); 16319 16320 /// Prevent diagnostic during tree transfrom as they are duplicates 16321 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16322 16323 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16324 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16325 if (!It->getInt()) 16326 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16327 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16328 Rec.ReferenceToConsteval.size()) { 16329 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16330 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16331 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16332 bool VisitDeclRefExpr(DeclRefExpr *E) { 16333 DRSet.erase(E); 16334 return DRSet.size(); 16335 } 16336 } Visitor(Rec.ReferenceToConsteval); 16337 Visitor.TraverseStmt( 16338 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16339 } 16340 for (auto CE : Rec.ImmediateInvocationCandidates) 16341 if (!CE.getInt()) 16342 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16343 for (auto DR : Rec.ReferenceToConsteval) { 16344 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16345 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16346 << FD; 16347 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16348 } 16349 } 16350 16351 void Sema::PopExpressionEvaluationContext() { 16352 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16353 unsigned NumTypos = Rec.NumTypos; 16354 16355 if (!Rec.Lambdas.empty()) { 16356 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16357 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16358 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16359 unsigned D; 16360 if (Rec.isUnevaluated()) { 16361 // C++11 [expr.prim.lambda]p2: 16362 // A lambda-expression shall not appear in an unevaluated operand 16363 // (Clause 5). 16364 D = diag::err_lambda_unevaluated_operand; 16365 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16366 // C++1y [expr.const]p2: 16367 // A conditional-expression e is a core constant expression unless the 16368 // evaluation of e, following the rules of the abstract machine, would 16369 // evaluate [...] a lambda-expression. 16370 D = diag::err_lambda_in_constant_expression; 16371 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16372 // C++17 [expr.prim.lamda]p2: 16373 // A lambda-expression shall not appear [...] in a template-argument. 16374 D = diag::err_lambda_in_invalid_context; 16375 } else 16376 llvm_unreachable("Couldn't infer lambda error message."); 16377 16378 for (const auto *L : Rec.Lambdas) 16379 Diag(L->getBeginLoc(), D); 16380 } 16381 } 16382 16383 WarnOnPendingNoDerefs(Rec); 16384 HandleImmediateInvocations(*this, Rec); 16385 16386 // Warn on any volatile-qualified simple-assignments that are not discarded- 16387 // value expressions nor unevaluated operands (those cases get removed from 16388 // this list by CheckUnusedVolatileAssignment). 16389 for (auto *BO : Rec.VolatileAssignmentLHSs) 16390 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16391 << BO->getType(); 16392 16393 // When are coming out of an unevaluated context, clear out any 16394 // temporaries that we may have created as part of the evaluation of 16395 // the expression in that context: they aren't relevant because they 16396 // will never be constructed. 16397 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16398 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16399 ExprCleanupObjects.end()); 16400 Cleanup = Rec.ParentCleanup; 16401 CleanupVarDeclMarking(); 16402 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16403 // Otherwise, merge the contexts together. 16404 } else { 16405 Cleanup.mergeFrom(Rec.ParentCleanup); 16406 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16407 Rec.SavedMaybeODRUseExprs.end()); 16408 } 16409 16410 // Pop the current expression evaluation context off the stack. 16411 ExprEvalContexts.pop_back(); 16412 16413 // The global expression evaluation context record is never popped. 16414 ExprEvalContexts.back().NumTypos += NumTypos; 16415 } 16416 16417 void Sema::DiscardCleanupsInEvaluationContext() { 16418 ExprCleanupObjects.erase( 16419 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16420 ExprCleanupObjects.end()); 16421 Cleanup.reset(); 16422 MaybeODRUseExprs.clear(); 16423 } 16424 16425 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16426 ExprResult Result = CheckPlaceholderExpr(E); 16427 if (Result.isInvalid()) 16428 return ExprError(); 16429 E = Result.get(); 16430 if (!E->getType()->isVariablyModifiedType()) 16431 return E; 16432 return TransformToPotentiallyEvaluated(E); 16433 } 16434 16435 /// Are we in a context that is potentially constant evaluated per C++20 16436 /// [expr.const]p12? 16437 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16438 /// C++2a [expr.const]p12: 16439 // An expression or conversion is potentially constant evaluated if it is 16440 switch (SemaRef.ExprEvalContexts.back().Context) { 16441 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16442 // -- a manifestly constant-evaluated expression, 16443 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16444 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16445 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16446 // -- a potentially-evaluated expression, 16447 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16448 // -- an immediate subexpression of a braced-init-list, 16449 16450 // -- [FIXME] an expression of the form & cast-expression that occurs 16451 // within a templated entity 16452 // -- a subexpression of one of the above that is not a subexpression of 16453 // a nested unevaluated operand. 16454 return true; 16455 16456 case Sema::ExpressionEvaluationContext::Unevaluated: 16457 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16458 // Expressions in this context are never evaluated. 16459 return false; 16460 } 16461 llvm_unreachable("Invalid context"); 16462 } 16463 16464 /// Return true if this function has a calling convention that requires mangling 16465 /// in the size of the parameter pack. 16466 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16467 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16468 // we don't need parameter type sizes. 16469 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16470 if (!TT.isOSWindows() || !TT.isX86()) 16471 return false; 16472 16473 // If this is C++ and this isn't an extern "C" function, parameters do not 16474 // need to be complete. In this case, C++ mangling will apply, which doesn't 16475 // use the size of the parameters. 16476 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16477 return false; 16478 16479 // Stdcall, fastcall, and vectorcall need this special treatment. 16480 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16481 switch (CC) { 16482 case CC_X86StdCall: 16483 case CC_X86FastCall: 16484 case CC_X86VectorCall: 16485 return true; 16486 default: 16487 break; 16488 } 16489 return false; 16490 } 16491 16492 /// Require that all of the parameter types of function be complete. Normally, 16493 /// parameter types are only required to be complete when a function is called 16494 /// or defined, but to mangle functions with certain calling conventions, the 16495 /// mangler needs to know the size of the parameter list. In this situation, 16496 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16497 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16498 /// result in a linker error. Clang doesn't implement this behavior, and instead 16499 /// attempts to error at compile time. 16500 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16501 SourceLocation Loc) { 16502 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16503 FunctionDecl *FD; 16504 ParmVarDecl *Param; 16505 16506 public: 16507 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16508 : FD(FD), Param(Param) {} 16509 16510 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16511 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16512 StringRef CCName; 16513 switch (CC) { 16514 case CC_X86StdCall: 16515 CCName = "stdcall"; 16516 break; 16517 case CC_X86FastCall: 16518 CCName = "fastcall"; 16519 break; 16520 case CC_X86VectorCall: 16521 CCName = "vectorcall"; 16522 break; 16523 default: 16524 llvm_unreachable("CC does not need mangling"); 16525 } 16526 16527 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16528 << Param->getDeclName() << FD->getDeclName() << CCName; 16529 } 16530 }; 16531 16532 for (ParmVarDecl *Param : FD->parameters()) { 16533 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16534 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16535 } 16536 } 16537 16538 namespace { 16539 enum class OdrUseContext { 16540 /// Declarations in this context are not odr-used. 16541 None, 16542 /// Declarations in this context are formally odr-used, but this is a 16543 /// dependent context. 16544 Dependent, 16545 /// Declarations in this context are odr-used but not actually used (yet). 16546 FormallyOdrUsed, 16547 /// Declarations in this context are used. 16548 Used 16549 }; 16550 } 16551 16552 /// Are we within a context in which references to resolved functions or to 16553 /// variables result in odr-use? 16554 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16555 OdrUseContext Result; 16556 16557 switch (SemaRef.ExprEvalContexts.back().Context) { 16558 case Sema::ExpressionEvaluationContext::Unevaluated: 16559 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16560 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16561 return OdrUseContext::None; 16562 16563 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16564 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16565 Result = OdrUseContext::Used; 16566 break; 16567 16568 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16569 Result = OdrUseContext::FormallyOdrUsed; 16570 break; 16571 16572 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16573 // A default argument formally results in odr-use, but doesn't actually 16574 // result in a use in any real sense until it itself is used. 16575 Result = OdrUseContext::FormallyOdrUsed; 16576 break; 16577 } 16578 16579 if (SemaRef.CurContext->isDependentContext()) 16580 return OdrUseContext::Dependent; 16581 16582 return Result; 16583 } 16584 16585 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16586 if (!Func->isConstexpr()) 16587 return false; 16588 16589 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16590 return true; 16591 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16592 return CCD && CCD->getInheritedConstructor(); 16593 } 16594 16595 /// Mark a function referenced, and check whether it is odr-used 16596 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16597 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16598 bool MightBeOdrUse) { 16599 assert(Func && "No function?"); 16600 16601 Func->setReferenced(); 16602 16603 // Recursive functions aren't really used until they're used from some other 16604 // context. 16605 bool IsRecursiveCall = CurContext == Func; 16606 16607 // C++11 [basic.def.odr]p3: 16608 // A function whose name appears as a potentially-evaluated expression is 16609 // odr-used if it is the unique lookup result or the selected member of a 16610 // set of overloaded functions [...]. 16611 // 16612 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16613 // can just check that here. 16614 OdrUseContext OdrUse = 16615 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16616 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16617 OdrUse = OdrUseContext::FormallyOdrUsed; 16618 16619 // Trivial default constructors and destructors are never actually used. 16620 // FIXME: What about other special members? 16621 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16622 OdrUse == OdrUseContext::Used) { 16623 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16624 if (Constructor->isDefaultConstructor()) 16625 OdrUse = OdrUseContext::FormallyOdrUsed; 16626 if (isa<CXXDestructorDecl>(Func)) 16627 OdrUse = OdrUseContext::FormallyOdrUsed; 16628 } 16629 16630 // C++20 [expr.const]p12: 16631 // A function [...] is needed for constant evaluation if it is [...] a 16632 // constexpr function that is named by an expression that is potentially 16633 // constant evaluated 16634 bool NeededForConstantEvaluation = 16635 isPotentiallyConstantEvaluatedContext(*this) && 16636 isImplicitlyDefinableConstexprFunction(Func); 16637 16638 // Determine whether we require a function definition to exist, per 16639 // C++11 [temp.inst]p3: 16640 // Unless a function template specialization has been explicitly 16641 // instantiated or explicitly specialized, the function template 16642 // specialization is implicitly instantiated when the specialization is 16643 // referenced in a context that requires a function definition to exist. 16644 // C++20 [temp.inst]p7: 16645 // The existence of a definition of a [...] function is considered to 16646 // affect the semantics of the program if the [...] function is needed for 16647 // constant evaluation by an expression 16648 // C++20 [basic.def.odr]p10: 16649 // Every program shall contain exactly one definition of every non-inline 16650 // function or variable that is odr-used in that program outside of a 16651 // discarded statement 16652 // C++20 [special]p1: 16653 // The implementation will implicitly define [defaulted special members] 16654 // if they are odr-used or needed for constant evaluation. 16655 // 16656 // Note that we skip the implicit instantiation of templates that are only 16657 // used in unused default arguments or by recursive calls to themselves. 16658 // This is formally non-conforming, but seems reasonable in practice. 16659 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16660 NeededForConstantEvaluation); 16661 16662 // C++14 [temp.expl.spec]p6: 16663 // If a template [...] is explicitly specialized then that specialization 16664 // shall be declared before the first use of that specialization that would 16665 // cause an implicit instantiation to take place, in every translation unit 16666 // in which such a use occurs 16667 if (NeedDefinition && 16668 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16669 Func->getMemberSpecializationInfo())) 16670 checkSpecializationVisibility(Loc, Func); 16671 16672 if (getLangOpts().CUDA) 16673 CheckCUDACall(Loc, Func); 16674 16675 if (getLangOpts().SYCLIsDevice) 16676 checkSYCLDeviceFunction(Loc, Func); 16677 16678 // If we need a definition, try to create one. 16679 if (NeedDefinition && !Func->getBody()) { 16680 runWithSufficientStackSpace(Loc, [&] { 16681 if (CXXConstructorDecl *Constructor = 16682 dyn_cast<CXXConstructorDecl>(Func)) { 16683 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16684 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16685 if (Constructor->isDefaultConstructor()) { 16686 if (Constructor->isTrivial() && 16687 !Constructor->hasAttr<DLLExportAttr>()) 16688 return; 16689 DefineImplicitDefaultConstructor(Loc, Constructor); 16690 } else if (Constructor->isCopyConstructor()) { 16691 DefineImplicitCopyConstructor(Loc, Constructor); 16692 } else if (Constructor->isMoveConstructor()) { 16693 DefineImplicitMoveConstructor(Loc, Constructor); 16694 } 16695 } else if (Constructor->getInheritedConstructor()) { 16696 DefineInheritingConstructor(Loc, Constructor); 16697 } 16698 } else if (CXXDestructorDecl *Destructor = 16699 dyn_cast<CXXDestructorDecl>(Func)) { 16700 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16701 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16702 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16703 return; 16704 DefineImplicitDestructor(Loc, Destructor); 16705 } 16706 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16707 MarkVTableUsed(Loc, Destructor->getParent()); 16708 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16709 if (MethodDecl->isOverloadedOperator() && 16710 MethodDecl->getOverloadedOperator() == OO_Equal) { 16711 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16712 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16713 if (MethodDecl->isCopyAssignmentOperator()) 16714 DefineImplicitCopyAssignment(Loc, MethodDecl); 16715 else if (MethodDecl->isMoveAssignmentOperator()) 16716 DefineImplicitMoveAssignment(Loc, MethodDecl); 16717 } 16718 } else if (isa<CXXConversionDecl>(MethodDecl) && 16719 MethodDecl->getParent()->isLambda()) { 16720 CXXConversionDecl *Conversion = 16721 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16722 if (Conversion->isLambdaToBlockPointerConversion()) 16723 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16724 else 16725 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16726 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16727 MarkVTableUsed(Loc, MethodDecl->getParent()); 16728 } 16729 16730 if (Func->isDefaulted() && !Func->isDeleted()) { 16731 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16732 if (DCK != DefaultedComparisonKind::None) 16733 DefineDefaultedComparison(Loc, Func, DCK); 16734 } 16735 16736 // Implicit instantiation of function templates and member functions of 16737 // class templates. 16738 if (Func->isImplicitlyInstantiable()) { 16739 TemplateSpecializationKind TSK = 16740 Func->getTemplateSpecializationKindForInstantiation(); 16741 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16742 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16743 if (FirstInstantiation) { 16744 PointOfInstantiation = Loc; 16745 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16746 } else if (TSK != TSK_ImplicitInstantiation) { 16747 // Use the point of use as the point of instantiation, instead of the 16748 // point of explicit instantiation (which we track as the actual point 16749 // of instantiation). This gives better backtraces in diagnostics. 16750 PointOfInstantiation = Loc; 16751 } 16752 16753 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16754 Func->isConstexpr()) { 16755 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16756 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16757 CodeSynthesisContexts.size()) 16758 PendingLocalImplicitInstantiations.push_back( 16759 std::make_pair(Func, PointOfInstantiation)); 16760 else if (Func->isConstexpr()) 16761 // Do not defer instantiations of constexpr functions, to avoid the 16762 // expression evaluator needing to call back into Sema if it sees a 16763 // call to such a function. 16764 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16765 else { 16766 Func->setInstantiationIsPending(true); 16767 PendingInstantiations.push_back( 16768 std::make_pair(Func, PointOfInstantiation)); 16769 // Notify the consumer that a function was implicitly instantiated. 16770 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16771 } 16772 } 16773 } else { 16774 // Walk redefinitions, as some of them may be instantiable. 16775 for (auto i : Func->redecls()) { 16776 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16777 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16778 } 16779 } 16780 }); 16781 } 16782 16783 // C++14 [except.spec]p17: 16784 // An exception-specification is considered to be needed when: 16785 // - the function is odr-used or, if it appears in an unevaluated operand, 16786 // would be odr-used if the expression were potentially-evaluated; 16787 // 16788 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16789 // function is a pure virtual function we're calling, and in that case the 16790 // function was selected by overload resolution and we need to resolve its 16791 // exception specification for a different reason. 16792 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16793 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16794 ResolveExceptionSpec(Loc, FPT); 16795 16796 // If this is the first "real" use, act on that. 16797 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16798 // Keep track of used but undefined functions. 16799 if (!Func->isDefined()) { 16800 if (mightHaveNonExternalLinkage(Func)) 16801 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16802 else if (Func->getMostRecentDecl()->isInlined() && 16803 !LangOpts.GNUInline && 16804 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16805 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16806 else if (isExternalWithNoLinkageType(Func)) 16807 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16808 } 16809 16810 // Some x86 Windows calling conventions mangle the size of the parameter 16811 // pack into the name. Computing the size of the parameters requires the 16812 // parameter types to be complete. Check that now. 16813 if (funcHasParameterSizeMangling(*this, Func)) 16814 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16815 16816 // In the MS C++ ABI, the compiler emits destructor variants where they are 16817 // used. If the destructor is used here but defined elsewhere, mark the 16818 // virtual base destructors referenced. If those virtual base destructors 16819 // are inline, this will ensure they are defined when emitting the complete 16820 // destructor variant. This checking may be redundant if the destructor is 16821 // provided later in this TU. 16822 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16823 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16824 CXXRecordDecl *Parent = Dtor->getParent(); 16825 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16826 CheckCompleteDestructorVariant(Loc, Dtor); 16827 } 16828 } 16829 16830 Func->markUsed(Context); 16831 } 16832 } 16833 16834 /// Directly mark a variable odr-used. Given a choice, prefer to use 16835 /// MarkVariableReferenced since it does additional checks and then 16836 /// calls MarkVarDeclODRUsed. 16837 /// If the variable must be captured: 16838 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16839 /// - else capture it in the DeclContext that maps to the 16840 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16841 static void 16842 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16843 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16844 // Keep track of used but undefined variables. 16845 // FIXME: We shouldn't suppress this warning for static data members. 16846 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16847 (!Var->isExternallyVisible() || Var->isInline() || 16848 SemaRef.isExternalWithNoLinkageType(Var)) && 16849 !(Var->isStaticDataMember() && Var->hasInit())) { 16850 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16851 if (old.isInvalid()) 16852 old = Loc; 16853 } 16854 QualType CaptureType, DeclRefType; 16855 if (SemaRef.LangOpts.OpenMP) 16856 SemaRef.tryCaptureOpenMPLambdas(Var); 16857 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16858 /*EllipsisLoc*/ SourceLocation(), 16859 /*BuildAndDiagnose*/ true, 16860 CaptureType, DeclRefType, 16861 FunctionScopeIndexToStopAt); 16862 16863 Var->markUsed(SemaRef.Context); 16864 } 16865 16866 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16867 SourceLocation Loc, 16868 unsigned CapturingScopeIndex) { 16869 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16870 } 16871 16872 static void 16873 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16874 ValueDecl *var, DeclContext *DC) { 16875 DeclContext *VarDC = var->getDeclContext(); 16876 16877 // If the parameter still belongs to the translation unit, then 16878 // we're actually just using one parameter in the declaration of 16879 // the next. 16880 if (isa<ParmVarDecl>(var) && 16881 isa<TranslationUnitDecl>(VarDC)) 16882 return; 16883 16884 // For C code, don't diagnose about capture if we're not actually in code 16885 // right now; it's impossible to write a non-constant expression outside of 16886 // function context, so we'll get other (more useful) diagnostics later. 16887 // 16888 // For C++, things get a bit more nasty... it would be nice to suppress this 16889 // diagnostic for certain cases like using a local variable in an array bound 16890 // for a member of a local class, but the correct predicate is not obvious. 16891 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16892 return; 16893 16894 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16895 unsigned ContextKind = 3; // unknown 16896 if (isa<CXXMethodDecl>(VarDC) && 16897 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16898 ContextKind = 2; 16899 } else if (isa<FunctionDecl>(VarDC)) { 16900 ContextKind = 0; 16901 } else if (isa<BlockDecl>(VarDC)) { 16902 ContextKind = 1; 16903 } 16904 16905 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16906 << var << ValueKind << ContextKind << VarDC; 16907 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16908 << var; 16909 16910 // FIXME: Add additional diagnostic info about class etc. which prevents 16911 // capture. 16912 } 16913 16914 16915 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16916 bool &SubCapturesAreNested, 16917 QualType &CaptureType, 16918 QualType &DeclRefType) { 16919 // Check whether we've already captured it. 16920 if (CSI->CaptureMap.count(Var)) { 16921 // If we found a capture, any subcaptures are nested. 16922 SubCapturesAreNested = true; 16923 16924 // Retrieve the capture type for this variable. 16925 CaptureType = CSI->getCapture(Var).getCaptureType(); 16926 16927 // Compute the type of an expression that refers to this variable. 16928 DeclRefType = CaptureType.getNonReferenceType(); 16929 16930 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16931 // are mutable in the sense that user can change their value - they are 16932 // private instances of the captured declarations. 16933 const Capture &Cap = CSI->getCapture(Var); 16934 if (Cap.isCopyCapture() && 16935 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16936 !(isa<CapturedRegionScopeInfo>(CSI) && 16937 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16938 DeclRefType.addConst(); 16939 return true; 16940 } 16941 return false; 16942 } 16943 16944 // Only block literals, captured statements, and lambda expressions can 16945 // capture; other scopes don't work. 16946 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16947 SourceLocation Loc, 16948 const bool Diagnose, Sema &S) { 16949 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16950 return getLambdaAwareParentOfDeclContext(DC); 16951 else if (Var->hasLocalStorage()) { 16952 if (Diagnose) 16953 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16954 } 16955 return nullptr; 16956 } 16957 16958 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16959 // certain types of variables (unnamed, variably modified types etc.) 16960 // so check for eligibility. 16961 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16962 SourceLocation Loc, 16963 const bool Diagnose, Sema &S) { 16964 16965 bool IsBlock = isa<BlockScopeInfo>(CSI); 16966 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16967 16968 // Lambdas are not allowed to capture unnamed variables 16969 // (e.g. anonymous unions). 16970 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16971 // assuming that's the intent. 16972 if (IsLambda && !Var->getDeclName()) { 16973 if (Diagnose) { 16974 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16975 S.Diag(Var->getLocation(), diag::note_declared_at); 16976 } 16977 return false; 16978 } 16979 16980 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16981 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16982 if (Diagnose) { 16983 S.Diag(Loc, diag::err_ref_vm_type); 16984 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 16985 } 16986 return false; 16987 } 16988 // Prohibit structs with flexible array members too. 16989 // We cannot capture what is in the tail end of the struct. 16990 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16991 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16992 if (Diagnose) { 16993 if (IsBlock) 16994 S.Diag(Loc, diag::err_ref_flexarray_type); 16995 else 16996 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 16997 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 16998 } 16999 return false; 17000 } 17001 } 17002 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17003 // Lambdas and captured statements are not allowed to capture __block 17004 // variables; they don't support the expected semantics. 17005 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17006 if (Diagnose) { 17007 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17008 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17009 } 17010 return false; 17011 } 17012 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17013 if (S.getLangOpts().OpenCL && IsBlock && 17014 Var->getType()->isBlockPointerType()) { 17015 if (Diagnose) 17016 S.Diag(Loc, diag::err_opencl_block_ref_block); 17017 return false; 17018 } 17019 17020 return true; 17021 } 17022 17023 // Returns true if the capture by block was successful. 17024 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17025 SourceLocation Loc, 17026 const bool BuildAndDiagnose, 17027 QualType &CaptureType, 17028 QualType &DeclRefType, 17029 const bool Nested, 17030 Sema &S, bool Invalid) { 17031 bool ByRef = false; 17032 17033 // Blocks are not allowed to capture arrays, excepting OpenCL. 17034 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17035 // (decayed to pointers). 17036 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17037 if (BuildAndDiagnose) { 17038 S.Diag(Loc, diag::err_ref_array_type); 17039 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17040 Invalid = true; 17041 } else { 17042 return false; 17043 } 17044 } 17045 17046 // Forbid the block-capture of autoreleasing variables. 17047 if (!Invalid && 17048 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17049 if (BuildAndDiagnose) { 17050 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17051 << /*block*/ 0; 17052 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17053 Invalid = true; 17054 } else { 17055 return false; 17056 } 17057 } 17058 17059 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17060 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17061 QualType PointeeTy = PT->getPointeeType(); 17062 17063 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17064 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17065 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17066 if (BuildAndDiagnose) { 17067 SourceLocation VarLoc = Var->getLocation(); 17068 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17069 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17070 } 17071 } 17072 } 17073 17074 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17075 if (HasBlocksAttr || CaptureType->isReferenceType() || 17076 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17077 // Block capture by reference does not change the capture or 17078 // declaration reference types. 17079 ByRef = true; 17080 } else { 17081 // Block capture by copy introduces 'const'. 17082 CaptureType = CaptureType.getNonReferenceType().withConst(); 17083 DeclRefType = CaptureType; 17084 } 17085 17086 // Actually capture the variable. 17087 if (BuildAndDiagnose) 17088 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17089 CaptureType, Invalid); 17090 17091 return !Invalid; 17092 } 17093 17094 17095 /// Capture the given variable in the captured region. 17096 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17097 VarDecl *Var, 17098 SourceLocation Loc, 17099 const bool BuildAndDiagnose, 17100 QualType &CaptureType, 17101 QualType &DeclRefType, 17102 const bool RefersToCapturedVariable, 17103 Sema &S, bool Invalid) { 17104 // By default, capture variables by reference. 17105 bool ByRef = true; 17106 // Using an LValue reference type is consistent with Lambdas (see below). 17107 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17108 if (S.isOpenMPCapturedDecl(Var)) { 17109 bool HasConst = DeclRefType.isConstQualified(); 17110 DeclRefType = DeclRefType.getUnqualifiedType(); 17111 // Don't lose diagnostics about assignments to const. 17112 if (HasConst) 17113 DeclRefType.addConst(); 17114 } 17115 // Do not capture firstprivates in tasks. 17116 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17117 OMPC_unknown) 17118 return true; 17119 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17120 RSI->OpenMPCaptureLevel); 17121 } 17122 17123 if (ByRef) 17124 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17125 else 17126 CaptureType = DeclRefType; 17127 17128 // Actually capture the variable. 17129 if (BuildAndDiagnose) 17130 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17131 Loc, SourceLocation(), CaptureType, Invalid); 17132 17133 return !Invalid; 17134 } 17135 17136 /// Capture the given variable in the lambda. 17137 static bool captureInLambda(LambdaScopeInfo *LSI, 17138 VarDecl *Var, 17139 SourceLocation Loc, 17140 const bool BuildAndDiagnose, 17141 QualType &CaptureType, 17142 QualType &DeclRefType, 17143 const bool RefersToCapturedVariable, 17144 const Sema::TryCaptureKind Kind, 17145 SourceLocation EllipsisLoc, 17146 const bool IsTopScope, 17147 Sema &S, bool Invalid) { 17148 // Determine whether we are capturing by reference or by value. 17149 bool ByRef = false; 17150 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17151 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17152 } else { 17153 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17154 } 17155 17156 // Compute the type of the field that will capture this variable. 17157 if (ByRef) { 17158 // C++11 [expr.prim.lambda]p15: 17159 // An entity is captured by reference if it is implicitly or 17160 // explicitly captured but not captured by copy. It is 17161 // unspecified whether additional unnamed non-static data 17162 // members are declared in the closure type for entities 17163 // captured by reference. 17164 // 17165 // FIXME: It is not clear whether we want to build an lvalue reference 17166 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17167 // to do the former, while EDG does the latter. Core issue 1249 will 17168 // clarify, but for now we follow GCC because it's a more permissive and 17169 // easily defensible position. 17170 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17171 } else { 17172 // C++11 [expr.prim.lambda]p14: 17173 // For each entity captured by copy, an unnamed non-static 17174 // data member is declared in the closure type. The 17175 // declaration order of these members is unspecified. The type 17176 // of such a data member is the type of the corresponding 17177 // captured entity if the entity is not a reference to an 17178 // object, or the referenced type otherwise. [Note: If the 17179 // captured entity is a reference to a function, the 17180 // corresponding data member is also a reference to a 17181 // function. - end note ] 17182 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17183 if (!RefType->getPointeeType()->isFunctionType()) 17184 CaptureType = RefType->getPointeeType(); 17185 } 17186 17187 // Forbid the lambda copy-capture of autoreleasing variables. 17188 if (!Invalid && 17189 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17190 if (BuildAndDiagnose) { 17191 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17192 S.Diag(Var->getLocation(), diag::note_previous_decl) 17193 << Var->getDeclName(); 17194 Invalid = true; 17195 } else { 17196 return false; 17197 } 17198 } 17199 17200 // Make sure that by-copy captures are of a complete and non-abstract type. 17201 if (!Invalid && BuildAndDiagnose) { 17202 if (!CaptureType->isDependentType() && 17203 S.RequireCompleteSizedType( 17204 Loc, CaptureType, 17205 diag::err_capture_of_incomplete_or_sizeless_type, 17206 Var->getDeclName())) 17207 Invalid = true; 17208 else if (S.RequireNonAbstractType(Loc, CaptureType, 17209 diag::err_capture_of_abstract_type)) 17210 Invalid = true; 17211 } 17212 } 17213 17214 // Compute the type of a reference to this captured variable. 17215 if (ByRef) 17216 DeclRefType = CaptureType.getNonReferenceType(); 17217 else { 17218 // C++ [expr.prim.lambda]p5: 17219 // The closure type for a lambda-expression has a public inline 17220 // function call operator [...]. This function call operator is 17221 // declared const (9.3.1) if and only if the lambda-expression's 17222 // parameter-declaration-clause is not followed by mutable. 17223 DeclRefType = CaptureType.getNonReferenceType(); 17224 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17225 DeclRefType.addConst(); 17226 } 17227 17228 // Add the capture. 17229 if (BuildAndDiagnose) 17230 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17231 Loc, EllipsisLoc, CaptureType, Invalid); 17232 17233 return !Invalid; 17234 } 17235 17236 bool Sema::tryCaptureVariable( 17237 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17238 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17239 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17240 // An init-capture is notionally from the context surrounding its 17241 // declaration, but its parent DC is the lambda class. 17242 DeclContext *VarDC = Var->getDeclContext(); 17243 if (Var->isInitCapture()) 17244 VarDC = VarDC->getParent(); 17245 17246 DeclContext *DC = CurContext; 17247 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17248 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17249 // We need to sync up the Declaration Context with the 17250 // FunctionScopeIndexToStopAt 17251 if (FunctionScopeIndexToStopAt) { 17252 unsigned FSIndex = FunctionScopes.size() - 1; 17253 while (FSIndex != MaxFunctionScopesIndex) { 17254 DC = getLambdaAwareParentOfDeclContext(DC); 17255 --FSIndex; 17256 } 17257 } 17258 17259 17260 // If the variable is declared in the current context, there is no need to 17261 // capture it. 17262 if (VarDC == DC) return true; 17263 17264 // Capture global variables if it is required to use private copy of this 17265 // variable. 17266 bool IsGlobal = !Var->hasLocalStorage(); 17267 if (IsGlobal && 17268 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17269 MaxFunctionScopesIndex))) 17270 return true; 17271 Var = Var->getCanonicalDecl(); 17272 17273 // Walk up the stack to determine whether we can capture the variable, 17274 // performing the "simple" checks that don't depend on type. We stop when 17275 // we've either hit the declared scope of the variable or find an existing 17276 // capture of that variable. We start from the innermost capturing-entity 17277 // (the DC) and ensure that all intervening capturing-entities 17278 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17279 // declcontext can either capture the variable or have already captured 17280 // the variable. 17281 CaptureType = Var->getType(); 17282 DeclRefType = CaptureType.getNonReferenceType(); 17283 bool Nested = false; 17284 bool Explicit = (Kind != TryCapture_Implicit); 17285 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17286 do { 17287 // Only block literals, captured statements, and lambda expressions can 17288 // capture; other scopes don't work. 17289 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17290 ExprLoc, 17291 BuildAndDiagnose, 17292 *this); 17293 // We need to check for the parent *first* because, if we *have* 17294 // private-captured a global variable, we need to recursively capture it in 17295 // intermediate blocks, lambdas, etc. 17296 if (!ParentDC) { 17297 if (IsGlobal) { 17298 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17299 break; 17300 } 17301 return true; 17302 } 17303 17304 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17305 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17306 17307 17308 // Check whether we've already captured it. 17309 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17310 DeclRefType)) { 17311 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17312 break; 17313 } 17314 // If we are instantiating a generic lambda call operator body, 17315 // we do not want to capture new variables. What was captured 17316 // during either a lambdas transformation or initial parsing 17317 // should be used. 17318 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17319 if (BuildAndDiagnose) { 17320 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17321 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17322 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17323 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17324 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17325 } else 17326 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17327 } 17328 return true; 17329 } 17330 17331 // Try to capture variable-length arrays types. 17332 if (Var->getType()->isVariablyModifiedType()) { 17333 // We're going to walk down into the type and look for VLA 17334 // expressions. 17335 QualType QTy = Var->getType(); 17336 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17337 QTy = PVD->getOriginalType(); 17338 captureVariablyModifiedType(Context, QTy, CSI); 17339 } 17340 17341 if (getLangOpts().OpenMP) { 17342 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17343 // OpenMP private variables should not be captured in outer scope, so 17344 // just break here. Similarly, global variables that are captured in a 17345 // target region should not be captured outside the scope of the region. 17346 if (RSI->CapRegionKind == CR_OpenMP) { 17347 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17348 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17349 // If the variable is private (i.e. not captured) and has variably 17350 // modified type, we still need to capture the type for correct 17351 // codegen in all regions, associated with the construct. Currently, 17352 // it is captured in the innermost captured region only. 17353 if (IsOpenMPPrivateDecl != OMPC_unknown && 17354 Var->getType()->isVariablyModifiedType()) { 17355 QualType QTy = Var->getType(); 17356 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17357 QTy = PVD->getOriginalType(); 17358 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17359 I < E; ++I) { 17360 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17361 FunctionScopes[FunctionScopesIndex - I]); 17362 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17363 "Wrong number of captured regions associated with the " 17364 "OpenMP construct."); 17365 captureVariablyModifiedType(Context, QTy, OuterRSI); 17366 } 17367 } 17368 bool IsTargetCap = 17369 IsOpenMPPrivateDecl != OMPC_private && 17370 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17371 RSI->OpenMPCaptureLevel); 17372 // Do not capture global if it is not privatized in outer regions. 17373 bool IsGlobalCap = 17374 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17375 RSI->OpenMPCaptureLevel); 17376 17377 // When we detect target captures we are looking from inside the 17378 // target region, therefore we need to propagate the capture from the 17379 // enclosing region. Therefore, the capture is not initially nested. 17380 if (IsTargetCap) 17381 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17382 17383 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17384 (IsGlobal && !IsGlobalCap)) { 17385 Nested = !IsTargetCap; 17386 DeclRefType = DeclRefType.getUnqualifiedType(); 17387 CaptureType = Context.getLValueReferenceType(DeclRefType); 17388 break; 17389 } 17390 } 17391 } 17392 } 17393 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17394 // No capture-default, and this is not an explicit capture 17395 // so cannot capture this variable. 17396 if (BuildAndDiagnose) { 17397 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17398 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17399 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17400 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17401 diag::note_lambda_decl); 17402 // FIXME: If we error out because an outer lambda can not implicitly 17403 // capture a variable that an inner lambda explicitly captures, we 17404 // should have the inner lambda do the explicit capture - because 17405 // it makes for cleaner diagnostics later. This would purely be done 17406 // so that the diagnostic does not misleadingly claim that a variable 17407 // can not be captured by a lambda implicitly even though it is captured 17408 // explicitly. Suggestion: 17409 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17410 // at the function head 17411 // - cache the StartingDeclContext - this must be a lambda 17412 // - captureInLambda in the innermost lambda the variable. 17413 } 17414 return true; 17415 } 17416 17417 FunctionScopesIndex--; 17418 DC = ParentDC; 17419 Explicit = false; 17420 } while (!VarDC->Equals(DC)); 17421 17422 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17423 // computing the type of the capture at each step, checking type-specific 17424 // requirements, and adding captures if requested. 17425 // If the variable had already been captured previously, we start capturing 17426 // at the lambda nested within that one. 17427 bool Invalid = false; 17428 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17429 ++I) { 17430 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17431 17432 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17433 // certain types of variables (unnamed, variably modified types etc.) 17434 // so check for eligibility. 17435 if (!Invalid) 17436 Invalid = 17437 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17438 17439 // After encountering an error, if we're actually supposed to capture, keep 17440 // capturing in nested contexts to suppress any follow-on diagnostics. 17441 if (Invalid && !BuildAndDiagnose) 17442 return true; 17443 17444 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17445 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17446 DeclRefType, Nested, *this, Invalid); 17447 Nested = true; 17448 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17449 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17450 CaptureType, DeclRefType, Nested, 17451 *this, Invalid); 17452 Nested = true; 17453 } else { 17454 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17455 Invalid = 17456 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17457 DeclRefType, Nested, Kind, EllipsisLoc, 17458 /*IsTopScope*/ I == N - 1, *this, Invalid); 17459 Nested = true; 17460 } 17461 17462 if (Invalid && !BuildAndDiagnose) 17463 return true; 17464 } 17465 return Invalid; 17466 } 17467 17468 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17469 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17470 QualType CaptureType; 17471 QualType DeclRefType; 17472 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17473 /*BuildAndDiagnose=*/true, CaptureType, 17474 DeclRefType, nullptr); 17475 } 17476 17477 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17478 QualType CaptureType; 17479 QualType DeclRefType; 17480 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17481 /*BuildAndDiagnose=*/false, CaptureType, 17482 DeclRefType, nullptr); 17483 } 17484 17485 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17486 QualType CaptureType; 17487 QualType DeclRefType; 17488 17489 // Determine whether we can capture this variable. 17490 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17491 /*BuildAndDiagnose=*/false, CaptureType, 17492 DeclRefType, nullptr)) 17493 return QualType(); 17494 17495 return DeclRefType; 17496 } 17497 17498 namespace { 17499 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17500 // The produced TemplateArgumentListInfo* points to data stored within this 17501 // object, so should only be used in contexts where the pointer will not be 17502 // used after the CopiedTemplateArgs object is destroyed. 17503 class CopiedTemplateArgs { 17504 bool HasArgs; 17505 TemplateArgumentListInfo TemplateArgStorage; 17506 public: 17507 template<typename RefExpr> 17508 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17509 if (HasArgs) 17510 E->copyTemplateArgumentsInto(TemplateArgStorage); 17511 } 17512 operator TemplateArgumentListInfo*() 17513 #ifdef __has_cpp_attribute 17514 #if __has_cpp_attribute(clang::lifetimebound) 17515 [[clang::lifetimebound]] 17516 #endif 17517 #endif 17518 { 17519 return HasArgs ? &TemplateArgStorage : nullptr; 17520 } 17521 }; 17522 } 17523 17524 /// Walk the set of potential results of an expression and mark them all as 17525 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17526 /// 17527 /// \return A new expression if we found any potential results, ExprEmpty() if 17528 /// not, and ExprError() if we diagnosed an error. 17529 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17530 NonOdrUseReason NOUR) { 17531 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17532 // an object that satisfies the requirements for appearing in a 17533 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17534 // is immediately applied." This function handles the lvalue-to-rvalue 17535 // conversion part. 17536 // 17537 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17538 // transform it into the relevant kind of non-odr-use node and rebuild the 17539 // tree of nodes leading to it. 17540 // 17541 // This is a mini-TreeTransform that only transforms a restricted subset of 17542 // nodes (and only certain operands of them). 17543 17544 // Rebuild a subexpression. 17545 auto Rebuild = [&](Expr *Sub) { 17546 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17547 }; 17548 17549 // Check whether a potential result satisfies the requirements of NOUR. 17550 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17551 // Any entity other than a VarDecl is always odr-used whenever it's named 17552 // in a potentially-evaluated expression. 17553 auto *VD = dyn_cast<VarDecl>(D); 17554 if (!VD) 17555 return true; 17556 17557 // C++2a [basic.def.odr]p4: 17558 // A variable x whose name appears as a potentially-evalauted expression 17559 // e is odr-used by e unless 17560 // -- x is a reference that is usable in constant expressions, or 17561 // -- x is a variable of non-reference type that is usable in constant 17562 // expressions and has no mutable subobjects, and e is an element of 17563 // the set of potential results of an expression of 17564 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17565 // conversion is applied, or 17566 // -- x is a variable of non-reference type, and e is an element of the 17567 // set of potential results of a discarded-value expression to which 17568 // the lvalue-to-rvalue conversion is not applied 17569 // 17570 // We check the first bullet and the "potentially-evaluated" condition in 17571 // BuildDeclRefExpr. We check the type requirements in the second bullet 17572 // in CheckLValueToRValueConversionOperand below. 17573 switch (NOUR) { 17574 case NOUR_None: 17575 case NOUR_Unevaluated: 17576 llvm_unreachable("unexpected non-odr-use-reason"); 17577 17578 case NOUR_Constant: 17579 // Constant references were handled when they were built. 17580 if (VD->getType()->isReferenceType()) 17581 return true; 17582 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17583 if (RD->hasMutableFields()) 17584 return true; 17585 if (!VD->isUsableInConstantExpressions(S.Context)) 17586 return true; 17587 break; 17588 17589 case NOUR_Discarded: 17590 if (VD->getType()->isReferenceType()) 17591 return true; 17592 break; 17593 } 17594 return false; 17595 }; 17596 17597 // Mark that this expression does not constitute an odr-use. 17598 auto MarkNotOdrUsed = [&] { 17599 S.MaybeODRUseExprs.remove(E); 17600 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17601 LSI->markVariableExprAsNonODRUsed(E); 17602 }; 17603 17604 // C++2a [basic.def.odr]p2: 17605 // The set of potential results of an expression e is defined as follows: 17606 switch (E->getStmtClass()) { 17607 // -- If e is an id-expression, ... 17608 case Expr::DeclRefExprClass: { 17609 auto *DRE = cast<DeclRefExpr>(E); 17610 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17611 break; 17612 17613 // Rebuild as a non-odr-use DeclRefExpr. 17614 MarkNotOdrUsed(); 17615 return DeclRefExpr::Create( 17616 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17617 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17618 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17619 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17620 } 17621 17622 case Expr::FunctionParmPackExprClass: { 17623 auto *FPPE = cast<FunctionParmPackExpr>(E); 17624 // If any of the declarations in the pack is odr-used, then the expression 17625 // as a whole constitutes an odr-use. 17626 for (VarDecl *D : *FPPE) 17627 if (IsPotentialResultOdrUsed(D)) 17628 return ExprEmpty(); 17629 17630 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17631 // nothing cares about whether we marked this as an odr-use, but it might 17632 // be useful for non-compiler tools. 17633 MarkNotOdrUsed(); 17634 break; 17635 } 17636 17637 // -- If e is a subscripting operation with an array operand... 17638 case Expr::ArraySubscriptExprClass: { 17639 auto *ASE = cast<ArraySubscriptExpr>(E); 17640 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17641 if (!OldBase->getType()->isArrayType()) 17642 break; 17643 ExprResult Base = Rebuild(OldBase); 17644 if (!Base.isUsable()) 17645 return Base; 17646 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17647 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17648 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17649 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17650 ASE->getRBracketLoc()); 17651 } 17652 17653 case Expr::MemberExprClass: { 17654 auto *ME = cast<MemberExpr>(E); 17655 // -- If e is a class member access expression [...] naming a non-static 17656 // data member... 17657 if (isa<FieldDecl>(ME->getMemberDecl())) { 17658 ExprResult Base = Rebuild(ME->getBase()); 17659 if (!Base.isUsable()) 17660 return Base; 17661 return MemberExpr::Create( 17662 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17663 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17664 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17665 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17666 ME->getObjectKind(), ME->isNonOdrUse()); 17667 } 17668 17669 if (ME->getMemberDecl()->isCXXInstanceMember()) 17670 break; 17671 17672 // -- If e is a class member access expression naming a static data member, 17673 // ... 17674 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17675 break; 17676 17677 // Rebuild as a non-odr-use MemberExpr. 17678 MarkNotOdrUsed(); 17679 return MemberExpr::Create( 17680 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17681 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17682 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17683 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17684 return ExprEmpty(); 17685 } 17686 17687 case Expr::BinaryOperatorClass: { 17688 auto *BO = cast<BinaryOperator>(E); 17689 Expr *LHS = BO->getLHS(); 17690 Expr *RHS = BO->getRHS(); 17691 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17692 if (BO->getOpcode() == BO_PtrMemD) { 17693 ExprResult Sub = Rebuild(LHS); 17694 if (!Sub.isUsable()) 17695 return Sub; 17696 LHS = Sub.get(); 17697 // -- If e is a comma expression, ... 17698 } else if (BO->getOpcode() == BO_Comma) { 17699 ExprResult Sub = Rebuild(RHS); 17700 if (!Sub.isUsable()) 17701 return Sub; 17702 RHS = Sub.get(); 17703 } else { 17704 break; 17705 } 17706 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17707 LHS, RHS); 17708 } 17709 17710 // -- If e has the form (e1)... 17711 case Expr::ParenExprClass: { 17712 auto *PE = cast<ParenExpr>(E); 17713 ExprResult Sub = Rebuild(PE->getSubExpr()); 17714 if (!Sub.isUsable()) 17715 return Sub; 17716 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17717 } 17718 17719 // -- If e is a glvalue conditional expression, ... 17720 // We don't apply this to a binary conditional operator. FIXME: Should we? 17721 case Expr::ConditionalOperatorClass: { 17722 auto *CO = cast<ConditionalOperator>(E); 17723 ExprResult LHS = Rebuild(CO->getLHS()); 17724 if (LHS.isInvalid()) 17725 return ExprError(); 17726 ExprResult RHS = Rebuild(CO->getRHS()); 17727 if (RHS.isInvalid()) 17728 return ExprError(); 17729 if (!LHS.isUsable() && !RHS.isUsable()) 17730 return ExprEmpty(); 17731 if (!LHS.isUsable()) 17732 LHS = CO->getLHS(); 17733 if (!RHS.isUsable()) 17734 RHS = CO->getRHS(); 17735 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17736 CO->getCond(), LHS.get(), RHS.get()); 17737 } 17738 17739 // [Clang extension] 17740 // -- If e has the form __extension__ e1... 17741 case Expr::UnaryOperatorClass: { 17742 auto *UO = cast<UnaryOperator>(E); 17743 if (UO->getOpcode() != UO_Extension) 17744 break; 17745 ExprResult Sub = Rebuild(UO->getSubExpr()); 17746 if (!Sub.isUsable()) 17747 return Sub; 17748 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17749 Sub.get()); 17750 } 17751 17752 // [Clang extension] 17753 // -- If e has the form _Generic(...), the set of potential results is the 17754 // union of the sets of potential results of the associated expressions. 17755 case Expr::GenericSelectionExprClass: { 17756 auto *GSE = cast<GenericSelectionExpr>(E); 17757 17758 SmallVector<Expr *, 4> AssocExprs; 17759 bool AnyChanged = false; 17760 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17761 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17762 if (AssocExpr.isInvalid()) 17763 return ExprError(); 17764 if (AssocExpr.isUsable()) { 17765 AssocExprs.push_back(AssocExpr.get()); 17766 AnyChanged = true; 17767 } else { 17768 AssocExprs.push_back(OrigAssocExpr); 17769 } 17770 } 17771 17772 return AnyChanged ? S.CreateGenericSelectionExpr( 17773 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17774 GSE->getRParenLoc(), GSE->getControllingExpr(), 17775 GSE->getAssocTypeSourceInfos(), AssocExprs) 17776 : ExprEmpty(); 17777 } 17778 17779 // [Clang extension] 17780 // -- If e has the form __builtin_choose_expr(...), the set of potential 17781 // results is the union of the sets of potential results of the 17782 // second and third subexpressions. 17783 case Expr::ChooseExprClass: { 17784 auto *CE = cast<ChooseExpr>(E); 17785 17786 ExprResult LHS = Rebuild(CE->getLHS()); 17787 if (LHS.isInvalid()) 17788 return ExprError(); 17789 17790 ExprResult RHS = Rebuild(CE->getLHS()); 17791 if (RHS.isInvalid()) 17792 return ExprError(); 17793 17794 if (!LHS.get() && !RHS.get()) 17795 return ExprEmpty(); 17796 if (!LHS.isUsable()) 17797 LHS = CE->getLHS(); 17798 if (!RHS.isUsable()) 17799 RHS = CE->getRHS(); 17800 17801 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17802 RHS.get(), CE->getRParenLoc()); 17803 } 17804 17805 // Step through non-syntactic nodes. 17806 case Expr::ConstantExprClass: { 17807 auto *CE = cast<ConstantExpr>(E); 17808 ExprResult Sub = Rebuild(CE->getSubExpr()); 17809 if (!Sub.isUsable()) 17810 return Sub; 17811 return ConstantExpr::Create(S.Context, Sub.get()); 17812 } 17813 17814 // We could mostly rely on the recursive rebuilding to rebuild implicit 17815 // casts, but not at the top level, so rebuild them here. 17816 case Expr::ImplicitCastExprClass: { 17817 auto *ICE = cast<ImplicitCastExpr>(E); 17818 // Only step through the narrow set of cast kinds we expect to encounter. 17819 // Anything else suggests we've left the region in which potential results 17820 // can be found. 17821 switch (ICE->getCastKind()) { 17822 case CK_NoOp: 17823 case CK_DerivedToBase: 17824 case CK_UncheckedDerivedToBase: { 17825 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17826 if (!Sub.isUsable()) 17827 return Sub; 17828 CXXCastPath Path(ICE->path()); 17829 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17830 ICE->getValueKind(), &Path); 17831 } 17832 17833 default: 17834 break; 17835 } 17836 break; 17837 } 17838 17839 default: 17840 break; 17841 } 17842 17843 // Can't traverse through this node. Nothing to do. 17844 return ExprEmpty(); 17845 } 17846 17847 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17848 // Check whether the operand is or contains an object of non-trivial C union 17849 // type. 17850 if (E->getType().isVolatileQualified() && 17851 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17852 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17853 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17854 Sema::NTCUC_LValueToRValueVolatile, 17855 NTCUK_Destruct|NTCUK_Copy); 17856 17857 // C++2a [basic.def.odr]p4: 17858 // [...] an expression of non-volatile-qualified non-class type to which 17859 // the lvalue-to-rvalue conversion is applied [...] 17860 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17861 return E; 17862 17863 ExprResult Result = 17864 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17865 if (Result.isInvalid()) 17866 return ExprError(); 17867 return Result.get() ? Result : E; 17868 } 17869 17870 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17871 Res = CorrectDelayedTyposInExpr(Res); 17872 17873 if (!Res.isUsable()) 17874 return Res; 17875 17876 // If a constant-expression is a reference to a variable where we delay 17877 // deciding whether it is an odr-use, just assume we will apply the 17878 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17879 // (a non-type template argument), we have special handling anyway. 17880 return CheckLValueToRValueConversionOperand(Res.get()); 17881 } 17882 17883 void Sema::CleanupVarDeclMarking() { 17884 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17885 // call. 17886 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17887 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17888 17889 for (Expr *E : LocalMaybeODRUseExprs) { 17890 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17891 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17892 DRE->getLocation(), *this); 17893 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17894 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17895 *this); 17896 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17897 for (VarDecl *VD : *FP) 17898 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17899 } else { 17900 llvm_unreachable("Unexpected expression"); 17901 } 17902 } 17903 17904 assert(MaybeODRUseExprs.empty() && 17905 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17906 } 17907 17908 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17909 VarDecl *Var, Expr *E) { 17910 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17911 isa<FunctionParmPackExpr>(E)) && 17912 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17913 Var->setReferenced(); 17914 17915 if (Var->isInvalidDecl()) 17916 return; 17917 17918 // Record a CUDA/HIP static device/constant variable if it is referenced 17919 // by host code. This is done conservatively, when the variable is referenced 17920 // in any of the following contexts: 17921 // - a non-function context 17922 // - a host function 17923 // - a host device function 17924 // This also requires the reference of the static device/constant variable by 17925 // host code to be visible in the device compilation for the compiler to be 17926 // able to externalize the static device/constant variable. 17927 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 17928 auto *CurContext = SemaRef.CurContext; 17929 if (!CurContext || !isa<FunctionDecl>(CurContext) || 17930 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 17931 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 17932 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 17933 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 17934 } 17935 17936 auto *MSI = Var->getMemberSpecializationInfo(); 17937 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17938 : Var->getTemplateSpecializationKind(); 17939 17940 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17941 bool UsableInConstantExpr = 17942 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17943 17944 // C++20 [expr.const]p12: 17945 // A variable [...] is needed for constant evaluation if it is [...] a 17946 // variable whose name appears as a potentially constant evaluated 17947 // expression that is either a contexpr variable or is of non-volatile 17948 // const-qualified integral type or of reference type 17949 bool NeededForConstantEvaluation = 17950 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17951 17952 bool NeedDefinition = 17953 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17954 17955 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17956 "Can't instantiate a partial template specialization."); 17957 17958 // If this might be a member specialization of a static data member, check 17959 // the specialization is visible. We already did the checks for variable 17960 // template specializations when we created them. 17961 if (NeedDefinition && TSK != TSK_Undeclared && 17962 !isa<VarTemplateSpecializationDecl>(Var)) 17963 SemaRef.checkSpecializationVisibility(Loc, Var); 17964 17965 // Perform implicit instantiation of static data members, static data member 17966 // templates of class templates, and variable template specializations. Delay 17967 // instantiations of variable templates, except for those that could be used 17968 // in a constant expression. 17969 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17970 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17971 // instantiation declaration if a variable is usable in a constant 17972 // expression (among other cases). 17973 bool TryInstantiating = 17974 TSK == TSK_ImplicitInstantiation || 17975 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17976 17977 if (TryInstantiating) { 17978 SourceLocation PointOfInstantiation = 17979 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17980 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17981 if (FirstInstantiation) { 17982 PointOfInstantiation = Loc; 17983 if (MSI) 17984 MSI->setPointOfInstantiation(PointOfInstantiation); 17985 else 17986 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17987 } 17988 17989 if (UsableInConstantExpr) { 17990 // Do not defer instantiations of variables that could be used in a 17991 // constant expression. 17992 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17993 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17994 }); 17995 } else if (FirstInstantiation || 17996 isa<VarTemplateSpecializationDecl>(Var)) { 17997 // FIXME: For a specialization of a variable template, we don't 17998 // distinguish between "declaration and type implicitly instantiated" 17999 // and "implicit instantiation of definition requested", so we have 18000 // no direct way to avoid enqueueing the pending instantiation 18001 // multiple times. 18002 SemaRef.PendingInstantiations 18003 .push_back(std::make_pair(Var, PointOfInstantiation)); 18004 } 18005 } 18006 } 18007 18008 // C++2a [basic.def.odr]p4: 18009 // A variable x whose name appears as a potentially-evaluated expression e 18010 // is odr-used by e unless 18011 // -- x is a reference that is usable in constant expressions 18012 // -- x is a variable of non-reference type that is usable in constant 18013 // expressions and has no mutable subobjects [FIXME], and e is an 18014 // element of the set of potential results of an expression of 18015 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18016 // conversion is applied 18017 // -- x is a variable of non-reference type, and e is an element of the set 18018 // of potential results of a discarded-value expression to which the 18019 // lvalue-to-rvalue conversion is not applied [FIXME] 18020 // 18021 // We check the first part of the second bullet here, and 18022 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18023 // FIXME: To get the third bullet right, we need to delay this even for 18024 // variables that are not usable in constant expressions. 18025 18026 // If we already know this isn't an odr-use, there's nothing more to do. 18027 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18028 if (DRE->isNonOdrUse()) 18029 return; 18030 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18031 if (ME->isNonOdrUse()) 18032 return; 18033 18034 switch (OdrUse) { 18035 case OdrUseContext::None: 18036 assert((!E || isa<FunctionParmPackExpr>(E)) && 18037 "missing non-odr-use marking for unevaluated decl ref"); 18038 break; 18039 18040 case OdrUseContext::FormallyOdrUsed: 18041 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18042 // behavior. 18043 break; 18044 18045 case OdrUseContext::Used: 18046 // If we might later find that this expression isn't actually an odr-use, 18047 // delay the marking. 18048 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18049 SemaRef.MaybeODRUseExprs.insert(E); 18050 else 18051 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18052 break; 18053 18054 case OdrUseContext::Dependent: 18055 // If this is a dependent context, we don't need to mark variables as 18056 // odr-used, but we may still need to track them for lambda capture. 18057 // FIXME: Do we also need to do this inside dependent typeid expressions 18058 // (which are modeled as unevaluated at this point)? 18059 const bool RefersToEnclosingScope = 18060 (SemaRef.CurContext != Var->getDeclContext() && 18061 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18062 if (RefersToEnclosingScope) { 18063 LambdaScopeInfo *const LSI = 18064 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18065 if (LSI && (!LSI->CallOperator || 18066 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18067 // If a variable could potentially be odr-used, defer marking it so 18068 // until we finish analyzing the full expression for any 18069 // lvalue-to-rvalue 18070 // or discarded value conversions that would obviate odr-use. 18071 // Add it to the list of potential captures that will be analyzed 18072 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18073 // unless the variable is a reference that was initialized by a constant 18074 // expression (this will never need to be captured or odr-used). 18075 // 18076 // FIXME: We can simplify this a lot after implementing P0588R1. 18077 assert(E && "Capture variable should be used in an expression."); 18078 if (!Var->getType()->isReferenceType() || 18079 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18080 LSI->addPotentialCapture(E->IgnoreParens()); 18081 } 18082 } 18083 break; 18084 } 18085 } 18086 18087 /// Mark a variable referenced, and check whether it is odr-used 18088 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18089 /// used directly for normal expressions referring to VarDecl. 18090 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18091 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18092 } 18093 18094 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18095 Decl *D, Expr *E, bool MightBeOdrUse) { 18096 if (SemaRef.isInOpenMPDeclareTargetContext()) 18097 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18098 18099 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18100 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18101 return; 18102 } 18103 18104 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18105 18106 // If this is a call to a method via a cast, also mark the method in the 18107 // derived class used in case codegen can devirtualize the call. 18108 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18109 if (!ME) 18110 return; 18111 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18112 if (!MD) 18113 return; 18114 // Only attempt to devirtualize if this is truly a virtual call. 18115 bool IsVirtualCall = MD->isVirtual() && 18116 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18117 if (!IsVirtualCall) 18118 return; 18119 18120 // If it's possible to devirtualize the call, mark the called function 18121 // referenced. 18122 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18123 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18124 if (DM) 18125 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18126 } 18127 18128 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18129 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18130 // TODO: update this with DR# once a defect report is filed. 18131 // C++11 defect. The address of a pure member should not be an ODR use, even 18132 // if it's a qualified reference. 18133 bool OdrUse = true; 18134 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18135 if (Method->isVirtual() && 18136 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18137 OdrUse = false; 18138 18139 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18140 if (!isConstantEvaluated() && FD->isConsteval() && 18141 !RebuildingImmediateInvocation) 18142 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18143 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18144 } 18145 18146 /// Perform reference-marking and odr-use handling for a MemberExpr. 18147 void Sema::MarkMemberReferenced(MemberExpr *E) { 18148 // C++11 [basic.def.odr]p2: 18149 // A non-overloaded function whose name appears as a potentially-evaluated 18150 // expression or a member of a set of candidate functions, if selected by 18151 // overload resolution when referred to from a potentially-evaluated 18152 // expression, is odr-used, unless it is a pure virtual function and its 18153 // name is not explicitly qualified. 18154 bool MightBeOdrUse = true; 18155 if (E->performsVirtualDispatch(getLangOpts())) { 18156 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18157 if (Method->isPure()) 18158 MightBeOdrUse = false; 18159 } 18160 SourceLocation Loc = 18161 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18162 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18163 } 18164 18165 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18166 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18167 for (VarDecl *VD : *E) 18168 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18169 } 18170 18171 /// Perform marking for a reference to an arbitrary declaration. It 18172 /// marks the declaration referenced, and performs odr-use checking for 18173 /// functions and variables. This method should not be used when building a 18174 /// normal expression which refers to a variable. 18175 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18176 bool MightBeOdrUse) { 18177 if (MightBeOdrUse) { 18178 if (auto *VD = dyn_cast<VarDecl>(D)) { 18179 MarkVariableReferenced(Loc, VD); 18180 return; 18181 } 18182 } 18183 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18184 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18185 return; 18186 } 18187 D->setReferenced(); 18188 } 18189 18190 namespace { 18191 // Mark all of the declarations used by a type as referenced. 18192 // FIXME: Not fully implemented yet! We need to have a better understanding 18193 // of when we're entering a context we should not recurse into. 18194 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18195 // TreeTransforms rebuilding the type in a new context. Rather than 18196 // duplicating the TreeTransform logic, we should consider reusing it here. 18197 // Currently that causes problems when rebuilding LambdaExprs. 18198 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18199 Sema &S; 18200 SourceLocation Loc; 18201 18202 public: 18203 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18204 18205 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18206 18207 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18208 }; 18209 } 18210 18211 bool MarkReferencedDecls::TraverseTemplateArgument( 18212 const TemplateArgument &Arg) { 18213 { 18214 // A non-type template argument is a constant-evaluated context. 18215 EnterExpressionEvaluationContext Evaluated( 18216 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18217 if (Arg.getKind() == TemplateArgument::Declaration) { 18218 if (Decl *D = Arg.getAsDecl()) 18219 S.MarkAnyDeclReferenced(Loc, D, true); 18220 } else if (Arg.getKind() == TemplateArgument::Expression) { 18221 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18222 } 18223 } 18224 18225 return Inherited::TraverseTemplateArgument(Arg); 18226 } 18227 18228 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18229 MarkReferencedDecls Marker(*this, Loc); 18230 Marker.TraverseType(T); 18231 } 18232 18233 namespace { 18234 /// Helper class that marks all of the declarations referenced by 18235 /// potentially-evaluated subexpressions as "referenced". 18236 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18237 public: 18238 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18239 bool SkipLocalVariables; 18240 18241 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18242 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18243 18244 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18245 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18246 } 18247 18248 void VisitDeclRefExpr(DeclRefExpr *E) { 18249 // If we were asked not to visit local variables, don't. 18250 if (SkipLocalVariables) { 18251 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18252 if (VD->hasLocalStorage()) 18253 return; 18254 } 18255 S.MarkDeclRefReferenced(E); 18256 } 18257 18258 void VisitMemberExpr(MemberExpr *E) { 18259 S.MarkMemberReferenced(E); 18260 Visit(E->getBase()); 18261 } 18262 }; 18263 } // namespace 18264 18265 /// Mark any declarations that appear within this expression or any 18266 /// potentially-evaluated subexpressions as "referenced". 18267 /// 18268 /// \param SkipLocalVariables If true, don't mark local variables as 18269 /// 'referenced'. 18270 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18271 bool SkipLocalVariables) { 18272 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18273 } 18274 18275 /// Emit a diagnostic that describes an effect on the run-time behavior 18276 /// of the program being compiled. 18277 /// 18278 /// This routine emits the given diagnostic when the code currently being 18279 /// type-checked is "potentially evaluated", meaning that there is a 18280 /// possibility that the code will actually be executable. Code in sizeof() 18281 /// expressions, code used only during overload resolution, etc., are not 18282 /// potentially evaluated. This routine will suppress such diagnostics or, 18283 /// in the absolutely nutty case of potentially potentially evaluated 18284 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18285 /// later. 18286 /// 18287 /// This routine should be used for all diagnostics that describe the run-time 18288 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18289 /// Failure to do so will likely result in spurious diagnostics or failures 18290 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18291 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18292 const PartialDiagnostic &PD) { 18293 switch (ExprEvalContexts.back().Context) { 18294 case ExpressionEvaluationContext::Unevaluated: 18295 case ExpressionEvaluationContext::UnevaluatedList: 18296 case ExpressionEvaluationContext::UnevaluatedAbstract: 18297 case ExpressionEvaluationContext::DiscardedStatement: 18298 // The argument will never be evaluated, so don't complain. 18299 break; 18300 18301 case ExpressionEvaluationContext::ConstantEvaluated: 18302 // Relevant diagnostics should be produced by constant evaluation. 18303 break; 18304 18305 case ExpressionEvaluationContext::PotentiallyEvaluated: 18306 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18307 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18308 FunctionScopes.back()->PossiblyUnreachableDiags. 18309 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18310 return true; 18311 } 18312 18313 // The initializer of a constexpr variable or of the first declaration of a 18314 // static data member is not syntactically a constant evaluated constant, 18315 // but nonetheless is always required to be a constant expression, so we 18316 // can skip diagnosing. 18317 // FIXME: Using the mangling context here is a hack. 18318 if (auto *VD = dyn_cast_or_null<VarDecl>( 18319 ExprEvalContexts.back().ManglingContextDecl)) { 18320 if (VD->isConstexpr() || 18321 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18322 break; 18323 // FIXME: For any other kind of variable, we should build a CFG for its 18324 // initializer and check whether the context in question is reachable. 18325 } 18326 18327 Diag(Loc, PD); 18328 return true; 18329 } 18330 18331 return false; 18332 } 18333 18334 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18335 const PartialDiagnostic &PD) { 18336 return DiagRuntimeBehavior( 18337 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18338 } 18339 18340 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18341 CallExpr *CE, FunctionDecl *FD) { 18342 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18343 return false; 18344 18345 // If we're inside a decltype's expression, don't check for a valid return 18346 // type or construct temporaries until we know whether this is the last call. 18347 if (ExprEvalContexts.back().ExprContext == 18348 ExpressionEvaluationContextRecord::EK_Decltype) { 18349 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18350 return false; 18351 } 18352 18353 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18354 FunctionDecl *FD; 18355 CallExpr *CE; 18356 18357 public: 18358 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18359 : FD(FD), CE(CE) { } 18360 18361 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18362 if (!FD) { 18363 S.Diag(Loc, diag::err_call_incomplete_return) 18364 << T << CE->getSourceRange(); 18365 return; 18366 } 18367 18368 S.Diag(Loc, diag::err_call_function_incomplete_return) 18369 << CE->getSourceRange() << FD << T; 18370 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18371 << FD->getDeclName(); 18372 } 18373 } Diagnoser(FD, CE); 18374 18375 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18376 return true; 18377 18378 return false; 18379 } 18380 18381 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18382 // will prevent this condition from triggering, which is what we want. 18383 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18384 SourceLocation Loc; 18385 18386 unsigned diagnostic = diag::warn_condition_is_assignment; 18387 bool IsOrAssign = false; 18388 18389 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18390 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18391 return; 18392 18393 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18394 18395 // Greylist some idioms by putting them into a warning subcategory. 18396 if (ObjCMessageExpr *ME 18397 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18398 Selector Sel = ME->getSelector(); 18399 18400 // self = [<foo> init...] 18401 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18402 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18403 18404 // <foo> = [<bar> nextObject] 18405 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18406 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18407 } 18408 18409 Loc = Op->getOperatorLoc(); 18410 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18411 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18412 return; 18413 18414 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18415 Loc = Op->getOperatorLoc(); 18416 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18417 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18418 else { 18419 // Not an assignment. 18420 return; 18421 } 18422 18423 Diag(Loc, diagnostic) << E->getSourceRange(); 18424 18425 SourceLocation Open = E->getBeginLoc(); 18426 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18427 Diag(Loc, diag::note_condition_assign_silence) 18428 << FixItHint::CreateInsertion(Open, "(") 18429 << FixItHint::CreateInsertion(Close, ")"); 18430 18431 if (IsOrAssign) 18432 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18433 << FixItHint::CreateReplacement(Loc, "!="); 18434 else 18435 Diag(Loc, diag::note_condition_assign_to_comparison) 18436 << FixItHint::CreateReplacement(Loc, "=="); 18437 } 18438 18439 /// Redundant parentheses over an equality comparison can indicate 18440 /// that the user intended an assignment used as condition. 18441 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18442 // Don't warn if the parens came from a macro. 18443 SourceLocation parenLoc = ParenE->getBeginLoc(); 18444 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18445 return; 18446 // Don't warn for dependent expressions. 18447 if (ParenE->isTypeDependent()) 18448 return; 18449 18450 Expr *E = ParenE->IgnoreParens(); 18451 18452 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18453 if (opE->getOpcode() == BO_EQ && 18454 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18455 == Expr::MLV_Valid) { 18456 SourceLocation Loc = opE->getOperatorLoc(); 18457 18458 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18459 SourceRange ParenERange = ParenE->getSourceRange(); 18460 Diag(Loc, diag::note_equality_comparison_silence) 18461 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18462 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18463 Diag(Loc, diag::note_equality_comparison_to_assign) 18464 << FixItHint::CreateReplacement(Loc, "="); 18465 } 18466 } 18467 18468 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18469 bool IsConstexpr) { 18470 DiagnoseAssignmentAsCondition(E); 18471 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18472 DiagnoseEqualityWithExtraParens(parenE); 18473 18474 ExprResult result = CheckPlaceholderExpr(E); 18475 if (result.isInvalid()) return ExprError(); 18476 E = result.get(); 18477 18478 if (!E->isTypeDependent()) { 18479 if (getLangOpts().CPlusPlus) 18480 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18481 18482 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18483 if (ERes.isInvalid()) 18484 return ExprError(); 18485 E = ERes.get(); 18486 18487 QualType T = E->getType(); 18488 if (!T->isScalarType()) { // C99 6.8.4.1p1 18489 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18490 << T << E->getSourceRange(); 18491 return ExprError(); 18492 } 18493 CheckBoolLikeConversion(E, Loc); 18494 } 18495 18496 return E; 18497 } 18498 18499 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18500 Expr *SubExpr, ConditionKind CK) { 18501 // Empty conditions are valid in for-statements. 18502 if (!SubExpr) 18503 return ConditionResult(); 18504 18505 ExprResult Cond; 18506 switch (CK) { 18507 case ConditionKind::Boolean: 18508 Cond = CheckBooleanCondition(Loc, SubExpr); 18509 break; 18510 18511 case ConditionKind::ConstexprIf: 18512 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18513 break; 18514 18515 case ConditionKind::Switch: 18516 Cond = CheckSwitchCondition(Loc, SubExpr); 18517 break; 18518 } 18519 if (Cond.isInvalid()) { 18520 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18521 {SubExpr}); 18522 if (!Cond.get()) 18523 return ConditionError(); 18524 } 18525 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18526 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18527 if (!FullExpr.get()) 18528 return ConditionError(); 18529 18530 return ConditionResult(*this, nullptr, FullExpr, 18531 CK == ConditionKind::ConstexprIf); 18532 } 18533 18534 namespace { 18535 /// A visitor for rebuilding a call to an __unknown_any expression 18536 /// to have an appropriate type. 18537 struct RebuildUnknownAnyFunction 18538 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18539 18540 Sema &S; 18541 18542 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18543 18544 ExprResult VisitStmt(Stmt *S) { 18545 llvm_unreachable("unexpected statement!"); 18546 } 18547 18548 ExprResult VisitExpr(Expr *E) { 18549 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18550 << E->getSourceRange(); 18551 return ExprError(); 18552 } 18553 18554 /// Rebuild an expression which simply semantically wraps another 18555 /// expression which it shares the type and value kind of. 18556 template <class T> ExprResult rebuildSugarExpr(T *E) { 18557 ExprResult SubResult = Visit(E->getSubExpr()); 18558 if (SubResult.isInvalid()) return ExprError(); 18559 18560 Expr *SubExpr = SubResult.get(); 18561 E->setSubExpr(SubExpr); 18562 E->setType(SubExpr->getType()); 18563 E->setValueKind(SubExpr->getValueKind()); 18564 assert(E->getObjectKind() == OK_Ordinary); 18565 return E; 18566 } 18567 18568 ExprResult VisitParenExpr(ParenExpr *E) { 18569 return rebuildSugarExpr(E); 18570 } 18571 18572 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18573 return rebuildSugarExpr(E); 18574 } 18575 18576 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18577 ExprResult SubResult = Visit(E->getSubExpr()); 18578 if (SubResult.isInvalid()) return ExprError(); 18579 18580 Expr *SubExpr = SubResult.get(); 18581 E->setSubExpr(SubExpr); 18582 E->setType(S.Context.getPointerType(SubExpr->getType())); 18583 assert(E->getValueKind() == VK_RValue); 18584 assert(E->getObjectKind() == OK_Ordinary); 18585 return E; 18586 } 18587 18588 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18589 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18590 18591 E->setType(VD->getType()); 18592 18593 assert(E->getValueKind() == VK_RValue); 18594 if (S.getLangOpts().CPlusPlus && 18595 !(isa<CXXMethodDecl>(VD) && 18596 cast<CXXMethodDecl>(VD)->isInstance())) 18597 E->setValueKind(VK_LValue); 18598 18599 return E; 18600 } 18601 18602 ExprResult VisitMemberExpr(MemberExpr *E) { 18603 return resolveDecl(E, E->getMemberDecl()); 18604 } 18605 18606 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18607 return resolveDecl(E, E->getDecl()); 18608 } 18609 }; 18610 } 18611 18612 /// Given a function expression of unknown-any type, try to rebuild it 18613 /// to have a function type. 18614 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18615 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18616 if (Result.isInvalid()) return ExprError(); 18617 return S.DefaultFunctionArrayConversion(Result.get()); 18618 } 18619 18620 namespace { 18621 /// A visitor for rebuilding an expression of type __unknown_anytype 18622 /// into one which resolves the type directly on the referring 18623 /// expression. Strict preservation of the original source 18624 /// structure is not a goal. 18625 struct RebuildUnknownAnyExpr 18626 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18627 18628 Sema &S; 18629 18630 /// The current destination type. 18631 QualType DestType; 18632 18633 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18634 : S(S), DestType(CastType) {} 18635 18636 ExprResult VisitStmt(Stmt *S) { 18637 llvm_unreachable("unexpected statement!"); 18638 } 18639 18640 ExprResult VisitExpr(Expr *E) { 18641 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18642 << E->getSourceRange(); 18643 return ExprError(); 18644 } 18645 18646 ExprResult VisitCallExpr(CallExpr *E); 18647 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18648 18649 /// Rebuild an expression which simply semantically wraps another 18650 /// expression which it shares the type and value kind of. 18651 template <class T> ExprResult rebuildSugarExpr(T *E) { 18652 ExprResult SubResult = Visit(E->getSubExpr()); 18653 if (SubResult.isInvalid()) return ExprError(); 18654 Expr *SubExpr = SubResult.get(); 18655 E->setSubExpr(SubExpr); 18656 E->setType(SubExpr->getType()); 18657 E->setValueKind(SubExpr->getValueKind()); 18658 assert(E->getObjectKind() == OK_Ordinary); 18659 return E; 18660 } 18661 18662 ExprResult VisitParenExpr(ParenExpr *E) { 18663 return rebuildSugarExpr(E); 18664 } 18665 18666 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18667 return rebuildSugarExpr(E); 18668 } 18669 18670 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18671 const PointerType *Ptr = DestType->getAs<PointerType>(); 18672 if (!Ptr) { 18673 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18674 << E->getSourceRange(); 18675 return ExprError(); 18676 } 18677 18678 if (isa<CallExpr>(E->getSubExpr())) { 18679 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18680 << E->getSourceRange(); 18681 return ExprError(); 18682 } 18683 18684 assert(E->getValueKind() == VK_RValue); 18685 assert(E->getObjectKind() == OK_Ordinary); 18686 E->setType(DestType); 18687 18688 // Build the sub-expression as if it were an object of the pointee type. 18689 DestType = Ptr->getPointeeType(); 18690 ExprResult SubResult = Visit(E->getSubExpr()); 18691 if (SubResult.isInvalid()) return ExprError(); 18692 E->setSubExpr(SubResult.get()); 18693 return E; 18694 } 18695 18696 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18697 18698 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18699 18700 ExprResult VisitMemberExpr(MemberExpr *E) { 18701 return resolveDecl(E, E->getMemberDecl()); 18702 } 18703 18704 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18705 return resolveDecl(E, E->getDecl()); 18706 } 18707 }; 18708 } 18709 18710 /// Rebuilds a call expression which yielded __unknown_anytype. 18711 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18712 Expr *CalleeExpr = E->getCallee(); 18713 18714 enum FnKind { 18715 FK_MemberFunction, 18716 FK_FunctionPointer, 18717 FK_BlockPointer 18718 }; 18719 18720 FnKind Kind; 18721 QualType CalleeType = CalleeExpr->getType(); 18722 if (CalleeType == S.Context.BoundMemberTy) { 18723 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18724 Kind = FK_MemberFunction; 18725 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18726 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18727 CalleeType = Ptr->getPointeeType(); 18728 Kind = FK_FunctionPointer; 18729 } else { 18730 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18731 Kind = FK_BlockPointer; 18732 } 18733 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18734 18735 // Verify that this is a legal result type of a function. 18736 if (DestType->isArrayType() || DestType->isFunctionType()) { 18737 unsigned diagID = diag::err_func_returning_array_function; 18738 if (Kind == FK_BlockPointer) 18739 diagID = diag::err_block_returning_array_function; 18740 18741 S.Diag(E->getExprLoc(), diagID) 18742 << DestType->isFunctionType() << DestType; 18743 return ExprError(); 18744 } 18745 18746 // Otherwise, go ahead and set DestType as the call's result. 18747 E->setType(DestType.getNonLValueExprType(S.Context)); 18748 E->setValueKind(Expr::getValueKindForType(DestType)); 18749 assert(E->getObjectKind() == OK_Ordinary); 18750 18751 // Rebuild the function type, replacing the result type with DestType. 18752 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18753 if (Proto) { 18754 // __unknown_anytype(...) is a special case used by the debugger when 18755 // it has no idea what a function's signature is. 18756 // 18757 // We want to build this call essentially under the K&R 18758 // unprototyped rules, but making a FunctionNoProtoType in C++ 18759 // would foul up all sorts of assumptions. However, we cannot 18760 // simply pass all arguments as variadic arguments, nor can we 18761 // portably just call the function under a non-variadic type; see 18762 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18763 // However, it turns out that in practice it is generally safe to 18764 // call a function declared as "A foo(B,C,D);" under the prototype 18765 // "A foo(B,C,D,...);". The only known exception is with the 18766 // Windows ABI, where any variadic function is implicitly cdecl 18767 // regardless of its normal CC. Therefore we change the parameter 18768 // types to match the types of the arguments. 18769 // 18770 // This is a hack, but it is far superior to moving the 18771 // corresponding target-specific code from IR-gen to Sema/AST. 18772 18773 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18774 SmallVector<QualType, 8> ArgTypes; 18775 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18776 ArgTypes.reserve(E->getNumArgs()); 18777 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18778 Expr *Arg = E->getArg(i); 18779 QualType ArgType = Arg->getType(); 18780 if (E->isLValue()) { 18781 ArgType = S.Context.getLValueReferenceType(ArgType); 18782 } else if (E->isXValue()) { 18783 ArgType = S.Context.getRValueReferenceType(ArgType); 18784 } 18785 ArgTypes.push_back(ArgType); 18786 } 18787 ParamTypes = ArgTypes; 18788 } 18789 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18790 Proto->getExtProtoInfo()); 18791 } else { 18792 DestType = S.Context.getFunctionNoProtoType(DestType, 18793 FnType->getExtInfo()); 18794 } 18795 18796 // Rebuild the appropriate pointer-to-function type. 18797 switch (Kind) { 18798 case FK_MemberFunction: 18799 // Nothing to do. 18800 break; 18801 18802 case FK_FunctionPointer: 18803 DestType = S.Context.getPointerType(DestType); 18804 break; 18805 18806 case FK_BlockPointer: 18807 DestType = S.Context.getBlockPointerType(DestType); 18808 break; 18809 } 18810 18811 // Finally, we can recurse. 18812 ExprResult CalleeResult = Visit(CalleeExpr); 18813 if (!CalleeResult.isUsable()) return ExprError(); 18814 E->setCallee(CalleeResult.get()); 18815 18816 // Bind a temporary if necessary. 18817 return S.MaybeBindToTemporary(E); 18818 } 18819 18820 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18821 // Verify that this is a legal result type of a call. 18822 if (DestType->isArrayType() || DestType->isFunctionType()) { 18823 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18824 << DestType->isFunctionType() << DestType; 18825 return ExprError(); 18826 } 18827 18828 // Rewrite the method result type if available. 18829 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18830 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18831 Method->setReturnType(DestType); 18832 } 18833 18834 // Change the type of the message. 18835 E->setType(DestType.getNonReferenceType()); 18836 E->setValueKind(Expr::getValueKindForType(DestType)); 18837 18838 return S.MaybeBindToTemporary(E); 18839 } 18840 18841 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18842 // The only case we should ever see here is a function-to-pointer decay. 18843 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18844 assert(E->getValueKind() == VK_RValue); 18845 assert(E->getObjectKind() == OK_Ordinary); 18846 18847 E->setType(DestType); 18848 18849 // Rebuild the sub-expression as the pointee (function) type. 18850 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18851 18852 ExprResult Result = Visit(E->getSubExpr()); 18853 if (!Result.isUsable()) return ExprError(); 18854 18855 E->setSubExpr(Result.get()); 18856 return E; 18857 } else if (E->getCastKind() == CK_LValueToRValue) { 18858 assert(E->getValueKind() == VK_RValue); 18859 assert(E->getObjectKind() == OK_Ordinary); 18860 18861 assert(isa<BlockPointerType>(E->getType())); 18862 18863 E->setType(DestType); 18864 18865 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18866 DestType = S.Context.getLValueReferenceType(DestType); 18867 18868 ExprResult Result = Visit(E->getSubExpr()); 18869 if (!Result.isUsable()) return ExprError(); 18870 18871 E->setSubExpr(Result.get()); 18872 return E; 18873 } else { 18874 llvm_unreachable("Unhandled cast type!"); 18875 } 18876 } 18877 18878 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18879 ExprValueKind ValueKind = VK_LValue; 18880 QualType Type = DestType; 18881 18882 // We know how to make this work for certain kinds of decls: 18883 18884 // - functions 18885 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18886 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18887 DestType = Ptr->getPointeeType(); 18888 ExprResult Result = resolveDecl(E, VD); 18889 if (Result.isInvalid()) return ExprError(); 18890 return S.ImpCastExprToType(Result.get(), Type, 18891 CK_FunctionToPointerDecay, VK_RValue); 18892 } 18893 18894 if (!Type->isFunctionType()) { 18895 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18896 << VD << E->getSourceRange(); 18897 return ExprError(); 18898 } 18899 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18900 // We must match the FunctionDecl's type to the hack introduced in 18901 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18902 // type. See the lengthy commentary in that routine. 18903 QualType FDT = FD->getType(); 18904 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18905 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18906 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18907 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18908 SourceLocation Loc = FD->getLocation(); 18909 FunctionDecl *NewFD = FunctionDecl::Create( 18910 S.Context, FD->getDeclContext(), Loc, Loc, 18911 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18912 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18913 /*ConstexprKind*/ CSK_unspecified); 18914 18915 if (FD->getQualifier()) 18916 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18917 18918 SmallVector<ParmVarDecl*, 16> Params; 18919 for (const auto &AI : FT->param_types()) { 18920 ParmVarDecl *Param = 18921 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18922 Param->setScopeInfo(0, Params.size()); 18923 Params.push_back(Param); 18924 } 18925 NewFD->setParams(Params); 18926 DRE->setDecl(NewFD); 18927 VD = DRE->getDecl(); 18928 } 18929 } 18930 18931 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18932 if (MD->isInstance()) { 18933 ValueKind = VK_RValue; 18934 Type = S.Context.BoundMemberTy; 18935 } 18936 18937 // Function references aren't l-values in C. 18938 if (!S.getLangOpts().CPlusPlus) 18939 ValueKind = VK_RValue; 18940 18941 // - variables 18942 } else if (isa<VarDecl>(VD)) { 18943 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18944 Type = RefTy->getPointeeType(); 18945 } else if (Type->isFunctionType()) { 18946 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18947 << VD << E->getSourceRange(); 18948 return ExprError(); 18949 } 18950 18951 // - nothing else 18952 } else { 18953 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18954 << VD << E->getSourceRange(); 18955 return ExprError(); 18956 } 18957 18958 // Modifying the declaration like this is friendly to IR-gen but 18959 // also really dangerous. 18960 VD->setType(DestType); 18961 E->setType(Type); 18962 E->setValueKind(ValueKind); 18963 return E; 18964 } 18965 18966 /// Check a cast of an unknown-any type. We intentionally only 18967 /// trigger this for C-style casts. 18968 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18969 Expr *CastExpr, CastKind &CastKind, 18970 ExprValueKind &VK, CXXCastPath &Path) { 18971 // The type we're casting to must be either void or complete. 18972 if (!CastType->isVoidType() && 18973 RequireCompleteType(TypeRange.getBegin(), CastType, 18974 diag::err_typecheck_cast_to_incomplete)) 18975 return ExprError(); 18976 18977 // Rewrite the casted expression from scratch. 18978 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18979 if (!result.isUsable()) return ExprError(); 18980 18981 CastExpr = result.get(); 18982 VK = CastExpr->getValueKind(); 18983 CastKind = CK_NoOp; 18984 18985 return CastExpr; 18986 } 18987 18988 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18989 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18990 } 18991 18992 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18993 Expr *arg, QualType ¶mType) { 18994 // If the syntactic form of the argument is not an explicit cast of 18995 // any sort, just do default argument promotion. 18996 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18997 if (!castArg) { 18998 ExprResult result = DefaultArgumentPromotion(arg); 18999 if (result.isInvalid()) return ExprError(); 19000 paramType = result.get()->getType(); 19001 return result; 19002 } 19003 19004 // Otherwise, use the type that was written in the explicit cast. 19005 assert(!arg->hasPlaceholderType()); 19006 paramType = castArg->getTypeAsWritten(); 19007 19008 // Copy-initialize a parameter of that type. 19009 InitializedEntity entity = 19010 InitializedEntity::InitializeParameter(Context, paramType, 19011 /*consumed*/ false); 19012 return PerformCopyInitialization(entity, callLoc, arg); 19013 } 19014 19015 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19016 Expr *orig = E; 19017 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19018 while (true) { 19019 E = E->IgnoreParenImpCasts(); 19020 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19021 E = call->getCallee(); 19022 diagID = diag::err_uncasted_call_of_unknown_any; 19023 } else { 19024 break; 19025 } 19026 } 19027 19028 SourceLocation loc; 19029 NamedDecl *d; 19030 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19031 loc = ref->getLocation(); 19032 d = ref->getDecl(); 19033 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19034 loc = mem->getMemberLoc(); 19035 d = mem->getMemberDecl(); 19036 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19037 diagID = diag::err_uncasted_call_of_unknown_any; 19038 loc = msg->getSelectorStartLoc(); 19039 d = msg->getMethodDecl(); 19040 if (!d) { 19041 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19042 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19043 << orig->getSourceRange(); 19044 return ExprError(); 19045 } 19046 } else { 19047 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19048 << E->getSourceRange(); 19049 return ExprError(); 19050 } 19051 19052 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19053 19054 // Never recoverable. 19055 return ExprError(); 19056 } 19057 19058 /// Check for operands with placeholder types and complain if found. 19059 /// Returns ExprError() if there was an error and no recovery was possible. 19060 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19061 if (!getLangOpts().CPlusPlus) { 19062 // C cannot handle TypoExpr nodes on either side of a binop because it 19063 // doesn't handle dependent types properly, so make sure any TypoExprs have 19064 // been dealt with before checking the operands. 19065 ExprResult Result = CorrectDelayedTyposInExpr(E); 19066 if (!Result.isUsable()) return ExprError(); 19067 E = Result.get(); 19068 } 19069 19070 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19071 if (!placeholderType) return E; 19072 19073 switch (placeholderType->getKind()) { 19074 19075 // Overloaded expressions. 19076 case BuiltinType::Overload: { 19077 // Try to resolve a single function template specialization. 19078 // This is obligatory. 19079 ExprResult Result = E; 19080 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19081 return Result; 19082 19083 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19084 // leaves Result unchanged on failure. 19085 Result = E; 19086 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19087 return Result; 19088 19089 // If that failed, try to recover with a call. 19090 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19091 /*complain*/ true); 19092 return Result; 19093 } 19094 19095 // Bound member functions. 19096 case BuiltinType::BoundMember: { 19097 ExprResult result = E; 19098 const Expr *BME = E->IgnoreParens(); 19099 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19100 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19101 if (isa<CXXPseudoDestructorExpr>(BME)) { 19102 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19103 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19104 if (ME->getMemberNameInfo().getName().getNameKind() == 19105 DeclarationName::CXXDestructorName) 19106 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19107 } 19108 tryToRecoverWithCall(result, PD, 19109 /*complain*/ true); 19110 return result; 19111 } 19112 19113 // ARC unbridged casts. 19114 case BuiltinType::ARCUnbridgedCast: { 19115 Expr *realCast = stripARCUnbridgedCast(E); 19116 diagnoseARCUnbridgedCast(realCast); 19117 return realCast; 19118 } 19119 19120 // Expressions of unknown type. 19121 case BuiltinType::UnknownAny: 19122 return diagnoseUnknownAnyExpr(*this, E); 19123 19124 // Pseudo-objects. 19125 case BuiltinType::PseudoObject: 19126 return checkPseudoObjectRValue(E); 19127 19128 case BuiltinType::BuiltinFn: { 19129 // Accept __noop without parens by implicitly converting it to a call expr. 19130 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19131 if (DRE) { 19132 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19133 if (FD->getBuiltinID() == Builtin::BI__noop) { 19134 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19135 CK_BuiltinFnToFnPtr) 19136 .get(); 19137 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19138 VK_RValue, SourceLocation(), 19139 FPOptionsOverride()); 19140 } 19141 } 19142 19143 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19144 return ExprError(); 19145 } 19146 19147 case BuiltinType::IncompleteMatrixIdx: 19148 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19149 ->getRowIdx() 19150 ->getBeginLoc(), 19151 diag::err_matrix_incomplete_index); 19152 return ExprError(); 19153 19154 // Expressions of unknown type. 19155 case BuiltinType::OMPArraySection: 19156 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19157 return ExprError(); 19158 19159 // Expressions of unknown type. 19160 case BuiltinType::OMPArrayShaping: 19161 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19162 19163 case BuiltinType::OMPIterator: 19164 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19165 19166 // Everything else should be impossible. 19167 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19168 case BuiltinType::Id: 19169 #include "clang/Basic/OpenCLImageTypes.def" 19170 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19171 case BuiltinType::Id: 19172 #include "clang/Basic/OpenCLExtensionTypes.def" 19173 #define SVE_TYPE(Name, Id, SingletonId) \ 19174 case BuiltinType::Id: 19175 #include "clang/Basic/AArch64SVEACLETypes.def" 19176 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19177 #define PLACEHOLDER_TYPE(Id, SingletonId) 19178 #include "clang/AST/BuiltinTypes.def" 19179 break; 19180 } 19181 19182 llvm_unreachable("invalid placeholder type!"); 19183 } 19184 19185 bool Sema::CheckCaseExpression(Expr *E) { 19186 if (E->isTypeDependent()) 19187 return true; 19188 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19189 return E->getType()->isIntegralOrEnumerationType(); 19190 return false; 19191 } 19192 19193 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19194 ExprResult 19195 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19196 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19197 "Unknown Objective-C Boolean value!"); 19198 QualType BoolT = Context.ObjCBuiltinBoolTy; 19199 if (!Context.getBOOLDecl()) { 19200 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19201 Sema::LookupOrdinaryName); 19202 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19203 NamedDecl *ND = Result.getFoundDecl(); 19204 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19205 Context.setBOOLDecl(TD); 19206 } 19207 } 19208 if (Context.getBOOLDecl()) 19209 BoolT = Context.getBOOLType(); 19210 return new (Context) 19211 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19212 } 19213 19214 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19215 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19216 SourceLocation RParen) { 19217 19218 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19219 19220 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19221 return Spec.getPlatform() == Platform; 19222 }); 19223 19224 VersionTuple Version; 19225 if (Spec != AvailSpecs.end()) 19226 Version = Spec->getVersion(); 19227 19228 // The use of `@available` in the enclosing function should be analyzed to 19229 // warn when it's used inappropriately (i.e. not if(@available)). 19230 if (getCurFunctionOrMethodDecl()) 19231 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19232 else if (getCurBlock() || getCurLambda()) 19233 getCurFunction()->HasPotentialAvailabilityViolations = true; 19234 19235 return new (Context) 19236 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19237 } 19238 19239 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19240 ArrayRef<Expr *> SubExprs, QualType T) { 19241 if (!Context.getLangOpts().RecoveryAST) 19242 return ExprError(); 19243 19244 if (isSFINAEContext()) 19245 return ExprError(); 19246 19247 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19248 // We don't know the concrete type, fallback to dependent type. 19249 T = Context.DependentTy; 19250 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19251 } 19252