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/FixedPoint.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 298 return true; 299 } 300 301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 302 // Lambdas are only default-constructible or assignable in C++2a onwards. 303 if (MD->getParent()->isLambda() && 304 ((isa<CXXConstructorDecl>(MD) && 305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 308 << !isa<CXXConstructorDecl>(MD); 309 } 310 } 311 312 auto getReferencedObjCProp = [](const NamedDecl *D) -> 313 const ObjCPropertyDecl * { 314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 315 return MD->findPropertyDecl(); 316 return nullptr; 317 }; 318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 320 return true; 321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 322 return true; 323 } 324 325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 326 // Only the variables omp_in and omp_out are allowed in the combiner. 327 // Only the variables omp_priv and omp_orig are allowed in the 328 // initializer-clause. 329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 331 isa<VarDecl>(D)) { 332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 333 << getCurFunction()->HasOMPDeclareReductionCombiner; 334 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 335 return true; 336 } 337 338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 339 // List-items in map clauses on this construct may only refer to the declared 340 // variable var and entities that could be referenced by a procedure defined 341 // at the same location 342 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 343 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 344 isa<VarDecl>(D)) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << DMD->getVarName().getAsString(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 359 if (const auto *VD = dyn_cast<ValueDecl>(D)) 360 checkDeviceDecl(VD, Loc); 361 362 if (!Context.getTargetInfo().isTLSSupported()) 363 if (const auto *VD = dyn_cast<VarDecl>(D)) 364 if (VD->getTLSKind() != VarDecl::TLS_None) 365 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 366 } 367 368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 369 !isUnevaluatedContext()) { 370 // C++ [expr.prim.req.nested] p3 371 // A local parameter shall only appear as an unevaluated operand 372 // (Clause 8) within the constraint-expression. 373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 374 << D; 375 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 376 return true; 377 } 378 379 return false; 380 } 381 382 /// DiagnoseSentinelCalls - This routine checks whether a call or 383 /// message-send is to a declaration with the sentinel attribute, and 384 /// if so, it checks that the requirements of the sentinel are 385 /// satisfied. 386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 387 ArrayRef<Expr *> Args) { 388 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 389 if (!attr) 390 return; 391 392 // The number of formal parameters of the declaration. 393 unsigned numFormalParams; 394 395 // The kind of declaration. This is also an index into a %select in 396 // the diagnostic. 397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 398 399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 400 numFormalParams = MD->param_size(); 401 calleeType = CT_Method; 402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 403 numFormalParams = FD->param_size(); 404 calleeType = CT_Function; 405 } else if (isa<VarDecl>(D)) { 406 QualType type = cast<ValueDecl>(D)->getType(); 407 const FunctionType *fn = nullptr; 408 if (const PointerType *ptr = type->getAs<PointerType>()) { 409 fn = ptr->getPointeeType()->getAs<FunctionType>(); 410 if (!fn) return; 411 calleeType = CT_Function; 412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 413 fn = ptr->getPointeeType()->castAs<FunctionType>(); 414 calleeType = CT_Block; 415 } else { 416 return; 417 } 418 419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 420 numFormalParams = proto->getNumParams(); 421 } else { 422 numFormalParams = 0; 423 } 424 } else { 425 return; 426 } 427 428 // "nullPos" is the number of formal parameters at the end which 429 // effectively count as part of the variadic arguments. This is 430 // useful if you would prefer to not have *any* formal parameters, 431 // but the language forces you to have at least one. 432 unsigned nullPos = attr->getNullPos(); 433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 435 436 // The number of arguments which should follow the sentinel. 437 unsigned numArgsAfterSentinel = attr->getSentinel(); 438 439 // If there aren't enough arguments for all the formal parameters, 440 // the sentinel, and the args after the sentinel, complain. 441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 444 return; 445 } 446 447 // Otherwise, find the sentinel expression. 448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 449 if (!sentinelExpr) return; 450 if (sentinelExpr->isValueDependent()) return; 451 if (Context.isSentinelNullExpr(sentinelExpr)) return; 452 453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 454 // or 'NULL' if those are actually defined in the context. Only use 455 // 'nil' for ObjC methods, where it's much more likely that the 456 // variadic arguments form a list of object pointers. 457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 458 std::string NullValue; 459 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 460 NullValue = "nil"; 461 else if (getLangOpts().CPlusPlus11) 462 NullValue = "nullptr"; 463 else if (PP.isMacroDefined("NULL")) 464 NullValue = "NULL"; 465 else 466 NullValue = "(void*) 0"; 467 468 if (MissingNilLoc.isInvalid()) 469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 470 else 471 Diag(MissingNilLoc, diag::warn_missing_sentinel) 472 << int(calleeType) 473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 475 } 476 477 SourceRange Sema::getExprRange(Expr *E) const { 478 return E ? E->getSourceRange() : SourceRange(); 479 } 480 481 //===----------------------------------------------------------------------===// 482 // Standard Promotions and Conversions 483 //===----------------------------------------------------------------------===// 484 485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 487 // Handle any placeholder expressions which made it here. 488 if (E->getType()->isPlaceholderType()) { 489 ExprResult result = CheckPlaceholderExpr(E); 490 if (result.isInvalid()) return ExprError(); 491 E = result.get(); 492 } 493 494 QualType Ty = E->getType(); 495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 496 497 if (Ty->isFunctionType()) { 498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 501 return ExprError(); 502 503 E = ImpCastExprToType(E, Context.getPointerType(Ty), 504 CK_FunctionToPointerDecay).get(); 505 } else if (Ty->isArrayType()) { 506 // In C90 mode, arrays only promote to pointers if the array expression is 507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 508 // type 'array of type' is converted to an expression that has type 'pointer 509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 510 // that has type 'array of type' ...". The relevant change is "an lvalue" 511 // (C90) to "an expression" (C99). 512 // 513 // C++ 4.2p1: 514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 515 // T" can be converted to an rvalue of type "pointer to T". 516 // 517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 519 CK_ArrayToPointerDecay).get(); 520 } 521 return E; 522 } 523 524 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 525 // Check to see if we are dereferencing a null pointer. If so, 526 // and if not volatile-qualified, this is undefined behavior that the 527 // optimizer will delete, so warn about it. People sometimes try to use this 528 // to get a deterministic trap and are surprised by clang's behavior. This 529 // only handles the pattern "*null", which is a very syntactic check. 530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 531 if (UO && UO->getOpcode() == UO_Deref && 532 UO->getSubExpr()->getType()->isPointerType()) { 533 const LangAS AS = 534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 535 if ((!isTargetAddressSpace(AS) || 536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 538 S.Context, Expr::NPC_ValueDependentIsNotNull) && 539 !UO->getType().isVolatileQualified()) { 540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 541 S.PDiag(diag::warn_indirection_through_null) 542 << UO->getSubExpr()->getSourceRange()); 543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 544 S.PDiag(diag::note_indirection_through_null)); 545 } 546 } 547 } 548 549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 550 SourceLocation AssignLoc, 551 const Expr* RHS) { 552 const ObjCIvarDecl *IV = OIRE->getDecl(); 553 if (!IV) 554 return; 555 556 DeclarationName MemberName = IV->getDeclName(); 557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 558 if (!Member || !Member->isStr("isa")) 559 return; 560 561 const Expr *Base = OIRE->getBase(); 562 QualType BaseType = Base->getType(); 563 if (OIRE->isArrow()) 564 BaseType = BaseType->getPointeeType(); 565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 567 ObjCInterfaceDecl *ClassDeclared = nullptr; 568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 569 if (!ClassDeclared->getSuperClass() 570 && (*ClassDeclared->ivar_begin()) == IV) { 571 if (RHS) { 572 NamedDecl *ObjectSetClass = 573 S.LookupSingleName(S.TUScope, 574 &S.Context.Idents.get("object_setClass"), 575 SourceLocation(), S.LookupOrdinaryName); 576 if (ObjectSetClass) { 577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 580 "object_setClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 583 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 584 } 585 else 586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 587 } else { 588 NamedDecl *ObjectGetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_getClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectGetClass) 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_getClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 598 else 599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 600 } 601 S.Diag(IV->getLocation(), diag::note_ivar_decl); 602 } 603 } 604 } 605 606 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 607 // Handle any placeholder expressions which made it here. 608 if (E->getType()->isPlaceholderType()) { 609 ExprResult result = CheckPlaceholderExpr(E); 610 if (result.isInvalid()) return ExprError(); 611 E = result.get(); 612 } 613 614 // C++ [conv.lval]p1: 615 // A glvalue of a non-function, non-array type T can be 616 // converted to a prvalue. 617 if (!E->isGLValue()) return E; 618 619 QualType T = E->getType(); 620 assert(!T.isNull() && "r-value conversion on typeless expression?"); 621 622 // lvalue-to-rvalue conversion cannot be applied to function or array types. 623 if (T->isFunctionType() || T->isArrayType()) 624 return E; 625 626 // We don't want to throw lvalue-to-rvalue casts on top of 627 // expressions of certain types in C++. 628 if (getLangOpts().CPlusPlus && 629 (E->getType() == Context.OverloadTy || 630 T->isDependentType() || 631 T->isRecordType())) 632 return E; 633 634 // The C standard is actually really unclear on this point, and 635 // DR106 tells us what the result should be but not why. It's 636 // generally best to say that void types just doesn't undergo 637 // lvalue-to-rvalue at all. Note that expressions of unqualified 638 // 'void' type are never l-values, but qualified void can be. 639 if (T->isVoidType()) 640 return E; 641 642 // OpenCL usually rejects direct accesses to values of 'half' type. 643 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 644 T->isHalfType()) { 645 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 646 << 0 << T; 647 return ExprError(); 648 } 649 650 CheckForNullPointerDereference(*this, E); 651 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 652 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 653 &Context.Idents.get("object_getClass"), 654 SourceLocation(), LookupOrdinaryName); 655 if (ObjectGetClass) 656 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 657 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 658 << FixItHint::CreateReplacement( 659 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 660 else 661 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 662 } 663 else if (const ObjCIvarRefExpr *OIRE = 664 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 665 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 666 667 // C++ [conv.lval]p1: 668 // [...] If T is a non-class type, the type of the prvalue is the 669 // cv-unqualified version of T. Otherwise, the type of the 670 // rvalue is T. 671 // 672 // C99 6.3.2.1p2: 673 // If the lvalue has qualified type, the value has the unqualified 674 // version of the type of the lvalue; otherwise, the value has the 675 // type of the lvalue. 676 if (T.hasQualifiers()) 677 T = T.getUnqualifiedType(); 678 679 // Under the MS ABI, lock down the inheritance model now. 680 if (T->isMemberPointerType() && 681 Context.getTargetInfo().getCXXABI().isMicrosoft()) 682 (void)isCompleteType(E->getExprLoc(), T); 683 684 ExprResult Res = CheckLValueToRValueConversionOperand(E); 685 if (Res.isInvalid()) 686 return Res; 687 E = Res.get(); 688 689 // Loading a __weak object implicitly retains the value, so we need a cleanup to 690 // balance that. 691 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 692 Cleanup.setExprNeedsCleanups(true); 693 694 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 695 Cleanup.setExprNeedsCleanups(true); 696 697 // C++ [conv.lval]p3: 698 // If T is cv std::nullptr_t, the result is a null pointer constant. 699 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 700 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 701 702 // C11 6.3.2.1p2: 703 // ... if the lvalue has atomic type, the value has the non-atomic version 704 // of the type of the lvalue ... 705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 706 T = Atomic->getValueType().getUnqualifiedType(); 707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 708 nullptr, VK_RValue); 709 } 710 711 return Res; 712 } 713 714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 716 if (Res.isInvalid()) 717 return ExprError(); 718 Res = DefaultLvalueConversion(Res.get()); 719 if (Res.isInvalid()) 720 return ExprError(); 721 return Res; 722 } 723 724 /// CallExprUnaryConversions - a special case of an unary conversion 725 /// performed on a function designator of a call expression. 726 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 727 QualType Ty = E->getType(); 728 ExprResult Res = E; 729 // Only do implicit cast for a function type, but not for a pointer 730 // to function type. 731 if (Ty->isFunctionType()) { 732 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 733 CK_FunctionToPointerDecay); 734 if (Res.isInvalid()) 735 return ExprError(); 736 } 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res.get(); 741 } 742 743 /// UsualUnaryConversions - Performs various conversions that are common to most 744 /// operators (C99 6.3). The conversions of array and function types are 745 /// sometimes suppressed. For example, the array->pointer conversion doesn't 746 /// apply if the array is an argument to the sizeof or address (&) operators. 747 /// In these instances, this routine should *not* be called. 748 ExprResult Sema::UsualUnaryConversions(Expr *E) { 749 // First, convert to an r-value. 750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 751 if (Res.isInvalid()) 752 return ExprError(); 753 E = Res.get(); 754 755 QualType Ty = E->getType(); 756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 757 758 // Half FP have to be promoted to float unless it is natively supported 759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 761 762 // Try to perform integral promotions if the object has a theoretically 763 // promotable type. 764 if (Ty->isIntegralOrUnscopedEnumerationType()) { 765 // C99 6.3.1.1p2: 766 // 767 // The following may be used in an expression wherever an int or 768 // unsigned int may be used: 769 // - an object or expression with an integer type whose integer 770 // conversion rank is less than or equal to the rank of int 771 // and unsigned int. 772 // - A bit-field of type _Bool, int, signed int, or unsigned int. 773 // 774 // If an int can represent all values of the original type, the 775 // value is converted to an int; otherwise, it is converted to an 776 // unsigned int. These are called the integer promotions. All 777 // other types are unchanged by the integer promotions. 778 779 QualType PTy = Context.isPromotableBitField(E); 780 if (!PTy.isNull()) { 781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 782 return E; 783 } 784 if (Ty->isPromotableIntegerType()) { 785 QualType PT = Context.getPromotedIntegerType(Ty); 786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 787 return E; 788 } 789 } 790 return E; 791 } 792 793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 794 /// do not have a prototype. Arguments that have type float or __fp16 795 /// are promoted to double. All other argument types are converted by 796 /// UsualUnaryConversions(). 797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 798 QualType Ty = E->getType(); 799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 800 801 ExprResult Res = UsualUnaryConversions(E); 802 if (Res.isInvalid()) 803 return ExprError(); 804 E = Res.get(); 805 806 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 807 // promote to double. 808 // Note that default argument promotion applies only to float (and 809 // half/fp16); it does not apply to _Float16. 810 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 811 if (BTy && (BTy->getKind() == BuiltinType::Half || 812 BTy->getKind() == BuiltinType::Float)) { 813 if (getLangOpts().OpenCL && 814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 815 if (BTy->getKind() == BuiltinType::Half) { 816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 817 } 818 } else { 819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 820 } 821 } 822 823 // C++ performs lvalue-to-rvalue conversion as a default argument 824 // promotion, even on class types, but note: 825 // C++11 [conv.lval]p2: 826 // When an lvalue-to-rvalue conversion occurs in an unevaluated 827 // operand or a subexpression thereof the value contained in the 828 // referenced object is not accessed. Otherwise, if the glvalue 829 // has a class type, the conversion copy-initializes a temporary 830 // of type T from the glvalue and the result of the conversion 831 // is a prvalue for the temporary. 832 // FIXME: add some way to gate this entire thing for correctness in 833 // potentially potentially evaluated contexts. 834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 835 ExprResult Temp = PerformCopyInitialization( 836 InitializedEntity::InitializeTemporary(E->getType()), 837 E->getExprLoc(), E); 838 if (Temp.isInvalid()) 839 return ExprError(); 840 E = Temp.get(); 841 } 842 843 return E; 844 } 845 846 /// Determine the degree of POD-ness for an expression. 847 /// Incomplete types are considered POD, since this check can be performed 848 /// when we're in an unevaluated context. 849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 850 if (Ty->isIncompleteType()) { 851 // C++11 [expr.call]p7: 852 // After these conversions, if the argument does not have arithmetic, 853 // enumeration, pointer, pointer to member, or class type, the program 854 // is ill-formed. 855 // 856 // Since we've already performed array-to-pointer and function-to-pointer 857 // decay, the only such type in C++ is cv void. This also handles 858 // initializer lists as variadic arguments. 859 if (Ty->isVoidType()) 860 return VAK_Invalid; 861 862 if (Ty->isObjCObjectType()) 863 return VAK_Invalid; 864 return VAK_Valid; 865 } 866 867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 868 return VAK_Invalid; 869 870 if (Ty.isCXX98PODType(Context)) 871 return VAK_Valid; 872 873 // C++11 [expr.call]p7: 874 // Passing a potentially-evaluated argument of class type (Clause 9) 875 // having a non-trivial copy constructor, a non-trivial move constructor, 876 // or a non-trivial destructor, with no corresponding parameter, 877 // is conditionally-supported with implementation-defined semantics. 878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 880 if (!Record->hasNonTrivialCopyConstructor() && 881 !Record->hasNonTrivialMoveConstructor() && 882 !Record->hasNonTrivialDestructor()) 883 return VAK_ValidInCXX11; 884 885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 886 return VAK_Valid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 891 if (getLangOpts().MSVCCompat) 892 return VAK_MSVCUndefined; 893 894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 895 // permitted to reject them. We should consider doing so. 896 return VAK_Undefined; 897 } 898 899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 900 // Don't allow one to pass an Objective-C interface to a vararg. 901 const QualType &Ty = E->getType(); 902 VarArgKind VAK = isValidVarArgType(Ty); 903 904 // Complain about passing non-POD types through varargs. 905 switch (VAK) { 906 case VAK_ValidInCXX11: 907 DiagRuntimeBehavior( 908 E->getBeginLoc(), nullptr, 909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 910 LLVM_FALLTHROUGH; 911 case VAK_Valid: 912 if (Ty->isRecordType()) { 913 // This is unlikely to be what the user intended. If the class has a 914 // 'c_str' member function, the user probably meant to call that. 915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 916 PDiag(diag::warn_pass_class_arg_to_vararg) 917 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 918 } 919 break; 920 921 case VAK_Undefined: 922 case VAK_MSVCUndefined: 923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 925 << getLangOpts().CPlusPlus11 << Ty << CT); 926 break; 927 928 case VAK_Invalid: 929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 930 Diag(E->getBeginLoc(), 931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 932 << Ty << CT; 933 else if (Ty->isObjCObjectType()) 934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 936 << Ty << CT); 937 else 938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 939 << isa<InitListExpr>(E) << Ty << CT; 940 break; 941 } 942 } 943 944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 945 /// will create a trap if the resulting type is not a POD type. 946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 947 FunctionDecl *FDecl) { 948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 949 // Strip the unbridged-cast placeholder expression off, if applicable. 950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 951 (CT == VariadicMethod || 952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 953 E = stripARCUnbridgedCast(E); 954 955 // Otherwise, do normal placeholder checking. 956 } else { 957 ExprResult ExprRes = CheckPlaceholderExpr(E); 958 if (ExprRes.isInvalid()) 959 return ExprError(); 960 E = ExprRes.get(); 961 } 962 } 963 964 ExprResult ExprRes = DefaultArgumentPromotion(E); 965 if (ExprRes.isInvalid()) 966 return ExprError(); 967 E = ExprRes.get(); 968 969 // Diagnostics regarding non-POD argument types are 970 // emitted along with format string checking in Sema::CheckFunctionCall(). 971 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 972 // Turn this into a trap. 973 CXXScopeSpec SS; 974 SourceLocation TemplateKWLoc; 975 UnqualifiedId Name; 976 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 977 E->getBeginLoc()); 978 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 979 /*HasTrailingLParen=*/true, 980 /*IsAddressOfOperand=*/false); 981 if (TrapFn.isInvalid()) 982 return ExprError(); 983 984 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 985 None, E->getEndLoc()); 986 if (Call.isInvalid()) 987 return ExprError(); 988 989 ExprResult Comma = 990 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 991 if (Comma.isInvalid()) 992 return ExprError(); 993 return Comma.get(); 994 } 995 996 if (!getLangOpts().CPlusPlus && 997 RequireCompleteType(E->getExprLoc(), E->getType(), 998 diag::err_call_incomplete_argument)) 999 return ExprError(); 1000 1001 return E; 1002 } 1003 1004 /// Converts an integer to complex float type. Helper function of 1005 /// UsualArithmeticConversions() 1006 /// 1007 /// \return false if the integer expression is an integer type and is 1008 /// successfully converted to the complex type. 1009 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1010 ExprResult &ComplexExpr, 1011 QualType IntTy, 1012 QualType ComplexTy, 1013 bool SkipCast) { 1014 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1015 if (SkipCast) return false; 1016 if (IntTy->isIntegerType()) { 1017 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1018 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1019 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1020 CK_FloatingRealToComplex); 1021 } else { 1022 assert(IntTy->isComplexIntegerType()); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1024 CK_IntegralComplexToFloatingComplex); 1025 } 1026 return false; 1027 } 1028 1029 /// Handle arithmetic conversion with complex types. Helper function of 1030 /// UsualArithmeticConversions() 1031 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1032 ExprResult &RHS, QualType LHSType, 1033 QualType RHSType, 1034 bool IsCompAssign) { 1035 // if we have an integer operand, the result is the complex type. 1036 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1037 /*skipCast*/false)) 1038 return LHSType; 1039 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1040 /*skipCast*/IsCompAssign)) 1041 return RHSType; 1042 1043 // This handles complex/complex, complex/float, or float/complex. 1044 // When both operands are complex, the shorter operand is converted to the 1045 // type of the longer, and that is the type of the result. This corresponds 1046 // to what is done when combining two real floating-point operands. 1047 // The fun begins when size promotion occur across type domains. 1048 // From H&S 6.3.4: When one operand is complex and the other is a real 1049 // floating-point type, the less precise type is converted, within it's 1050 // real or complex domain, to the precision of the other type. For example, 1051 // when combining a "long double" with a "double _Complex", the 1052 // "double _Complex" is promoted to "long double _Complex". 1053 1054 // Compute the rank of the two types, regardless of whether they are complex. 1055 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1056 1057 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1058 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1059 QualType LHSElementType = 1060 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1061 QualType RHSElementType = 1062 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1063 1064 QualType ResultType = S.Context.getComplexType(LHSElementType); 1065 if (Order < 0) { 1066 // Promote the precision of the LHS if not an assignment. 1067 ResultType = S.Context.getComplexType(RHSElementType); 1068 if (!IsCompAssign) { 1069 if (LHSComplexType) 1070 LHS = 1071 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1072 else 1073 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1074 } 1075 } else if (Order > 0) { 1076 // Promote the precision of the RHS. 1077 if (RHSComplexType) 1078 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1079 else 1080 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1081 } 1082 return ResultType; 1083 } 1084 1085 /// Handle arithmetic conversion from integer to float. Helper function 1086 /// of UsualArithmeticConversions() 1087 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1088 ExprResult &IntExpr, 1089 QualType FloatTy, QualType IntTy, 1090 bool ConvertFloat, bool ConvertInt) { 1091 if (IntTy->isIntegerType()) { 1092 if (ConvertInt) 1093 // Convert intExpr to the lhs floating point type. 1094 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1095 CK_IntegralToFloating); 1096 return FloatTy; 1097 } 1098 1099 // Convert both sides to the appropriate complex float. 1100 assert(IntTy->isComplexIntegerType()); 1101 QualType result = S.Context.getComplexType(FloatTy); 1102 1103 // _Complex int -> _Complex float 1104 if (ConvertInt) 1105 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1106 CK_IntegralComplexToFloatingComplex); 1107 1108 // float -> _Complex float 1109 if (ConvertFloat) 1110 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1111 CK_FloatingRealToComplex); 1112 1113 return result; 1114 } 1115 1116 /// Handle arithmethic conversion with floating point types. Helper 1117 /// function of UsualArithmeticConversions() 1118 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1119 ExprResult &RHS, QualType LHSType, 1120 QualType RHSType, bool IsCompAssign) { 1121 bool LHSFloat = LHSType->isRealFloatingType(); 1122 bool RHSFloat = RHSType->isRealFloatingType(); 1123 1124 // If we have two real floating types, convert the smaller operand 1125 // to the bigger result. 1126 if (LHSFloat && RHSFloat) { 1127 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1128 if (order > 0) { 1129 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1130 return LHSType; 1131 } 1132 1133 assert(order < 0 && "illegal float comparison"); 1134 if (!IsCompAssign) 1135 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1136 return RHSType; 1137 } 1138 1139 if (LHSFloat) { 1140 // Half FP has to be promoted to float unless it is natively supported 1141 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1142 LHSType = S.Context.FloatTy; 1143 1144 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1145 /*ConvertFloat=*/!IsCompAssign, 1146 /*ConvertInt=*/ true); 1147 } 1148 assert(RHSFloat); 1149 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1150 /*convertInt=*/ true, 1151 /*convertFloat=*/!IsCompAssign); 1152 } 1153 1154 /// Diagnose attempts to convert between __float128 and long double if 1155 /// there is no support for such conversion. Helper function of 1156 /// UsualArithmeticConversions(). 1157 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1158 QualType RHSType) { 1159 /* No issue converting if at least one of the types is not a floating point 1160 type or the two types have the same rank. 1161 */ 1162 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1163 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1164 return false; 1165 1166 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1167 "The remaining types must be floating point types."); 1168 1169 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1170 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1171 1172 QualType LHSElemType = LHSComplex ? 1173 LHSComplex->getElementType() : LHSType; 1174 QualType RHSElemType = RHSComplex ? 1175 RHSComplex->getElementType() : RHSType; 1176 1177 // No issue if the two types have the same representation 1178 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1179 &S.Context.getFloatTypeSemantics(RHSElemType)) 1180 return false; 1181 1182 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1183 RHSElemType == S.Context.LongDoubleTy); 1184 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1185 RHSElemType == S.Context.Float128Ty); 1186 1187 // We've handled the situation where __float128 and long double have the same 1188 // representation. We allow all conversions for all possible long double types 1189 // except PPC's double double. 1190 return Float128AndLongDouble && 1191 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1192 &llvm::APFloat::PPCDoubleDouble()); 1193 } 1194 1195 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1196 1197 namespace { 1198 /// These helper callbacks are placed in an anonymous namespace to 1199 /// permit their use as function template parameters. 1200 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1201 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1202 } 1203 1204 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1205 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1206 CK_IntegralComplexCast); 1207 } 1208 } 1209 1210 /// Handle integer arithmetic conversions. Helper function of 1211 /// UsualArithmeticConversions() 1212 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1213 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1214 ExprResult &RHS, QualType LHSType, 1215 QualType RHSType, bool IsCompAssign) { 1216 // The rules for this case are in C99 6.3.1.8 1217 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1218 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1219 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1220 if (LHSSigned == RHSSigned) { 1221 // Same signedness; use the higher-ranked type 1222 if (order >= 0) { 1223 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1224 return LHSType; 1225 } else if (!IsCompAssign) 1226 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1227 return RHSType; 1228 } else if (order != (LHSSigned ? 1 : -1)) { 1229 // The unsigned type has greater than or equal rank to the 1230 // signed type, so use the unsigned type 1231 if (RHSSigned) { 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 (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1238 // The two types are different widths; if we are here, that 1239 // means the signed type is larger than the unsigned type, so 1240 // use the signed type. 1241 if (LHSSigned) { 1242 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1243 return LHSType; 1244 } else if (!IsCompAssign) 1245 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1246 return RHSType; 1247 } else { 1248 // The signed type is higher-ranked than the unsigned type, 1249 // but isn't actually any bigger (like unsigned int and long 1250 // on most 32-bit systems). Use the unsigned type corresponding 1251 // to the signed type. 1252 QualType result = 1253 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1254 RHS = (*doRHSCast)(S, RHS.get(), result); 1255 if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), result); 1257 return result; 1258 } 1259 } 1260 1261 /// Handle conversions with GCC complex int extension. Helper function 1262 /// of UsualArithmeticConversions() 1263 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1264 ExprResult &RHS, QualType LHSType, 1265 QualType RHSType, 1266 bool IsCompAssign) { 1267 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1268 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1269 1270 if (LHSComplexInt && RHSComplexInt) { 1271 QualType LHSEltType = LHSComplexInt->getElementType(); 1272 QualType RHSEltType = RHSComplexInt->getElementType(); 1273 QualType ScalarType = 1274 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1275 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1276 1277 return S.Context.getComplexType(ScalarType); 1278 } 1279 1280 if (LHSComplexInt) { 1281 QualType LHSEltType = LHSComplexInt->getElementType(); 1282 QualType ScalarType = 1283 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1284 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1285 QualType ComplexType = S.Context.getComplexType(ScalarType); 1286 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1287 CK_IntegralRealToComplex); 1288 1289 return ComplexType; 1290 } 1291 1292 assert(RHSComplexInt); 1293 1294 QualType RHSEltType = RHSComplexInt->getElementType(); 1295 QualType ScalarType = 1296 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1297 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1298 QualType ComplexType = S.Context.getComplexType(ScalarType); 1299 1300 if (!IsCompAssign) 1301 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1302 CK_IntegralRealToComplex); 1303 return ComplexType; 1304 } 1305 1306 /// Return the rank of a given fixed point or integer type. The value itself 1307 /// doesn't matter, but the values must be increasing with proper increasing 1308 /// rank as described in N1169 4.1.1. 1309 static unsigned GetFixedPointRank(QualType Ty) { 1310 const auto *BTy = Ty->getAs<BuiltinType>(); 1311 assert(BTy && "Expected a builtin type."); 1312 1313 switch (BTy->getKind()) { 1314 case BuiltinType::ShortFract: 1315 case BuiltinType::UShortFract: 1316 case BuiltinType::SatShortFract: 1317 case BuiltinType::SatUShortFract: 1318 return 1; 1319 case BuiltinType::Fract: 1320 case BuiltinType::UFract: 1321 case BuiltinType::SatFract: 1322 case BuiltinType::SatUFract: 1323 return 2; 1324 case BuiltinType::LongFract: 1325 case BuiltinType::ULongFract: 1326 case BuiltinType::SatLongFract: 1327 case BuiltinType::SatULongFract: 1328 return 3; 1329 case BuiltinType::ShortAccum: 1330 case BuiltinType::UShortAccum: 1331 case BuiltinType::SatShortAccum: 1332 case BuiltinType::SatUShortAccum: 1333 return 4; 1334 case BuiltinType::Accum: 1335 case BuiltinType::UAccum: 1336 case BuiltinType::SatAccum: 1337 case BuiltinType::SatUAccum: 1338 return 5; 1339 case BuiltinType::LongAccum: 1340 case BuiltinType::ULongAccum: 1341 case BuiltinType::SatLongAccum: 1342 case BuiltinType::SatULongAccum: 1343 return 6; 1344 default: 1345 if (BTy->isInteger()) 1346 return 0; 1347 llvm_unreachable("Unexpected fixed point or integer type"); 1348 } 1349 } 1350 1351 /// handleFixedPointConversion - Fixed point operations between fixed 1352 /// point types and integers or other fixed point types do not fall under 1353 /// usual arithmetic conversion since these conversions could result in loss 1354 /// of precsision (N1169 4.1.4). These operations should be calculated with 1355 /// the full precision of their result type (N1169 4.1.6.2.1). 1356 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1357 QualType RHSTy) { 1358 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1359 "Expected at least one of the operands to be a fixed point type"); 1360 assert((LHSTy->isFixedPointOrIntegerType() || 1361 RHSTy->isFixedPointOrIntegerType()) && 1362 "Special fixed point arithmetic operation conversions are only " 1363 "applied to ints or other fixed point types"); 1364 1365 // If one operand has signed fixed-point type and the other operand has 1366 // unsigned fixed-point type, then the unsigned fixed-point operand is 1367 // converted to its corresponding signed fixed-point type and the resulting 1368 // type is the type of the converted operand. 1369 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1370 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1371 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1372 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1373 1374 // The result type is the type with the highest rank, whereby a fixed-point 1375 // conversion rank is always greater than an integer conversion rank; if the 1376 // type of either of the operands is a saturating fixedpoint type, the result 1377 // type shall be the saturating fixed-point type corresponding to the type 1378 // with the highest rank; the resulting value is converted (taking into 1379 // account rounding and overflow) to the precision of the resulting type. 1380 // Same ranks between signed and unsigned types are resolved earlier, so both 1381 // types are either signed or both unsigned at this point. 1382 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1383 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1384 1385 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1386 1387 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1388 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1389 1390 return ResultTy; 1391 } 1392 1393 /// Check that the usual arithmetic conversions can be performed on this pair of 1394 /// expressions that might be of enumeration type. 1395 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1396 SourceLocation Loc, 1397 Sema::ArithConvKind ACK) { 1398 // C++2a [expr.arith.conv]p1: 1399 // If one operand is of enumeration type and the other operand is of a 1400 // different enumeration type or a floating-point type, this behavior is 1401 // deprecated ([depr.arith.conv.enum]). 1402 // 1403 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1404 // Eventually we will presumably reject these cases (in C++23 onwards?). 1405 QualType L = LHS->getType(), R = RHS->getType(); 1406 bool LEnum = L->isUnscopedEnumerationType(), 1407 REnum = R->isUnscopedEnumerationType(); 1408 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1409 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1410 (REnum && L->isFloatingType())) { 1411 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1412 ? diag::warn_arith_conv_enum_float_cxx20 1413 : diag::warn_arith_conv_enum_float) 1414 << LHS->getSourceRange() << RHS->getSourceRange() 1415 << (int)ACK << LEnum << L << R; 1416 } else if (!IsCompAssign && LEnum && REnum && 1417 !S.Context.hasSameUnqualifiedType(L, R)) { 1418 unsigned DiagID; 1419 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1420 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1421 // If either enumeration type is unnamed, it's less likely that the 1422 // user cares about this, but this situation is still deprecated in 1423 // C++2a. Use a different warning group. 1424 DiagID = S.getLangOpts().CPlusPlus20 1425 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1426 : diag::warn_arith_conv_mixed_anon_enum_types; 1427 } else if (ACK == Sema::ACK_Conditional) { 1428 // Conditional expressions are separated out because they have 1429 // historically had a different warning flag. 1430 DiagID = S.getLangOpts().CPlusPlus20 1431 ? diag::warn_conditional_mixed_enum_types_cxx20 1432 : diag::warn_conditional_mixed_enum_types; 1433 } else if (ACK == Sema::ACK_Comparison) { 1434 // Comparison expressions are separated out because they have 1435 // historically had a different warning flag. 1436 DiagID = S.getLangOpts().CPlusPlus20 1437 ? diag::warn_comparison_mixed_enum_types_cxx20 1438 : diag::warn_comparison_mixed_enum_types; 1439 } else { 1440 DiagID = S.getLangOpts().CPlusPlus20 1441 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1442 : diag::warn_arith_conv_mixed_enum_types; 1443 } 1444 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1445 << (int)ACK << L << R; 1446 } 1447 } 1448 1449 /// UsualArithmeticConversions - Performs various conversions that are common to 1450 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1451 /// routine returns the first non-arithmetic type found. The client is 1452 /// responsible for emitting appropriate error diagnostics. 1453 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1454 SourceLocation Loc, 1455 ArithConvKind ACK) { 1456 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1457 1458 if (ACK != ACK_CompAssign) { 1459 LHS = UsualUnaryConversions(LHS.get()); 1460 if (LHS.isInvalid()) 1461 return QualType(); 1462 } 1463 1464 RHS = UsualUnaryConversions(RHS.get()); 1465 if (RHS.isInvalid()) 1466 return QualType(); 1467 1468 // For conversion purposes, we ignore any qualifiers. 1469 // For example, "const float" and "float" are equivalent. 1470 QualType LHSType = 1471 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1472 QualType RHSType = 1473 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1474 1475 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1476 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1477 LHSType = AtomicLHS->getValueType(); 1478 1479 // If both types are identical, no conversion is needed. 1480 if (LHSType == RHSType) 1481 return LHSType; 1482 1483 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1484 // The caller can deal with this (e.g. pointer + int). 1485 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1486 return QualType(); 1487 1488 // Apply unary and bitfield promotions to the LHS's type. 1489 QualType LHSUnpromotedType = LHSType; 1490 if (LHSType->isPromotableIntegerType()) 1491 LHSType = Context.getPromotedIntegerType(LHSType); 1492 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1493 if (!LHSBitfieldPromoteTy.isNull()) 1494 LHSType = LHSBitfieldPromoteTy; 1495 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1496 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1497 1498 // If both types are identical, no conversion is needed. 1499 if (LHSType == RHSType) 1500 return LHSType; 1501 1502 // ExtInt types aren't subject to conversions between them or normal integers, 1503 // so this fails. 1504 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1505 return QualType(); 1506 1507 // At this point, we have two different arithmetic types. 1508 1509 // Diagnose attempts to convert between __float128 and long double where 1510 // such conversions currently can't be handled. 1511 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1512 return QualType(); 1513 1514 // Handle complex types first (C99 6.3.1.8p1). 1515 if (LHSType->isComplexType() || RHSType->isComplexType()) 1516 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1517 ACK == ACK_CompAssign); 1518 1519 // Now handle "real" floating types (i.e. float, double, long double). 1520 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1521 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1522 ACK == ACK_CompAssign); 1523 1524 // Handle GCC complex int extension. 1525 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1526 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1527 ACK == ACK_CompAssign); 1528 1529 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1530 return handleFixedPointConversion(*this, LHSType, RHSType); 1531 1532 // Finally, we have two differing integer types. 1533 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1534 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1535 } 1536 1537 //===----------------------------------------------------------------------===// 1538 // Semantic Analysis for various Expression Types 1539 //===----------------------------------------------------------------------===// 1540 1541 1542 ExprResult 1543 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1544 SourceLocation DefaultLoc, 1545 SourceLocation RParenLoc, 1546 Expr *ControllingExpr, 1547 ArrayRef<ParsedType> ArgTypes, 1548 ArrayRef<Expr *> ArgExprs) { 1549 unsigned NumAssocs = ArgTypes.size(); 1550 assert(NumAssocs == ArgExprs.size()); 1551 1552 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1553 for (unsigned i = 0; i < NumAssocs; ++i) { 1554 if (ArgTypes[i]) 1555 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1556 else 1557 Types[i] = nullptr; 1558 } 1559 1560 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1561 ControllingExpr, 1562 llvm::makeArrayRef(Types, NumAssocs), 1563 ArgExprs); 1564 delete [] Types; 1565 return ER; 1566 } 1567 1568 ExprResult 1569 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1570 SourceLocation DefaultLoc, 1571 SourceLocation RParenLoc, 1572 Expr *ControllingExpr, 1573 ArrayRef<TypeSourceInfo *> Types, 1574 ArrayRef<Expr *> Exprs) { 1575 unsigned NumAssocs = Types.size(); 1576 assert(NumAssocs == Exprs.size()); 1577 1578 // Decay and strip qualifiers for the controlling expression type, and handle 1579 // placeholder type replacement. See committee discussion from WG14 DR423. 1580 { 1581 EnterExpressionEvaluationContext Unevaluated( 1582 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1583 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1584 if (R.isInvalid()) 1585 return ExprError(); 1586 ControllingExpr = R.get(); 1587 } 1588 1589 // The controlling expression is an unevaluated operand, so side effects are 1590 // likely unintended. 1591 if (!inTemplateInstantiation() && 1592 ControllingExpr->HasSideEffects(Context, false)) 1593 Diag(ControllingExpr->getExprLoc(), 1594 diag::warn_side_effects_unevaluated_context); 1595 1596 bool TypeErrorFound = false, 1597 IsResultDependent = ControllingExpr->isTypeDependent(), 1598 ContainsUnexpandedParameterPack 1599 = ControllingExpr->containsUnexpandedParameterPack(); 1600 1601 for (unsigned i = 0; i < NumAssocs; ++i) { 1602 if (Exprs[i]->containsUnexpandedParameterPack()) 1603 ContainsUnexpandedParameterPack = true; 1604 1605 if (Types[i]) { 1606 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1607 ContainsUnexpandedParameterPack = true; 1608 1609 if (Types[i]->getType()->isDependentType()) { 1610 IsResultDependent = true; 1611 } else { 1612 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1613 // complete object type other than a variably modified type." 1614 unsigned D = 0; 1615 if (Types[i]->getType()->isIncompleteType()) 1616 D = diag::err_assoc_type_incomplete; 1617 else if (!Types[i]->getType()->isObjectType()) 1618 D = diag::err_assoc_type_nonobject; 1619 else if (Types[i]->getType()->isVariablyModifiedType()) 1620 D = diag::err_assoc_type_variably_modified; 1621 1622 if (D != 0) { 1623 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1624 << Types[i]->getTypeLoc().getSourceRange() 1625 << Types[i]->getType(); 1626 TypeErrorFound = true; 1627 } 1628 1629 // C11 6.5.1.1p2 "No two generic associations in the same generic 1630 // selection shall specify compatible types." 1631 for (unsigned j = i+1; j < NumAssocs; ++j) 1632 if (Types[j] && !Types[j]->getType()->isDependentType() && 1633 Context.typesAreCompatible(Types[i]->getType(), 1634 Types[j]->getType())) { 1635 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1636 diag::err_assoc_compatible_types) 1637 << Types[j]->getTypeLoc().getSourceRange() 1638 << Types[j]->getType() 1639 << Types[i]->getType(); 1640 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1641 diag::note_compat_assoc) 1642 << Types[i]->getTypeLoc().getSourceRange() 1643 << Types[i]->getType(); 1644 TypeErrorFound = true; 1645 } 1646 } 1647 } 1648 } 1649 if (TypeErrorFound) 1650 return ExprError(); 1651 1652 // If we determined that the generic selection is result-dependent, don't 1653 // try to compute the result expression. 1654 if (IsResultDependent) 1655 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1656 Exprs, DefaultLoc, RParenLoc, 1657 ContainsUnexpandedParameterPack); 1658 1659 SmallVector<unsigned, 1> CompatIndices; 1660 unsigned DefaultIndex = -1U; 1661 for (unsigned i = 0; i < NumAssocs; ++i) { 1662 if (!Types[i]) 1663 DefaultIndex = i; 1664 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1665 Types[i]->getType())) 1666 CompatIndices.push_back(i); 1667 } 1668 1669 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1670 // type compatible with at most one of the types named in its generic 1671 // association list." 1672 if (CompatIndices.size() > 1) { 1673 // We strip parens here because the controlling expression is typically 1674 // parenthesized in macro definitions. 1675 ControllingExpr = ControllingExpr->IgnoreParens(); 1676 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1677 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1678 << (unsigned)CompatIndices.size(); 1679 for (unsigned I : CompatIndices) { 1680 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1681 diag::note_compat_assoc) 1682 << Types[I]->getTypeLoc().getSourceRange() 1683 << Types[I]->getType(); 1684 } 1685 return ExprError(); 1686 } 1687 1688 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1689 // its controlling expression shall have type compatible with exactly one of 1690 // the types named in its generic association list." 1691 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1692 // We strip parens here because the controlling expression is typically 1693 // parenthesized in macro definitions. 1694 ControllingExpr = ControllingExpr->IgnoreParens(); 1695 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1696 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1697 return ExprError(); 1698 } 1699 1700 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1701 // type name that is compatible with the type of the controlling expression, 1702 // then the result expression of the generic selection is the expression 1703 // in that generic association. Otherwise, the result expression of the 1704 // generic selection is the expression in the default generic association." 1705 unsigned ResultIndex = 1706 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1707 1708 return GenericSelectionExpr::Create( 1709 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1710 ContainsUnexpandedParameterPack, ResultIndex); 1711 } 1712 1713 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1714 /// location of the token and the offset of the ud-suffix within it. 1715 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1716 unsigned Offset) { 1717 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1718 S.getLangOpts()); 1719 } 1720 1721 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1722 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1723 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1724 IdentifierInfo *UDSuffix, 1725 SourceLocation UDSuffixLoc, 1726 ArrayRef<Expr*> Args, 1727 SourceLocation LitEndLoc) { 1728 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1729 1730 QualType ArgTy[2]; 1731 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1732 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1733 if (ArgTy[ArgIdx]->isArrayType()) 1734 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1735 } 1736 1737 DeclarationName OpName = 1738 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1739 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1740 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1741 1742 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1743 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1744 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1745 /*AllowStringTemplate*/ false, 1746 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1747 return ExprError(); 1748 1749 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1750 } 1751 1752 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1753 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1754 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1755 /// multiple tokens. However, the common case is that StringToks points to one 1756 /// string. 1757 /// 1758 ExprResult 1759 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1760 assert(!StringToks.empty() && "Must have at least one string!"); 1761 1762 StringLiteralParser Literal(StringToks, PP); 1763 if (Literal.hadError) 1764 return ExprError(); 1765 1766 SmallVector<SourceLocation, 4> StringTokLocs; 1767 for (const Token &Tok : StringToks) 1768 StringTokLocs.push_back(Tok.getLocation()); 1769 1770 QualType CharTy = Context.CharTy; 1771 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1772 if (Literal.isWide()) { 1773 CharTy = Context.getWideCharType(); 1774 Kind = StringLiteral::Wide; 1775 } else if (Literal.isUTF8()) { 1776 if (getLangOpts().Char8) 1777 CharTy = Context.Char8Ty; 1778 Kind = StringLiteral::UTF8; 1779 } else if (Literal.isUTF16()) { 1780 CharTy = Context.Char16Ty; 1781 Kind = StringLiteral::UTF16; 1782 } else if (Literal.isUTF32()) { 1783 CharTy = Context.Char32Ty; 1784 Kind = StringLiteral::UTF32; 1785 } else if (Literal.isPascal()) { 1786 CharTy = Context.UnsignedCharTy; 1787 } 1788 1789 // Warn on initializing an array of char from a u8 string literal; this 1790 // becomes ill-formed in C++2a. 1791 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1792 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1793 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1794 1795 // Create removals for all 'u8' prefixes in the string literal(s). This 1796 // ensures C++2a compatibility (but may change the program behavior when 1797 // built by non-Clang compilers for which the execution character set is 1798 // not always UTF-8). 1799 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1800 SourceLocation RemovalDiagLoc; 1801 for (const Token &Tok : StringToks) { 1802 if (Tok.getKind() == tok::utf8_string_literal) { 1803 if (RemovalDiagLoc.isInvalid()) 1804 RemovalDiagLoc = Tok.getLocation(); 1805 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1806 Tok.getLocation(), 1807 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1808 getSourceManager(), getLangOpts()))); 1809 } 1810 } 1811 Diag(RemovalDiagLoc, RemovalDiag); 1812 } 1813 1814 QualType StrTy = 1815 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1816 1817 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1818 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1819 Kind, Literal.Pascal, StrTy, 1820 &StringTokLocs[0], 1821 StringTokLocs.size()); 1822 if (Literal.getUDSuffix().empty()) 1823 return Lit; 1824 1825 // We're building a user-defined literal. 1826 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1827 SourceLocation UDSuffixLoc = 1828 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1829 Literal.getUDSuffixOffset()); 1830 1831 // Make sure we're allowed user-defined literals here. 1832 if (!UDLScope) 1833 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1834 1835 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1836 // operator "" X (str, len) 1837 QualType SizeType = Context.getSizeType(); 1838 1839 DeclarationName OpName = 1840 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1841 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1842 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1843 1844 QualType ArgTy[] = { 1845 Context.getArrayDecayedType(StrTy), SizeType 1846 }; 1847 1848 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1849 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1850 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1851 /*AllowStringTemplate*/ true, 1852 /*DiagnoseMissing*/ true)) { 1853 1854 case LOLR_Cooked: { 1855 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1856 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1857 StringTokLocs[0]); 1858 Expr *Args[] = { Lit, LenArg }; 1859 1860 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1861 } 1862 1863 case LOLR_StringTemplate: { 1864 TemplateArgumentListInfo ExplicitArgs; 1865 1866 unsigned CharBits = Context.getIntWidth(CharTy); 1867 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1868 llvm::APSInt Value(CharBits, CharIsUnsigned); 1869 1870 TemplateArgument TypeArg(CharTy); 1871 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1872 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1873 1874 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1875 Value = Lit->getCodeUnit(I); 1876 TemplateArgument Arg(Context, Value, CharTy); 1877 TemplateArgumentLocInfo ArgInfo; 1878 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1879 } 1880 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1881 &ExplicitArgs); 1882 } 1883 case LOLR_Raw: 1884 case LOLR_Template: 1885 case LOLR_ErrorNoDiagnostic: 1886 llvm_unreachable("unexpected literal operator lookup result"); 1887 case LOLR_Error: 1888 return ExprError(); 1889 } 1890 llvm_unreachable("unexpected literal operator lookup result"); 1891 } 1892 1893 DeclRefExpr * 1894 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1895 SourceLocation Loc, 1896 const CXXScopeSpec *SS) { 1897 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1898 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1899 } 1900 1901 DeclRefExpr * 1902 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1903 const DeclarationNameInfo &NameInfo, 1904 const CXXScopeSpec *SS, NamedDecl *FoundD, 1905 SourceLocation TemplateKWLoc, 1906 const TemplateArgumentListInfo *TemplateArgs) { 1907 NestedNameSpecifierLoc NNS = 1908 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1909 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1910 TemplateArgs); 1911 } 1912 1913 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1914 // A declaration named in an unevaluated operand never constitutes an odr-use. 1915 if (isUnevaluatedContext()) 1916 return NOUR_Unevaluated; 1917 1918 // C++2a [basic.def.odr]p4: 1919 // A variable x whose name appears as a potentially-evaluated expression e 1920 // is odr-used by e unless [...] x is a reference that is usable in 1921 // constant expressions. 1922 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1923 if (VD->getType()->isReferenceType() && 1924 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1925 VD->isUsableInConstantExpressions(Context)) 1926 return NOUR_Constant; 1927 } 1928 1929 // All remaining non-variable cases constitute an odr-use. For variables, we 1930 // need to wait and see how the expression is used. 1931 return NOUR_None; 1932 } 1933 1934 /// BuildDeclRefExpr - Build an expression that references a 1935 /// declaration that does not require a closure capture. 1936 DeclRefExpr * 1937 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1938 const DeclarationNameInfo &NameInfo, 1939 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1940 SourceLocation TemplateKWLoc, 1941 const TemplateArgumentListInfo *TemplateArgs) { 1942 bool RefersToCapturedVariable = 1943 isa<VarDecl>(D) && 1944 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1945 1946 DeclRefExpr *E = DeclRefExpr::Create( 1947 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1948 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1949 MarkDeclRefReferenced(E); 1950 1951 // C++ [except.spec]p17: 1952 // An exception-specification is considered to be needed when: 1953 // - in an expression, the function is the unique lookup result or 1954 // the selected member of a set of overloaded functions. 1955 // 1956 // We delay doing this until after we've built the function reference and 1957 // marked it as used so that: 1958 // a) if the function is defaulted, we get errors from defining it before / 1959 // instead of errors from computing its exception specification, and 1960 // b) if the function is a defaulted comparison, we can use the body we 1961 // build when defining it as input to the exception specification 1962 // computation rather than computing a new body. 1963 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1964 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1965 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1966 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1967 } 1968 } 1969 1970 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1971 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1972 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1973 getCurFunction()->recordUseOfWeak(E); 1974 1975 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1976 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1977 FD = IFD->getAnonField(); 1978 if (FD) { 1979 UnusedPrivateFields.remove(FD); 1980 // Just in case we're building an illegal pointer-to-member. 1981 if (FD->isBitField()) 1982 E->setObjectKind(OK_BitField); 1983 } 1984 1985 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1986 // designates a bit-field. 1987 if (auto *BD = dyn_cast<BindingDecl>(D)) 1988 if (auto *BE = BD->getBinding()) 1989 E->setObjectKind(BE->getObjectKind()); 1990 1991 return E; 1992 } 1993 1994 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1995 /// possibly a list of template arguments. 1996 /// 1997 /// If this produces template arguments, it is permitted to call 1998 /// DecomposeTemplateName. 1999 /// 2000 /// This actually loses a lot of source location information for 2001 /// non-standard name kinds; we should consider preserving that in 2002 /// some way. 2003 void 2004 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2005 TemplateArgumentListInfo &Buffer, 2006 DeclarationNameInfo &NameInfo, 2007 const TemplateArgumentListInfo *&TemplateArgs) { 2008 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2009 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2010 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2011 2012 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2013 Id.TemplateId->NumArgs); 2014 translateTemplateArguments(TemplateArgsPtr, Buffer); 2015 2016 TemplateName TName = Id.TemplateId->Template.get(); 2017 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2018 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2019 TemplateArgs = &Buffer; 2020 } else { 2021 NameInfo = GetNameFromUnqualifiedId(Id); 2022 TemplateArgs = nullptr; 2023 } 2024 } 2025 2026 static void emitEmptyLookupTypoDiagnostic( 2027 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2028 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2029 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2030 DeclContext *Ctx = 2031 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2032 if (!TC) { 2033 // Emit a special diagnostic for failed member lookups. 2034 // FIXME: computing the declaration context might fail here (?) 2035 if (Ctx) 2036 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2037 << SS.getRange(); 2038 else 2039 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2040 return; 2041 } 2042 2043 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2044 bool DroppedSpecifier = 2045 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2046 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2047 ? diag::note_implicit_param_decl 2048 : diag::note_previous_decl; 2049 if (!Ctx) 2050 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2051 SemaRef.PDiag(NoteID)); 2052 else 2053 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2054 << Typo << Ctx << DroppedSpecifier 2055 << SS.getRange(), 2056 SemaRef.PDiag(NoteID)); 2057 } 2058 2059 /// Diagnose an empty lookup. 2060 /// 2061 /// \return false if new lookup candidates were found 2062 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2063 CorrectionCandidateCallback &CCC, 2064 TemplateArgumentListInfo *ExplicitTemplateArgs, 2065 ArrayRef<Expr *> Args, TypoExpr **Out) { 2066 DeclarationName Name = R.getLookupName(); 2067 2068 unsigned diagnostic = diag::err_undeclared_var_use; 2069 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2070 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2071 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2072 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2073 diagnostic = diag::err_undeclared_use; 2074 diagnostic_suggest = diag::err_undeclared_use_suggest; 2075 } 2076 2077 // If the original lookup was an unqualified lookup, fake an 2078 // unqualified lookup. This is useful when (for example) the 2079 // original lookup would not have found something because it was a 2080 // dependent name. 2081 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2082 while (DC) { 2083 if (isa<CXXRecordDecl>(DC)) { 2084 LookupQualifiedName(R, DC); 2085 2086 if (!R.empty()) { 2087 // Don't give errors about ambiguities in this lookup. 2088 R.suppressDiagnostics(); 2089 2090 // During a default argument instantiation the CurContext points 2091 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2092 // function parameter list, hence add an explicit check. 2093 bool isDefaultArgument = 2094 !CodeSynthesisContexts.empty() && 2095 CodeSynthesisContexts.back().Kind == 2096 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2097 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2098 bool isInstance = CurMethod && 2099 CurMethod->isInstance() && 2100 DC == CurMethod->getParent() && !isDefaultArgument; 2101 2102 // Give a code modification hint to insert 'this->'. 2103 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2104 // Actually quite difficult! 2105 if (getLangOpts().MSVCCompat) 2106 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2107 if (isInstance) { 2108 Diag(R.getNameLoc(), diagnostic) << Name 2109 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2110 CheckCXXThisCapture(R.getNameLoc()); 2111 } else { 2112 Diag(R.getNameLoc(), diagnostic) << Name; 2113 } 2114 2115 // Do we really want to note all of these? 2116 for (NamedDecl *D : R) 2117 Diag(D->getLocation(), diag::note_dependent_var_use); 2118 2119 // Return true if we are inside a default argument instantiation 2120 // and the found name refers to an instance member function, otherwise 2121 // the function calling DiagnoseEmptyLookup will try to create an 2122 // implicit member call and this is wrong for default argument. 2123 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2124 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2125 return true; 2126 } 2127 2128 // Tell the callee to try to recover. 2129 return false; 2130 } 2131 2132 R.clear(); 2133 } 2134 2135 DC = DC->getLookupParent(); 2136 } 2137 2138 // We didn't find anything, so try to correct for a typo. 2139 TypoCorrection Corrected; 2140 if (S && Out) { 2141 SourceLocation TypoLoc = R.getNameLoc(); 2142 assert(!ExplicitTemplateArgs && 2143 "Diagnosing an empty lookup with explicit template args!"); 2144 *Out = CorrectTypoDelayed( 2145 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2146 [=](const TypoCorrection &TC) { 2147 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2148 diagnostic, diagnostic_suggest); 2149 }, 2150 nullptr, CTK_ErrorRecovery); 2151 if (*Out) 2152 return true; 2153 } else if (S && 2154 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2155 S, &SS, CCC, CTK_ErrorRecovery))) { 2156 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2157 bool DroppedSpecifier = 2158 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2159 R.setLookupName(Corrected.getCorrection()); 2160 2161 bool AcceptableWithRecovery = false; 2162 bool AcceptableWithoutRecovery = false; 2163 NamedDecl *ND = Corrected.getFoundDecl(); 2164 if (ND) { 2165 if (Corrected.isOverloaded()) { 2166 OverloadCandidateSet OCS(R.getNameLoc(), 2167 OverloadCandidateSet::CSK_Normal); 2168 OverloadCandidateSet::iterator Best; 2169 for (NamedDecl *CD : Corrected) { 2170 if (FunctionTemplateDecl *FTD = 2171 dyn_cast<FunctionTemplateDecl>(CD)) 2172 AddTemplateOverloadCandidate( 2173 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2174 Args, OCS); 2175 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2176 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2177 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2178 Args, OCS); 2179 } 2180 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2181 case OR_Success: 2182 ND = Best->FoundDecl; 2183 Corrected.setCorrectionDecl(ND); 2184 break; 2185 default: 2186 // FIXME: Arbitrarily pick the first declaration for the note. 2187 Corrected.setCorrectionDecl(ND); 2188 break; 2189 } 2190 } 2191 R.addDecl(ND); 2192 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2193 CXXRecordDecl *Record = nullptr; 2194 if (Corrected.getCorrectionSpecifier()) { 2195 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2196 Record = Ty->getAsCXXRecordDecl(); 2197 } 2198 if (!Record) 2199 Record = cast<CXXRecordDecl>( 2200 ND->getDeclContext()->getRedeclContext()); 2201 R.setNamingClass(Record); 2202 } 2203 2204 auto *UnderlyingND = ND->getUnderlyingDecl(); 2205 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2206 isa<FunctionTemplateDecl>(UnderlyingND); 2207 // FIXME: If we ended up with a typo for a type name or 2208 // Objective-C class name, we're in trouble because the parser 2209 // is in the wrong place to recover. Suggest the typo 2210 // correction, but don't make it a fix-it since we're not going 2211 // to recover well anyway. 2212 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2213 getAsTypeTemplateDecl(UnderlyingND) || 2214 isa<ObjCInterfaceDecl>(UnderlyingND); 2215 } else { 2216 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2217 // because we aren't able to recover. 2218 AcceptableWithoutRecovery = true; 2219 } 2220 2221 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2222 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2223 ? diag::note_implicit_param_decl 2224 : diag::note_previous_decl; 2225 if (SS.isEmpty()) 2226 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2227 PDiag(NoteID), AcceptableWithRecovery); 2228 else 2229 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2230 << Name << computeDeclContext(SS, false) 2231 << DroppedSpecifier << SS.getRange(), 2232 PDiag(NoteID), AcceptableWithRecovery); 2233 2234 // Tell the callee whether to try to recover. 2235 return !AcceptableWithRecovery; 2236 } 2237 } 2238 R.clear(); 2239 2240 // Emit a special diagnostic for failed member lookups. 2241 // FIXME: computing the declaration context might fail here (?) 2242 if (!SS.isEmpty()) { 2243 Diag(R.getNameLoc(), diag::err_no_member) 2244 << Name << computeDeclContext(SS, false) 2245 << SS.getRange(); 2246 return true; 2247 } 2248 2249 // Give up, we can't recover. 2250 Diag(R.getNameLoc(), diagnostic) << Name; 2251 return true; 2252 } 2253 2254 /// In Microsoft mode, if we are inside a template class whose parent class has 2255 /// dependent base classes, and we can't resolve an unqualified identifier, then 2256 /// assume the identifier is a member of a dependent base class. We can only 2257 /// recover successfully in static methods, instance methods, and other contexts 2258 /// where 'this' is available. This doesn't precisely match MSVC's 2259 /// instantiation model, but it's close enough. 2260 static Expr * 2261 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2262 DeclarationNameInfo &NameInfo, 2263 SourceLocation TemplateKWLoc, 2264 const TemplateArgumentListInfo *TemplateArgs) { 2265 // Only try to recover from lookup into dependent bases in static methods or 2266 // contexts where 'this' is available. 2267 QualType ThisType = S.getCurrentThisType(); 2268 const CXXRecordDecl *RD = nullptr; 2269 if (!ThisType.isNull()) 2270 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2271 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2272 RD = MD->getParent(); 2273 if (!RD || !RD->hasAnyDependentBases()) 2274 return nullptr; 2275 2276 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2277 // is available, suggest inserting 'this->' as a fixit. 2278 SourceLocation Loc = NameInfo.getLoc(); 2279 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2280 DB << NameInfo.getName() << RD; 2281 2282 if (!ThisType.isNull()) { 2283 DB << FixItHint::CreateInsertion(Loc, "this->"); 2284 return CXXDependentScopeMemberExpr::Create( 2285 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2286 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2287 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2288 } 2289 2290 // Synthesize a fake NNS that points to the derived class. This will 2291 // perform name lookup during template instantiation. 2292 CXXScopeSpec SS; 2293 auto *NNS = 2294 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2295 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2296 return DependentScopeDeclRefExpr::Create( 2297 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2298 TemplateArgs); 2299 } 2300 2301 ExprResult 2302 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2303 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2304 bool HasTrailingLParen, bool IsAddressOfOperand, 2305 CorrectionCandidateCallback *CCC, 2306 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2307 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2308 "cannot be direct & operand and have a trailing lparen"); 2309 if (SS.isInvalid()) 2310 return ExprError(); 2311 2312 TemplateArgumentListInfo TemplateArgsBuffer; 2313 2314 // Decompose the UnqualifiedId into the following data. 2315 DeclarationNameInfo NameInfo; 2316 const TemplateArgumentListInfo *TemplateArgs; 2317 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2318 2319 DeclarationName Name = NameInfo.getName(); 2320 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2321 SourceLocation NameLoc = NameInfo.getLoc(); 2322 2323 if (II && II->isEditorPlaceholder()) { 2324 // FIXME: When typed placeholders are supported we can create a typed 2325 // placeholder expression node. 2326 return ExprError(); 2327 } 2328 2329 // C++ [temp.dep.expr]p3: 2330 // An id-expression is type-dependent if it contains: 2331 // -- an identifier that was declared with a dependent type, 2332 // (note: handled after lookup) 2333 // -- a template-id that is dependent, 2334 // (note: handled in BuildTemplateIdExpr) 2335 // -- a conversion-function-id that specifies a dependent type, 2336 // -- a nested-name-specifier that contains a class-name that 2337 // names a dependent type. 2338 // Determine whether this is a member of an unknown specialization; 2339 // we need to handle these differently. 2340 bool DependentID = false; 2341 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2342 Name.getCXXNameType()->isDependentType()) { 2343 DependentID = true; 2344 } else if (SS.isSet()) { 2345 if (DeclContext *DC = computeDeclContext(SS, false)) { 2346 if (RequireCompleteDeclContext(SS, DC)) 2347 return ExprError(); 2348 } else { 2349 DependentID = true; 2350 } 2351 } 2352 2353 if (DependentID) 2354 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2355 IsAddressOfOperand, TemplateArgs); 2356 2357 // Perform the required lookup. 2358 LookupResult R(*this, NameInfo, 2359 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2360 ? LookupObjCImplicitSelfParam 2361 : LookupOrdinaryName); 2362 if (TemplateKWLoc.isValid() || TemplateArgs) { 2363 // Lookup the template name again to correctly establish the context in 2364 // which it was found. This is really unfortunate as we already did the 2365 // lookup to determine that it was a template name in the first place. If 2366 // this becomes a performance hit, we can work harder to preserve those 2367 // results until we get here but it's likely not worth it. 2368 bool MemberOfUnknownSpecialization; 2369 AssumedTemplateKind AssumedTemplate; 2370 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2371 MemberOfUnknownSpecialization, TemplateKWLoc, 2372 &AssumedTemplate)) 2373 return ExprError(); 2374 2375 if (MemberOfUnknownSpecialization || 2376 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2377 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2378 IsAddressOfOperand, TemplateArgs); 2379 } else { 2380 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2381 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2382 2383 // If the result might be in a dependent base class, this is a dependent 2384 // id-expression. 2385 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2386 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2387 IsAddressOfOperand, TemplateArgs); 2388 2389 // If this reference is in an Objective-C method, then we need to do 2390 // some special Objective-C lookup, too. 2391 if (IvarLookupFollowUp) { 2392 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2393 if (E.isInvalid()) 2394 return ExprError(); 2395 2396 if (Expr *Ex = E.getAs<Expr>()) 2397 return Ex; 2398 } 2399 } 2400 2401 if (R.isAmbiguous()) 2402 return ExprError(); 2403 2404 // This could be an implicitly declared function reference (legal in C90, 2405 // extension in C99, forbidden in C++). 2406 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2407 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2408 if (D) R.addDecl(D); 2409 } 2410 2411 // Determine whether this name might be a candidate for 2412 // argument-dependent lookup. 2413 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2414 2415 if (R.empty() && !ADL) { 2416 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2417 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2418 TemplateKWLoc, TemplateArgs)) 2419 return E; 2420 } 2421 2422 // Don't diagnose an empty lookup for inline assembly. 2423 if (IsInlineAsmIdentifier) 2424 return ExprError(); 2425 2426 // If this name wasn't predeclared and if this is not a function 2427 // call, diagnose the problem. 2428 TypoExpr *TE = nullptr; 2429 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2430 : nullptr); 2431 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2432 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2433 "Typo correction callback misconfigured"); 2434 if (CCC) { 2435 // Make sure the callback knows what the typo being diagnosed is. 2436 CCC->setTypoName(II); 2437 if (SS.isValid()) 2438 CCC->setTypoNNS(SS.getScopeRep()); 2439 } 2440 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2441 // a template name, but we happen to have always already looked up the name 2442 // before we get here if it must be a template name. 2443 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2444 None, &TE)) { 2445 if (TE && KeywordReplacement) { 2446 auto &State = getTypoExprState(TE); 2447 auto BestTC = State.Consumer->getNextCorrection(); 2448 if (BestTC.isKeyword()) { 2449 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2450 if (State.DiagHandler) 2451 State.DiagHandler(BestTC); 2452 KeywordReplacement->startToken(); 2453 KeywordReplacement->setKind(II->getTokenID()); 2454 KeywordReplacement->setIdentifierInfo(II); 2455 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2456 // Clean up the state associated with the TypoExpr, since it has 2457 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2458 clearDelayedTypo(TE); 2459 // Signal that a correction to a keyword was performed by returning a 2460 // valid-but-null ExprResult. 2461 return (Expr*)nullptr; 2462 } 2463 State.Consumer->resetCorrectionStream(); 2464 } 2465 return TE ? TE : ExprError(); 2466 } 2467 2468 assert(!R.empty() && 2469 "DiagnoseEmptyLookup returned false but added no results"); 2470 2471 // If we found an Objective-C instance variable, let 2472 // LookupInObjCMethod build the appropriate expression to 2473 // reference the ivar. 2474 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2475 R.clear(); 2476 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2477 // In a hopelessly buggy code, Objective-C instance variable 2478 // lookup fails and no expression will be built to reference it. 2479 if (!E.isInvalid() && !E.get()) 2480 return ExprError(); 2481 return E; 2482 } 2483 } 2484 2485 // This is guaranteed from this point on. 2486 assert(!R.empty() || ADL); 2487 2488 // Check whether this might be a C++ implicit instance member access. 2489 // C++ [class.mfct.non-static]p3: 2490 // When an id-expression that is not part of a class member access 2491 // syntax and not used to form a pointer to member is used in the 2492 // body of a non-static member function of class X, if name lookup 2493 // resolves the name in the id-expression to a non-static non-type 2494 // member of some class C, the id-expression is transformed into a 2495 // class member access expression using (*this) as the 2496 // postfix-expression to the left of the . operator. 2497 // 2498 // But we don't actually need to do this for '&' operands if R 2499 // resolved to a function or overloaded function set, because the 2500 // expression is ill-formed if it actually works out to be a 2501 // non-static member function: 2502 // 2503 // C++ [expr.ref]p4: 2504 // Otherwise, if E1.E2 refers to a non-static member function. . . 2505 // [t]he expression can be used only as the left-hand operand of a 2506 // member function call. 2507 // 2508 // There are other safeguards against such uses, but it's important 2509 // to get this right here so that we don't end up making a 2510 // spuriously dependent expression if we're inside a dependent 2511 // instance method. 2512 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2513 bool MightBeImplicitMember; 2514 if (!IsAddressOfOperand) 2515 MightBeImplicitMember = true; 2516 else if (!SS.isEmpty()) 2517 MightBeImplicitMember = false; 2518 else if (R.isOverloadedResult()) 2519 MightBeImplicitMember = false; 2520 else if (R.isUnresolvableResult()) 2521 MightBeImplicitMember = true; 2522 else 2523 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2524 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2525 isa<MSPropertyDecl>(R.getFoundDecl()); 2526 2527 if (MightBeImplicitMember) 2528 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2529 R, TemplateArgs, S); 2530 } 2531 2532 if (TemplateArgs || TemplateKWLoc.isValid()) { 2533 2534 // In C++1y, if this is a variable template id, then check it 2535 // in BuildTemplateIdExpr(). 2536 // The single lookup result must be a variable template declaration. 2537 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2538 Id.TemplateId->Kind == TNK_Var_template) { 2539 assert(R.getAsSingle<VarTemplateDecl>() && 2540 "There should only be one declaration found."); 2541 } 2542 2543 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2544 } 2545 2546 return BuildDeclarationNameExpr(SS, R, ADL); 2547 } 2548 2549 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2550 /// declaration name, generally during template instantiation. 2551 /// There's a large number of things which don't need to be done along 2552 /// this path. 2553 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2554 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2555 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2556 DeclContext *DC = computeDeclContext(SS, false); 2557 if (!DC) 2558 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2559 NameInfo, /*TemplateArgs=*/nullptr); 2560 2561 if (RequireCompleteDeclContext(SS, DC)) 2562 return ExprError(); 2563 2564 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2565 LookupQualifiedName(R, DC); 2566 2567 if (R.isAmbiguous()) 2568 return ExprError(); 2569 2570 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2571 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2572 NameInfo, /*TemplateArgs=*/nullptr); 2573 2574 if (R.empty()) { 2575 Diag(NameInfo.getLoc(), diag::err_no_member) 2576 << NameInfo.getName() << DC << SS.getRange(); 2577 return ExprError(); 2578 } 2579 2580 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2581 // Diagnose a missing typename if this resolved unambiguously to a type in 2582 // a dependent context. If we can recover with a type, downgrade this to 2583 // a warning in Microsoft compatibility mode. 2584 unsigned DiagID = diag::err_typename_missing; 2585 if (RecoveryTSI && getLangOpts().MSVCCompat) 2586 DiagID = diag::ext_typename_missing; 2587 SourceLocation Loc = SS.getBeginLoc(); 2588 auto D = Diag(Loc, DiagID); 2589 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2590 << SourceRange(Loc, NameInfo.getEndLoc()); 2591 2592 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2593 // context. 2594 if (!RecoveryTSI) 2595 return ExprError(); 2596 2597 // Only issue the fixit if we're prepared to recover. 2598 D << FixItHint::CreateInsertion(Loc, "typename "); 2599 2600 // Recover by pretending this was an elaborated type. 2601 QualType Ty = Context.getTypeDeclType(TD); 2602 TypeLocBuilder TLB; 2603 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2604 2605 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2606 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2607 QTL.setElaboratedKeywordLoc(SourceLocation()); 2608 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2609 2610 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2611 2612 return ExprEmpty(); 2613 } 2614 2615 // Defend against this resolving to an implicit member access. We usually 2616 // won't get here if this might be a legitimate a class member (we end up in 2617 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2618 // a pointer-to-member or in an unevaluated context in C++11. 2619 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2620 return BuildPossibleImplicitMemberExpr(SS, 2621 /*TemplateKWLoc=*/SourceLocation(), 2622 R, /*TemplateArgs=*/nullptr, S); 2623 2624 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2625 } 2626 2627 /// The parser has read a name in, and Sema has detected that we're currently 2628 /// inside an ObjC method. Perform some additional checks and determine if we 2629 /// should form a reference to an ivar. 2630 /// 2631 /// Ideally, most of this would be done by lookup, but there's 2632 /// actually quite a lot of extra work involved. 2633 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2634 IdentifierInfo *II) { 2635 SourceLocation Loc = Lookup.getNameLoc(); 2636 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2637 2638 // Check for error condition which is already reported. 2639 if (!CurMethod) 2640 return DeclResult(true); 2641 2642 // There are two cases to handle here. 1) scoped lookup could have failed, 2643 // in which case we should look for an ivar. 2) scoped lookup could have 2644 // found a decl, but that decl is outside the current instance method (i.e. 2645 // a global variable). In these two cases, we do a lookup for an ivar with 2646 // this name, if the lookup sucedes, we replace it our current decl. 2647 2648 // If we're in a class method, we don't normally want to look for 2649 // ivars. But if we don't find anything else, and there's an 2650 // ivar, that's an error. 2651 bool IsClassMethod = CurMethod->isClassMethod(); 2652 2653 bool LookForIvars; 2654 if (Lookup.empty()) 2655 LookForIvars = true; 2656 else if (IsClassMethod) 2657 LookForIvars = false; 2658 else 2659 LookForIvars = (Lookup.isSingleResult() && 2660 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2661 ObjCInterfaceDecl *IFace = nullptr; 2662 if (LookForIvars) { 2663 IFace = CurMethod->getClassInterface(); 2664 ObjCInterfaceDecl *ClassDeclared; 2665 ObjCIvarDecl *IV = nullptr; 2666 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2667 // Diagnose using an ivar in a class method. 2668 if (IsClassMethod) { 2669 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2670 return DeclResult(true); 2671 } 2672 2673 // Diagnose the use of an ivar outside of the declaring class. 2674 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2675 !declaresSameEntity(ClassDeclared, IFace) && 2676 !getLangOpts().DebuggerSupport) 2677 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2678 2679 // Success. 2680 return IV; 2681 } 2682 } else if (CurMethod->isInstanceMethod()) { 2683 // We should warn if a local variable hides an ivar. 2684 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2685 ObjCInterfaceDecl *ClassDeclared; 2686 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2687 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2688 declaresSameEntity(IFace, ClassDeclared)) 2689 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2690 } 2691 } 2692 } else if (Lookup.isSingleResult() && 2693 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2694 // If accessing a stand-alone ivar in a class method, this is an error. 2695 if (const ObjCIvarDecl *IV = 2696 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2697 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2698 return DeclResult(true); 2699 } 2700 } 2701 2702 // Didn't encounter an error, didn't find an ivar. 2703 return DeclResult(false); 2704 } 2705 2706 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2707 ObjCIvarDecl *IV) { 2708 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2709 assert(CurMethod && CurMethod->isInstanceMethod() && 2710 "should not reference ivar from this context"); 2711 2712 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2713 assert(IFace && "should not reference ivar from this context"); 2714 2715 // If we're referencing an invalid decl, just return this as a silent 2716 // error node. The error diagnostic was already emitted on the decl. 2717 if (IV->isInvalidDecl()) 2718 return ExprError(); 2719 2720 // Check if referencing a field with __attribute__((deprecated)). 2721 if (DiagnoseUseOfDecl(IV, Loc)) 2722 return ExprError(); 2723 2724 // FIXME: This should use a new expr for a direct reference, don't 2725 // turn this into Self->ivar, just return a BareIVarExpr or something. 2726 IdentifierInfo &II = Context.Idents.get("self"); 2727 UnqualifiedId SelfName; 2728 SelfName.setIdentifier(&II, SourceLocation()); 2729 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2730 CXXScopeSpec SelfScopeSpec; 2731 SourceLocation TemplateKWLoc; 2732 ExprResult SelfExpr = 2733 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2734 /*HasTrailingLParen=*/false, 2735 /*IsAddressOfOperand=*/false); 2736 if (SelfExpr.isInvalid()) 2737 return ExprError(); 2738 2739 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2740 if (SelfExpr.isInvalid()) 2741 return ExprError(); 2742 2743 MarkAnyDeclReferenced(Loc, IV, true); 2744 2745 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2746 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2747 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2748 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2749 2750 ObjCIvarRefExpr *Result = new (Context) 2751 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2752 IV->getLocation(), SelfExpr.get(), true, true); 2753 2754 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2755 if (!isUnevaluatedContext() && 2756 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2757 getCurFunction()->recordUseOfWeak(Result); 2758 } 2759 if (getLangOpts().ObjCAutoRefCount) 2760 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2761 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2762 2763 return Result; 2764 } 2765 2766 /// The parser has read a name in, and Sema has detected that we're currently 2767 /// inside an ObjC method. Perform some additional checks and determine if we 2768 /// should form a reference to an ivar. If so, build an expression referencing 2769 /// that ivar. 2770 ExprResult 2771 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2772 IdentifierInfo *II, bool AllowBuiltinCreation) { 2773 // FIXME: Integrate this lookup step into LookupParsedName. 2774 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2775 if (Ivar.isInvalid()) 2776 return ExprError(); 2777 if (Ivar.isUsable()) 2778 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2779 cast<ObjCIvarDecl>(Ivar.get())); 2780 2781 if (Lookup.empty() && II && AllowBuiltinCreation) 2782 LookupBuiltin(Lookup); 2783 2784 // Sentinel value saying that we didn't do anything special. 2785 return ExprResult(false); 2786 } 2787 2788 /// Cast a base object to a member's actual type. 2789 /// 2790 /// Logically this happens in three phases: 2791 /// 2792 /// * First we cast from the base type to the naming class. 2793 /// The naming class is the class into which we were looking 2794 /// when we found the member; it's the qualifier type if a 2795 /// qualifier was provided, and otherwise it's the base type. 2796 /// 2797 /// * Next we cast from the naming class to the declaring class. 2798 /// If the member we found was brought into a class's scope by 2799 /// a using declaration, this is that class; otherwise it's 2800 /// the class declaring the member. 2801 /// 2802 /// * Finally we cast from the declaring class to the "true" 2803 /// declaring class of the member. This conversion does not 2804 /// obey access control. 2805 ExprResult 2806 Sema::PerformObjectMemberConversion(Expr *From, 2807 NestedNameSpecifier *Qualifier, 2808 NamedDecl *FoundDecl, 2809 NamedDecl *Member) { 2810 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2811 if (!RD) 2812 return From; 2813 2814 QualType DestRecordType; 2815 QualType DestType; 2816 QualType FromRecordType; 2817 QualType FromType = From->getType(); 2818 bool PointerConversions = false; 2819 if (isa<FieldDecl>(Member)) { 2820 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2821 auto FromPtrType = FromType->getAs<PointerType>(); 2822 DestRecordType = Context.getAddrSpaceQualType( 2823 DestRecordType, FromPtrType 2824 ? FromType->getPointeeType().getAddressSpace() 2825 : FromType.getAddressSpace()); 2826 2827 if (FromPtrType) { 2828 DestType = Context.getPointerType(DestRecordType); 2829 FromRecordType = FromPtrType->getPointeeType(); 2830 PointerConversions = true; 2831 } else { 2832 DestType = DestRecordType; 2833 FromRecordType = FromType; 2834 } 2835 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2836 if (Method->isStatic()) 2837 return From; 2838 2839 DestType = Method->getThisType(); 2840 DestRecordType = DestType->getPointeeType(); 2841 2842 if (FromType->getAs<PointerType>()) { 2843 FromRecordType = FromType->getPointeeType(); 2844 PointerConversions = true; 2845 } else { 2846 FromRecordType = FromType; 2847 DestType = DestRecordType; 2848 } 2849 2850 LangAS FromAS = FromRecordType.getAddressSpace(); 2851 LangAS DestAS = DestRecordType.getAddressSpace(); 2852 if (FromAS != DestAS) { 2853 QualType FromRecordTypeWithoutAS = 2854 Context.removeAddrSpaceQualType(FromRecordType); 2855 QualType FromTypeWithDestAS = 2856 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2857 if (PointerConversions) 2858 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2859 From = ImpCastExprToType(From, FromTypeWithDestAS, 2860 CK_AddressSpaceConversion, From->getValueKind()) 2861 .get(); 2862 } 2863 } else { 2864 // No conversion necessary. 2865 return From; 2866 } 2867 2868 if (DestType->isDependentType() || FromType->isDependentType()) 2869 return From; 2870 2871 // If the unqualified types are the same, no conversion is necessary. 2872 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2873 return From; 2874 2875 SourceRange FromRange = From->getSourceRange(); 2876 SourceLocation FromLoc = FromRange.getBegin(); 2877 2878 ExprValueKind VK = From->getValueKind(); 2879 2880 // C++ [class.member.lookup]p8: 2881 // [...] Ambiguities can often be resolved by qualifying a name with its 2882 // class name. 2883 // 2884 // If the member was a qualified name and the qualified referred to a 2885 // specific base subobject type, we'll cast to that intermediate type 2886 // first and then to the object in which the member is declared. That allows 2887 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2888 // 2889 // class Base { public: int x; }; 2890 // class Derived1 : public Base { }; 2891 // class Derived2 : public Base { }; 2892 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2893 // 2894 // void VeryDerived::f() { 2895 // x = 17; // error: ambiguous base subobjects 2896 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2897 // } 2898 if (Qualifier && Qualifier->getAsType()) { 2899 QualType QType = QualType(Qualifier->getAsType(), 0); 2900 assert(QType->isRecordType() && "lookup done with non-record type"); 2901 2902 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2903 2904 // In C++98, the qualifier type doesn't actually have to be a base 2905 // type of the object type, in which case we just ignore it. 2906 // Otherwise build the appropriate casts. 2907 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2908 CXXCastPath BasePath; 2909 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2910 FromLoc, FromRange, &BasePath)) 2911 return ExprError(); 2912 2913 if (PointerConversions) 2914 QType = Context.getPointerType(QType); 2915 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2916 VK, &BasePath).get(); 2917 2918 FromType = QType; 2919 FromRecordType = QRecordType; 2920 2921 // If the qualifier type was the same as the destination type, 2922 // we're done. 2923 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2924 return From; 2925 } 2926 } 2927 2928 bool IgnoreAccess = false; 2929 2930 // If we actually found the member through a using declaration, cast 2931 // down to the using declaration's type. 2932 // 2933 // Pointer equality is fine here because only one declaration of a 2934 // class ever has member declarations. 2935 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2936 assert(isa<UsingShadowDecl>(FoundDecl)); 2937 QualType URecordType = Context.getTypeDeclType( 2938 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2939 2940 // We only need to do this if the naming-class to declaring-class 2941 // conversion is non-trivial. 2942 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2943 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2944 CXXCastPath BasePath; 2945 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2946 FromLoc, FromRange, &BasePath)) 2947 return ExprError(); 2948 2949 QualType UType = URecordType; 2950 if (PointerConversions) 2951 UType = Context.getPointerType(UType); 2952 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2953 VK, &BasePath).get(); 2954 FromType = UType; 2955 FromRecordType = URecordType; 2956 } 2957 2958 // We don't do access control for the conversion from the 2959 // declaring class to the true declaring class. 2960 IgnoreAccess = true; 2961 } 2962 2963 CXXCastPath BasePath; 2964 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2965 FromLoc, FromRange, &BasePath, 2966 IgnoreAccess)) 2967 return ExprError(); 2968 2969 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2970 VK, &BasePath); 2971 } 2972 2973 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2974 const LookupResult &R, 2975 bool HasTrailingLParen) { 2976 // Only when used directly as the postfix-expression of a call. 2977 if (!HasTrailingLParen) 2978 return false; 2979 2980 // Never if a scope specifier was provided. 2981 if (SS.isSet()) 2982 return false; 2983 2984 // Only in C++ or ObjC++. 2985 if (!getLangOpts().CPlusPlus) 2986 return false; 2987 2988 // Turn off ADL when we find certain kinds of declarations during 2989 // normal lookup: 2990 for (NamedDecl *D : R) { 2991 // C++0x [basic.lookup.argdep]p3: 2992 // -- a declaration of a class member 2993 // Since using decls preserve this property, we check this on the 2994 // original decl. 2995 if (D->isCXXClassMember()) 2996 return false; 2997 2998 // C++0x [basic.lookup.argdep]p3: 2999 // -- a block-scope function declaration that is not a 3000 // using-declaration 3001 // NOTE: we also trigger this for function templates (in fact, we 3002 // don't check the decl type at all, since all other decl types 3003 // turn off ADL anyway). 3004 if (isa<UsingShadowDecl>(D)) 3005 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3006 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3007 return false; 3008 3009 // C++0x [basic.lookup.argdep]p3: 3010 // -- a declaration that is neither a function or a function 3011 // template 3012 // And also for builtin functions. 3013 if (isa<FunctionDecl>(D)) { 3014 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3015 3016 // But also builtin functions. 3017 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3018 return false; 3019 } else if (!isa<FunctionTemplateDecl>(D)) 3020 return false; 3021 } 3022 3023 return true; 3024 } 3025 3026 3027 /// Diagnoses obvious problems with the use of the given declaration 3028 /// as an expression. This is only actually called for lookups that 3029 /// were not overloaded, and it doesn't promise that the declaration 3030 /// will in fact be used. 3031 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3032 if (D->isInvalidDecl()) 3033 return true; 3034 3035 if (isa<TypedefNameDecl>(D)) { 3036 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3037 return true; 3038 } 3039 3040 if (isa<ObjCInterfaceDecl>(D)) { 3041 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3042 return true; 3043 } 3044 3045 if (isa<NamespaceDecl>(D)) { 3046 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3047 return true; 3048 } 3049 3050 return false; 3051 } 3052 3053 // Certain multiversion types should be treated as overloaded even when there is 3054 // only one result. 3055 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3056 assert(R.isSingleResult() && "Expected only a single result"); 3057 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3058 return FD && 3059 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3060 } 3061 3062 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3063 LookupResult &R, bool NeedsADL, 3064 bool AcceptInvalidDecl) { 3065 // If this is a single, fully-resolved result and we don't need ADL, 3066 // just build an ordinary singleton decl ref. 3067 if (!NeedsADL && R.isSingleResult() && 3068 !R.getAsSingle<FunctionTemplateDecl>() && 3069 !ShouldLookupResultBeMultiVersionOverload(R)) 3070 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3071 R.getRepresentativeDecl(), nullptr, 3072 AcceptInvalidDecl); 3073 3074 // We only need to check the declaration if there's exactly one 3075 // result, because in the overloaded case the results can only be 3076 // functions and function templates. 3077 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3078 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3079 return ExprError(); 3080 3081 // Otherwise, just build an unresolved lookup expression. Suppress 3082 // any lookup-related diagnostics; we'll hash these out later, when 3083 // we've picked a target. 3084 R.suppressDiagnostics(); 3085 3086 UnresolvedLookupExpr *ULE 3087 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3088 SS.getWithLocInContext(Context), 3089 R.getLookupNameInfo(), 3090 NeedsADL, R.isOverloadedResult(), 3091 R.begin(), R.end()); 3092 3093 return ULE; 3094 } 3095 3096 static void 3097 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3098 ValueDecl *var, DeclContext *DC); 3099 3100 /// Complete semantic analysis for a reference to the given declaration. 3101 ExprResult Sema::BuildDeclarationNameExpr( 3102 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3103 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3104 bool AcceptInvalidDecl) { 3105 assert(D && "Cannot refer to a NULL declaration"); 3106 assert(!isa<FunctionTemplateDecl>(D) && 3107 "Cannot refer unambiguously to a function template"); 3108 3109 SourceLocation Loc = NameInfo.getLoc(); 3110 if (CheckDeclInExpr(*this, Loc, D)) 3111 return ExprError(); 3112 3113 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3114 // Specifically diagnose references to class templates that are missing 3115 // a template argument list. 3116 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3117 return ExprError(); 3118 } 3119 3120 // Make sure that we're referring to a value. 3121 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3122 if (!VD) { 3123 Diag(Loc, diag::err_ref_non_value) 3124 << D << SS.getRange(); 3125 Diag(D->getLocation(), diag::note_declared_at); 3126 return ExprError(); 3127 } 3128 3129 // Check whether this declaration can be used. Note that we suppress 3130 // this check when we're going to perform argument-dependent lookup 3131 // on this function name, because this might not be the function 3132 // that overload resolution actually selects. 3133 if (DiagnoseUseOfDecl(VD, Loc)) 3134 return ExprError(); 3135 3136 // Only create DeclRefExpr's for valid Decl's. 3137 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3138 return ExprError(); 3139 3140 // Handle members of anonymous structs and unions. If we got here, 3141 // and the reference is to a class member indirect field, then this 3142 // must be the subject of a pointer-to-member expression. 3143 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3144 if (!indirectField->isCXXClassMember()) 3145 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3146 indirectField); 3147 3148 { 3149 QualType type = VD->getType(); 3150 if (type.isNull()) 3151 return ExprError(); 3152 ExprValueKind valueKind = VK_RValue; 3153 3154 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3155 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3156 // is expanded by some outer '...' in the context of the use. 3157 type = type.getNonPackExpansionType(); 3158 3159 switch (D->getKind()) { 3160 // Ignore all the non-ValueDecl kinds. 3161 #define ABSTRACT_DECL(kind) 3162 #define VALUE(type, base) 3163 #define DECL(type, base) \ 3164 case Decl::type: 3165 #include "clang/AST/DeclNodes.inc" 3166 llvm_unreachable("invalid value decl kind"); 3167 3168 // These shouldn't make it here. 3169 case Decl::ObjCAtDefsField: 3170 llvm_unreachable("forming non-member reference to ivar?"); 3171 3172 // Enum constants are always r-values and never references. 3173 // Unresolved using declarations are dependent. 3174 case Decl::EnumConstant: 3175 case Decl::UnresolvedUsingValue: 3176 case Decl::OMPDeclareReduction: 3177 case Decl::OMPDeclareMapper: 3178 valueKind = VK_RValue; 3179 break; 3180 3181 // Fields and indirect fields that got here must be for 3182 // pointer-to-member expressions; we just call them l-values for 3183 // internal consistency, because this subexpression doesn't really 3184 // exist in the high-level semantics. 3185 case Decl::Field: 3186 case Decl::IndirectField: 3187 case Decl::ObjCIvar: 3188 assert(getLangOpts().CPlusPlus && 3189 "building reference to field in C?"); 3190 3191 // These can't have reference type in well-formed programs, but 3192 // for internal consistency we do this anyway. 3193 type = type.getNonReferenceType(); 3194 valueKind = VK_LValue; 3195 break; 3196 3197 // Non-type template parameters are either l-values or r-values 3198 // depending on the type. 3199 case Decl::NonTypeTemplateParm: { 3200 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3201 type = reftype->getPointeeType(); 3202 valueKind = VK_LValue; // even if the parameter is an r-value reference 3203 break; 3204 } 3205 3206 // For non-references, we need to strip qualifiers just in case 3207 // the template parameter was declared as 'const int' or whatever. 3208 valueKind = VK_RValue; 3209 type = type.getUnqualifiedType(); 3210 break; 3211 } 3212 3213 case Decl::Var: 3214 case Decl::VarTemplateSpecialization: 3215 case Decl::VarTemplatePartialSpecialization: 3216 case Decl::Decomposition: 3217 case Decl::OMPCapturedExpr: 3218 // In C, "extern void blah;" is valid and is an r-value. 3219 if (!getLangOpts().CPlusPlus && 3220 !type.hasQualifiers() && 3221 type->isVoidType()) { 3222 valueKind = VK_RValue; 3223 break; 3224 } 3225 LLVM_FALLTHROUGH; 3226 3227 case Decl::ImplicitParam: 3228 case Decl::ParmVar: { 3229 // These are always l-values. 3230 valueKind = VK_LValue; 3231 type = type.getNonReferenceType(); 3232 3233 // FIXME: Does the addition of const really only apply in 3234 // potentially-evaluated contexts? Since the variable isn't actually 3235 // captured in an unevaluated context, it seems that the answer is no. 3236 if (!isUnevaluatedContext()) { 3237 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3238 if (!CapturedType.isNull()) 3239 type = CapturedType; 3240 } 3241 3242 break; 3243 } 3244 3245 case Decl::Binding: { 3246 // These are always lvalues. 3247 valueKind = VK_LValue; 3248 type = type.getNonReferenceType(); 3249 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3250 // decides how that's supposed to work. 3251 auto *BD = cast<BindingDecl>(VD); 3252 if (BD->getDeclContext() != CurContext) { 3253 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3254 if (DD && DD->hasLocalStorage()) 3255 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3256 } 3257 break; 3258 } 3259 3260 case Decl::Function: { 3261 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3262 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3263 type = Context.BuiltinFnTy; 3264 valueKind = VK_RValue; 3265 break; 3266 } 3267 } 3268 3269 const FunctionType *fty = type->castAs<FunctionType>(); 3270 3271 // If we're referring to a function with an __unknown_anytype 3272 // result type, make the entire expression __unknown_anytype. 3273 if (fty->getReturnType() == Context.UnknownAnyTy) { 3274 type = Context.UnknownAnyTy; 3275 valueKind = VK_RValue; 3276 break; 3277 } 3278 3279 // Functions are l-values in C++. 3280 if (getLangOpts().CPlusPlus) { 3281 valueKind = VK_LValue; 3282 break; 3283 } 3284 3285 // C99 DR 316 says that, if a function type comes from a 3286 // function definition (without a prototype), that type is only 3287 // used for checking compatibility. Therefore, when referencing 3288 // the function, we pretend that we don't have the full function 3289 // type. 3290 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3291 isa<FunctionProtoType>(fty)) 3292 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3293 fty->getExtInfo()); 3294 3295 // Functions are r-values in C. 3296 valueKind = VK_RValue; 3297 break; 3298 } 3299 3300 case Decl::CXXDeductionGuide: 3301 llvm_unreachable("building reference to deduction guide"); 3302 3303 case Decl::MSProperty: 3304 case Decl::MSGuid: 3305 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3306 // or duplicated between host and device? 3307 valueKind = VK_LValue; 3308 break; 3309 3310 case Decl::CXXMethod: 3311 // If we're referring to a method with an __unknown_anytype 3312 // result type, make the entire expression __unknown_anytype. 3313 // This should only be possible with a type written directly. 3314 if (const FunctionProtoType *proto 3315 = dyn_cast<FunctionProtoType>(VD->getType())) 3316 if (proto->getReturnType() == Context.UnknownAnyTy) { 3317 type = Context.UnknownAnyTy; 3318 valueKind = VK_RValue; 3319 break; 3320 } 3321 3322 // C++ methods are l-values if static, r-values if non-static. 3323 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3324 valueKind = VK_LValue; 3325 break; 3326 } 3327 LLVM_FALLTHROUGH; 3328 3329 case Decl::CXXConversion: 3330 case Decl::CXXDestructor: 3331 case Decl::CXXConstructor: 3332 valueKind = VK_RValue; 3333 break; 3334 } 3335 3336 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3337 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3338 TemplateArgs); 3339 } 3340 } 3341 3342 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3343 SmallString<32> &Target) { 3344 Target.resize(CharByteWidth * (Source.size() + 1)); 3345 char *ResultPtr = &Target[0]; 3346 const llvm::UTF8 *ErrorPtr; 3347 bool success = 3348 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3349 (void)success; 3350 assert(success); 3351 Target.resize(ResultPtr - &Target[0]); 3352 } 3353 3354 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3355 PredefinedExpr::IdentKind IK) { 3356 // Pick the current block, lambda, captured statement or function. 3357 Decl *currentDecl = nullptr; 3358 if (const BlockScopeInfo *BSI = getCurBlock()) 3359 currentDecl = BSI->TheDecl; 3360 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3361 currentDecl = LSI->CallOperator; 3362 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3363 currentDecl = CSI->TheCapturedDecl; 3364 else 3365 currentDecl = getCurFunctionOrMethodDecl(); 3366 3367 if (!currentDecl) { 3368 Diag(Loc, diag::ext_predef_outside_function); 3369 currentDecl = Context.getTranslationUnitDecl(); 3370 } 3371 3372 QualType ResTy; 3373 StringLiteral *SL = nullptr; 3374 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3375 ResTy = Context.DependentTy; 3376 else { 3377 // Pre-defined identifiers are of type char[x], where x is the length of 3378 // the string. 3379 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3380 unsigned Length = Str.length(); 3381 3382 llvm::APInt LengthI(32, Length + 1); 3383 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3384 ResTy = 3385 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3386 SmallString<32> RawChars; 3387 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3388 Str, RawChars); 3389 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3390 ArrayType::Normal, 3391 /*IndexTypeQuals*/ 0); 3392 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3393 /*Pascal*/ false, ResTy, Loc); 3394 } else { 3395 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3396 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3397 ArrayType::Normal, 3398 /*IndexTypeQuals*/ 0); 3399 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3400 /*Pascal*/ false, ResTy, Loc); 3401 } 3402 } 3403 3404 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3405 } 3406 3407 static std::pair<QualType, StringLiteral *> 3408 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3409 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3410 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3411 3412 if (OpType->isDependentType()) { 3413 Result.first = Context.DependentTy; 3414 return Result; 3415 } 3416 3417 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3418 llvm::APInt Length(32, Str.length() + 1); 3419 Result.first = 3420 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3421 Result.first = Context.getConstantArrayType( 3422 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3423 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3424 /*Pascal*/ false, Result.first, OpLoc); 3425 return Result; 3426 } 3427 3428 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3429 TypeSourceInfo *Operand) { 3430 QualType ResultTy; 3431 StringLiteral *SL; 3432 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3433 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3434 3435 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3436 PredefinedExpr::UniqueStableNameType, SL, 3437 Operand); 3438 } 3439 3440 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3441 Expr *E) { 3442 QualType ResultTy; 3443 StringLiteral *SL; 3444 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3445 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3446 3447 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3448 PredefinedExpr::UniqueStableNameExpr, SL, E); 3449 } 3450 3451 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3452 SourceLocation L, SourceLocation R, 3453 ParsedType Ty) { 3454 TypeSourceInfo *TInfo = nullptr; 3455 QualType T = GetTypeFromParser(Ty, &TInfo); 3456 3457 if (T.isNull()) 3458 return ExprError(); 3459 if (!TInfo) 3460 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3461 3462 return BuildUniqueStableName(OpLoc, TInfo); 3463 } 3464 3465 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3466 SourceLocation L, SourceLocation R, 3467 Expr *E) { 3468 return BuildUniqueStableName(OpLoc, E); 3469 } 3470 3471 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3472 PredefinedExpr::IdentKind IK; 3473 3474 switch (Kind) { 3475 default: llvm_unreachable("Unknown simple primary expr!"); 3476 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3477 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3478 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3479 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3480 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3481 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3482 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3483 } 3484 3485 return BuildPredefinedExpr(Loc, IK); 3486 } 3487 3488 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3489 SmallString<16> CharBuffer; 3490 bool Invalid = false; 3491 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3492 if (Invalid) 3493 return ExprError(); 3494 3495 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3496 PP, Tok.getKind()); 3497 if (Literal.hadError()) 3498 return ExprError(); 3499 3500 QualType Ty; 3501 if (Literal.isWide()) 3502 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3503 else if (Literal.isUTF8() && getLangOpts().Char8) 3504 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3505 else if (Literal.isUTF16()) 3506 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3507 else if (Literal.isUTF32()) 3508 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3509 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3510 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3511 else 3512 Ty = Context.CharTy; // 'x' -> char in C++ 3513 3514 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3515 if (Literal.isWide()) 3516 Kind = CharacterLiteral::Wide; 3517 else if (Literal.isUTF16()) 3518 Kind = CharacterLiteral::UTF16; 3519 else if (Literal.isUTF32()) 3520 Kind = CharacterLiteral::UTF32; 3521 else if (Literal.isUTF8()) 3522 Kind = CharacterLiteral::UTF8; 3523 3524 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3525 Tok.getLocation()); 3526 3527 if (Literal.getUDSuffix().empty()) 3528 return Lit; 3529 3530 // We're building a user-defined literal. 3531 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3532 SourceLocation UDSuffixLoc = 3533 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3534 3535 // Make sure we're allowed user-defined literals here. 3536 if (!UDLScope) 3537 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3538 3539 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3540 // operator "" X (ch) 3541 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3542 Lit, Tok.getLocation()); 3543 } 3544 3545 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3546 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3547 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3548 Context.IntTy, Loc); 3549 } 3550 3551 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3552 QualType Ty, SourceLocation Loc) { 3553 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3554 3555 using llvm::APFloat; 3556 APFloat Val(Format); 3557 3558 APFloat::opStatus result = Literal.GetFloatValue(Val); 3559 3560 // Overflow is always an error, but underflow is only an error if 3561 // we underflowed to zero (APFloat reports denormals as underflow). 3562 if ((result & APFloat::opOverflow) || 3563 ((result & APFloat::opUnderflow) && Val.isZero())) { 3564 unsigned diagnostic; 3565 SmallString<20> buffer; 3566 if (result & APFloat::opOverflow) { 3567 diagnostic = diag::warn_float_overflow; 3568 APFloat::getLargest(Format).toString(buffer); 3569 } else { 3570 diagnostic = diag::warn_float_underflow; 3571 APFloat::getSmallest(Format).toString(buffer); 3572 } 3573 3574 S.Diag(Loc, diagnostic) 3575 << Ty 3576 << StringRef(buffer.data(), buffer.size()); 3577 } 3578 3579 bool isExact = (result == APFloat::opOK); 3580 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3581 } 3582 3583 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3584 assert(E && "Invalid expression"); 3585 3586 if (E->isValueDependent()) 3587 return false; 3588 3589 QualType QT = E->getType(); 3590 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3591 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3592 return true; 3593 } 3594 3595 llvm::APSInt ValueAPS; 3596 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3597 3598 if (R.isInvalid()) 3599 return true; 3600 3601 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3602 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3603 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3604 << ValueAPS.toString(10) << ValueIsPositive; 3605 return true; 3606 } 3607 3608 return false; 3609 } 3610 3611 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3612 // Fast path for a single digit (which is quite common). A single digit 3613 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3614 if (Tok.getLength() == 1) { 3615 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3616 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3617 } 3618 3619 SmallString<128> SpellingBuffer; 3620 // NumericLiteralParser wants to overread by one character. Add padding to 3621 // the buffer in case the token is copied to the buffer. If getSpelling() 3622 // returns a StringRef to the memory buffer, it should have a null char at 3623 // the EOF, so it is also safe. 3624 SpellingBuffer.resize(Tok.getLength() + 1); 3625 3626 // Get the spelling of the token, which eliminates trigraphs, etc. 3627 bool Invalid = false; 3628 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3629 if (Invalid) 3630 return ExprError(); 3631 3632 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3633 if (Literal.hadError) 3634 return ExprError(); 3635 3636 if (Literal.hasUDSuffix()) { 3637 // We're building a user-defined literal. 3638 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3639 SourceLocation UDSuffixLoc = 3640 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3641 3642 // Make sure we're allowed user-defined literals here. 3643 if (!UDLScope) 3644 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3645 3646 QualType CookedTy; 3647 if (Literal.isFloatingLiteral()) { 3648 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3649 // long double, the literal is treated as a call of the form 3650 // operator "" X (f L) 3651 CookedTy = Context.LongDoubleTy; 3652 } else { 3653 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3654 // unsigned long long, the literal is treated as a call of the form 3655 // operator "" X (n ULL) 3656 CookedTy = Context.UnsignedLongLongTy; 3657 } 3658 3659 DeclarationName OpName = 3660 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3661 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3662 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3663 3664 SourceLocation TokLoc = Tok.getLocation(); 3665 3666 // Perform literal operator lookup to determine if we're building a raw 3667 // literal or a cooked one. 3668 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3669 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3670 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3671 /*AllowStringTemplate*/ false, 3672 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3673 case LOLR_ErrorNoDiagnostic: 3674 // Lookup failure for imaginary constants isn't fatal, there's still the 3675 // GNU extension producing _Complex types. 3676 break; 3677 case LOLR_Error: 3678 return ExprError(); 3679 case LOLR_Cooked: { 3680 Expr *Lit; 3681 if (Literal.isFloatingLiteral()) { 3682 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3683 } else { 3684 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3685 if (Literal.GetIntegerValue(ResultVal)) 3686 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3687 << /* Unsigned */ 1; 3688 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3689 Tok.getLocation()); 3690 } 3691 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3692 } 3693 3694 case LOLR_Raw: { 3695 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3696 // literal is treated as a call of the form 3697 // operator "" X ("n") 3698 unsigned Length = Literal.getUDSuffixOffset(); 3699 QualType StrTy = Context.getConstantArrayType( 3700 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3701 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3702 Expr *Lit = StringLiteral::Create( 3703 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3704 /*Pascal*/false, StrTy, &TokLoc, 1); 3705 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3706 } 3707 3708 case LOLR_Template: { 3709 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3710 // template), L is treated as a call fo the form 3711 // operator "" X <'c1', 'c2', ... 'ck'>() 3712 // where n is the source character sequence c1 c2 ... ck. 3713 TemplateArgumentListInfo ExplicitArgs; 3714 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3715 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3716 llvm::APSInt Value(CharBits, CharIsUnsigned); 3717 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3718 Value = TokSpelling[I]; 3719 TemplateArgument Arg(Context, Value, Context.CharTy); 3720 TemplateArgumentLocInfo ArgInfo; 3721 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3722 } 3723 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3724 &ExplicitArgs); 3725 } 3726 case LOLR_StringTemplate: 3727 llvm_unreachable("unexpected literal operator lookup result"); 3728 } 3729 } 3730 3731 Expr *Res; 3732 3733 if (Literal.isFixedPointLiteral()) { 3734 QualType Ty; 3735 3736 if (Literal.isAccum) { 3737 if (Literal.isHalf) { 3738 Ty = Context.ShortAccumTy; 3739 } else if (Literal.isLong) { 3740 Ty = Context.LongAccumTy; 3741 } else { 3742 Ty = Context.AccumTy; 3743 } 3744 } else if (Literal.isFract) { 3745 if (Literal.isHalf) { 3746 Ty = Context.ShortFractTy; 3747 } else if (Literal.isLong) { 3748 Ty = Context.LongFractTy; 3749 } else { 3750 Ty = Context.FractTy; 3751 } 3752 } 3753 3754 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3755 3756 bool isSigned = !Literal.isUnsigned; 3757 unsigned scale = Context.getFixedPointScale(Ty); 3758 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3759 3760 llvm::APInt Val(bit_width, 0, isSigned); 3761 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3762 bool ValIsZero = Val.isNullValue() && !Overflowed; 3763 3764 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3765 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3766 // Clause 6.4.4 - The value of a constant shall be in the range of 3767 // representable values for its type, with exception for constants of a 3768 // fract type with a value of exactly 1; such a constant shall denote 3769 // the maximal value for the type. 3770 --Val; 3771 else if (Val.ugt(MaxVal) || Overflowed) 3772 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3773 3774 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3775 Tok.getLocation(), scale); 3776 } else if (Literal.isFloatingLiteral()) { 3777 QualType Ty; 3778 if (Literal.isHalf){ 3779 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3780 Ty = Context.HalfTy; 3781 else { 3782 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3783 return ExprError(); 3784 } 3785 } else if (Literal.isFloat) 3786 Ty = Context.FloatTy; 3787 else if (Literal.isLong) 3788 Ty = Context.LongDoubleTy; 3789 else if (Literal.isFloat16) 3790 Ty = Context.Float16Ty; 3791 else if (Literal.isFloat128) 3792 Ty = Context.Float128Ty; 3793 else 3794 Ty = Context.DoubleTy; 3795 3796 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3797 3798 if (Ty == Context.DoubleTy) { 3799 if (getLangOpts().SinglePrecisionConstants) { 3800 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3801 if (BTy->getKind() != BuiltinType::Float) { 3802 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3803 } 3804 } else if (getLangOpts().OpenCL && 3805 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3806 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3807 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3808 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3809 } 3810 } 3811 } else if (!Literal.isIntegerLiteral()) { 3812 return ExprError(); 3813 } else { 3814 QualType Ty; 3815 3816 // 'long long' is a C99 or C++11 feature. 3817 if (!getLangOpts().C99 && Literal.isLongLong) { 3818 if (getLangOpts().CPlusPlus) 3819 Diag(Tok.getLocation(), 3820 getLangOpts().CPlusPlus11 ? 3821 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3822 else 3823 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3824 } 3825 3826 // Get the value in the widest-possible width. 3827 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3828 llvm::APInt ResultVal(MaxWidth, 0); 3829 3830 if (Literal.GetIntegerValue(ResultVal)) { 3831 // If this value didn't fit into uintmax_t, error and force to ull. 3832 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3833 << /* Unsigned */ 1; 3834 Ty = Context.UnsignedLongLongTy; 3835 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3836 "long long is not intmax_t?"); 3837 } else { 3838 // If this value fits into a ULL, try to figure out what else it fits into 3839 // according to the rules of C99 6.4.4.1p5. 3840 3841 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3842 // be an unsigned int. 3843 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3844 3845 // Check from smallest to largest, picking the smallest type we can. 3846 unsigned Width = 0; 3847 3848 // Microsoft specific integer suffixes are explicitly sized. 3849 if (Literal.MicrosoftInteger) { 3850 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3851 Width = 8; 3852 Ty = Context.CharTy; 3853 } else { 3854 Width = Literal.MicrosoftInteger; 3855 Ty = Context.getIntTypeForBitwidth(Width, 3856 /*Signed=*/!Literal.isUnsigned); 3857 } 3858 } 3859 3860 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3861 // Are int/unsigned possibilities? 3862 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3863 3864 // Does it fit in a unsigned int? 3865 if (ResultVal.isIntN(IntSize)) { 3866 // Does it fit in a signed int? 3867 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3868 Ty = Context.IntTy; 3869 else if (AllowUnsigned) 3870 Ty = Context.UnsignedIntTy; 3871 Width = IntSize; 3872 } 3873 } 3874 3875 // Are long/unsigned long possibilities? 3876 if (Ty.isNull() && !Literal.isLongLong) { 3877 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3878 3879 // Does it fit in a unsigned long? 3880 if (ResultVal.isIntN(LongSize)) { 3881 // Does it fit in a signed long? 3882 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3883 Ty = Context.LongTy; 3884 else if (AllowUnsigned) 3885 Ty = Context.UnsignedLongTy; 3886 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3887 // is compatible. 3888 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3889 const unsigned LongLongSize = 3890 Context.getTargetInfo().getLongLongWidth(); 3891 Diag(Tok.getLocation(), 3892 getLangOpts().CPlusPlus 3893 ? Literal.isLong 3894 ? diag::warn_old_implicitly_unsigned_long_cxx 3895 : /*C++98 UB*/ diag:: 3896 ext_old_implicitly_unsigned_long_cxx 3897 : diag::warn_old_implicitly_unsigned_long) 3898 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3899 : /*will be ill-formed*/ 1); 3900 Ty = Context.UnsignedLongTy; 3901 } 3902 Width = LongSize; 3903 } 3904 } 3905 3906 // Check long long if needed. 3907 if (Ty.isNull()) { 3908 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3909 3910 // Does it fit in a unsigned long long? 3911 if (ResultVal.isIntN(LongLongSize)) { 3912 // Does it fit in a signed long long? 3913 // To be compatible with MSVC, hex integer literals ending with the 3914 // LL or i64 suffix are always signed in Microsoft mode. 3915 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3916 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3917 Ty = Context.LongLongTy; 3918 else if (AllowUnsigned) 3919 Ty = Context.UnsignedLongLongTy; 3920 Width = LongLongSize; 3921 } 3922 } 3923 3924 // If we still couldn't decide a type, we probably have something that 3925 // does not fit in a signed long long, but has no U suffix. 3926 if (Ty.isNull()) { 3927 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3928 Ty = Context.UnsignedLongLongTy; 3929 Width = Context.getTargetInfo().getLongLongWidth(); 3930 } 3931 3932 if (ResultVal.getBitWidth() != Width) 3933 ResultVal = ResultVal.trunc(Width); 3934 } 3935 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3936 } 3937 3938 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3939 if (Literal.isImaginary) { 3940 Res = new (Context) ImaginaryLiteral(Res, 3941 Context.getComplexType(Res->getType())); 3942 3943 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3944 } 3945 return Res; 3946 } 3947 3948 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3949 assert(E && "ActOnParenExpr() missing expr"); 3950 return new (Context) ParenExpr(L, R, E); 3951 } 3952 3953 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3954 SourceLocation Loc, 3955 SourceRange ArgRange) { 3956 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3957 // scalar or vector data type argument..." 3958 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3959 // type (C99 6.2.5p18) or void. 3960 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3961 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3962 << T << ArgRange; 3963 return true; 3964 } 3965 3966 assert((T->isVoidType() || !T->isIncompleteType()) && 3967 "Scalar types should always be complete"); 3968 return false; 3969 } 3970 3971 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3972 SourceLocation Loc, 3973 SourceRange ArgRange, 3974 UnaryExprOrTypeTrait TraitKind) { 3975 // Invalid types must be hard errors for SFINAE in C++. 3976 if (S.LangOpts.CPlusPlus) 3977 return true; 3978 3979 // C99 6.5.3.4p1: 3980 if (T->isFunctionType() && 3981 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3982 TraitKind == UETT_PreferredAlignOf)) { 3983 // sizeof(function)/alignof(function) is allowed as an extension. 3984 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3985 << getTraitSpelling(TraitKind) << ArgRange; 3986 return false; 3987 } 3988 3989 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3990 // this is an error (OpenCL v1.1 s6.3.k) 3991 if (T->isVoidType()) { 3992 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3993 : diag::ext_sizeof_alignof_void_type; 3994 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 3995 return false; 3996 } 3997 3998 return true; 3999 } 4000 4001 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4002 SourceLocation Loc, 4003 SourceRange ArgRange, 4004 UnaryExprOrTypeTrait TraitKind) { 4005 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4006 // runtime doesn't allow it. 4007 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4008 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4009 << T << (TraitKind == UETT_SizeOf) 4010 << ArgRange; 4011 return true; 4012 } 4013 4014 return false; 4015 } 4016 4017 /// Check whether E is a pointer from a decayed array type (the decayed 4018 /// pointer type is equal to T) and emit a warning if it is. 4019 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4020 Expr *E) { 4021 // Don't warn if the operation changed the type. 4022 if (T != E->getType()) 4023 return; 4024 4025 // Now look for array decays. 4026 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4027 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4028 return; 4029 4030 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4031 << ICE->getType() 4032 << ICE->getSubExpr()->getType(); 4033 } 4034 4035 /// Check the constraints on expression operands to unary type expression 4036 /// and type traits. 4037 /// 4038 /// Completes any types necessary and validates the constraints on the operand 4039 /// expression. The logic mostly mirrors the type-based overload, but may modify 4040 /// the expression as it completes the type for that expression through template 4041 /// instantiation, etc. 4042 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4043 UnaryExprOrTypeTrait ExprKind) { 4044 QualType ExprTy = E->getType(); 4045 assert(!ExprTy->isReferenceType()); 4046 4047 bool IsUnevaluatedOperand = 4048 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4049 ExprKind == UETT_PreferredAlignOf); 4050 if (IsUnevaluatedOperand) { 4051 ExprResult Result = CheckUnevaluatedOperand(E); 4052 if (Result.isInvalid()) 4053 return true; 4054 E = Result.get(); 4055 } 4056 4057 if (ExprKind == UETT_VecStep) 4058 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4059 E->getSourceRange()); 4060 4061 // Explicitly list some types as extensions. 4062 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4063 E->getSourceRange(), ExprKind)) 4064 return false; 4065 4066 // 'alignof' applied to an expression only requires the base element type of 4067 // the expression to be complete. 'sizeof' requires the expression's type to 4068 // be complete (and will attempt to complete it if it's an array of unknown 4069 // bound). 4070 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4071 if (RequireCompleteSizedType( 4072 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4073 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4074 getTraitSpelling(ExprKind), E->getSourceRange())) 4075 return true; 4076 } else { 4077 if (RequireCompleteSizedExprType( 4078 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4079 getTraitSpelling(ExprKind), E->getSourceRange())) 4080 return true; 4081 } 4082 4083 // Completing the expression's type may have changed it. 4084 ExprTy = E->getType(); 4085 assert(!ExprTy->isReferenceType()); 4086 4087 if (ExprTy->isFunctionType()) { 4088 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4089 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4090 return true; 4091 } 4092 4093 // The operand for sizeof and alignof is in an unevaluated expression context, 4094 // so side effects could result in unintended consequences. 4095 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4096 E->HasSideEffects(Context, false)) 4097 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4098 4099 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4100 E->getSourceRange(), ExprKind)) 4101 return true; 4102 4103 if (ExprKind == UETT_SizeOf) { 4104 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4105 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4106 QualType OType = PVD->getOriginalType(); 4107 QualType Type = PVD->getType(); 4108 if (Type->isPointerType() && OType->isArrayType()) { 4109 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4110 << Type << OType; 4111 Diag(PVD->getLocation(), diag::note_declared_at); 4112 } 4113 } 4114 } 4115 4116 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4117 // decays into a pointer and returns an unintended result. This is most 4118 // likely a typo for "sizeof(array) op x". 4119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4120 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4121 BO->getLHS()); 4122 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4123 BO->getRHS()); 4124 } 4125 } 4126 4127 return false; 4128 } 4129 4130 /// Check the constraints on operands to unary expression and type 4131 /// traits. 4132 /// 4133 /// This will complete any types necessary, and validate the various constraints 4134 /// on those operands. 4135 /// 4136 /// The UsualUnaryConversions() function is *not* called by this routine. 4137 /// C99 6.3.2.1p[2-4] all state: 4138 /// Except when it is the operand of the sizeof operator ... 4139 /// 4140 /// C++ [expr.sizeof]p4 4141 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4142 /// standard conversions are not applied to the operand of sizeof. 4143 /// 4144 /// This policy is followed for all of the unary trait expressions. 4145 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4146 SourceLocation OpLoc, 4147 SourceRange ExprRange, 4148 UnaryExprOrTypeTrait ExprKind) { 4149 if (ExprType->isDependentType()) 4150 return false; 4151 4152 // C++ [expr.sizeof]p2: 4153 // When applied to a reference or a reference type, the result 4154 // is the size of the referenced type. 4155 // C++11 [expr.alignof]p3: 4156 // When alignof is applied to a reference type, the result 4157 // shall be the alignment of the referenced type. 4158 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4159 ExprType = Ref->getPointeeType(); 4160 4161 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4162 // When alignof or _Alignof is applied to an array type, the result 4163 // is the alignment of the element type. 4164 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4165 ExprKind == UETT_OpenMPRequiredSimdAlign) 4166 ExprType = Context.getBaseElementType(ExprType); 4167 4168 if (ExprKind == UETT_VecStep) 4169 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4170 4171 // Explicitly list some types as extensions. 4172 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4173 ExprKind)) 4174 return false; 4175 4176 if (RequireCompleteSizedType( 4177 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4178 getTraitSpelling(ExprKind), ExprRange)) 4179 return true; 4180 4181 if (ExprType->isFunctionType()) { 4182 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4183 << getTraitSpelling(ExprKind) << ExprRange; 4184 return true; 4185 } 4186 4187 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4188 ExprKind)) 4189 return true; 4190 4191 return false; 4192 } 4193 4194 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4195 // Cannot know anything else if the expression is dependent. 4196 if (E->isTypeDependent()) 4197 return false; 4198 4199 if (E->getObjectKind() == OK_BitField) { 4200 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4201 << 1 << E->getSourceRange(); 4202 return true; 4203 } 4204 4205 ValueDecl *D = nullptr; 4206 Expr *Inner = E->IgnoreParens(); 4207 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4208 D = DRE->getDecl(); 4209 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4210 D = ME->getMemberDecl(); 4211 } 4212 4213 // If it's a field, require the containing struct to have a 4214 // complete definition so that we can compute the layout. 4215 // 4216 // This can happen in C++11 onwards, either by naming the member 4217 // in a way that is not transformed into a member access expression 4218 // (in an unevaluated operand, for instance), or by naming the member 4219 // in a trailing-return-type. 4220 // 4221 // For the record, since __alignof__ on expressions is a GCC 4222 // extension, GCC seems to permit this but always gives the 4223 // nonsensical answer 0. 4224 // 4225 // We don't really need the layout here --- we could instead just 4226 // directly check for all the appropriate alignment-lowing 4227 // attributes --- but that would require duplicating a lot of 4228 // logic that just isn't worth duplicating for such a marginal 4229 // use-case. 4230 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4231 // Fast path this check, since we at least know the record has a 4232 // definition if we can find a member of it. 4233 if (!FD->getParent()->isCompleteDefinition()) { 4234 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4235 << E->getSourceRange(); 4236 return true; 4237 } 4238 4239 // Otherwise, if it's a field, and the field doesn't have 4240 // reference type, then it must have a complete type (or be a 4241 // flexible array member, which we explicitly want to 4242 // white-list anyway), which makes the following checks trivial. 4243 if (!FD->getType()->isReferenceType()) 4244 return false; 4245 } 4246 4247 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4248 } 4249 4250 bool Sema::CheckVecStepExpr(Expr *E) { 4251 E = E->IgnoreParens(); 4252 4253 // Cannot know anything else if the expression is dependent. 4254 if (E->isTypeDependent()) 4255 return false; 4256 4257 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4258 } 4259 4260 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4261 CapturingScopeInfo *CSI) { 4262 assert(T->isVariablyModifiedType()); 4263 assert(CSI != nullptr); 4264 4265 // We're going to walk down into the type and look for VLA expressions. 4266 do { 4267 const Type *Ty = T.getTypePtr(); 4268 switch (Ty->getTypeClass()) { 4269 #define TYPE(Class, Base) 4270 #define ABSTRACT_TYPE(Class, Base) 4271 #define NON_CANONICAL_TYPE(Class, Base) 4272 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4273 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4274 #include "clang/AST/TypeNodes.inc" 4275 T = QualType(); 4276 break; 4277 // These types are never variably-modified. 4278 case Type::Builtin: 4279 case Type::Complex: 4280 case Type::Vector: 4281 case Type::ExtVector: 4282 case Type::ConstantMatrix: 4283 case Type::Record: 4284 case Type::Enum: 4285 case Type::Elaborated: 4286 case Type::TemplateSpecialization: 4287 case Type::ObjCObject: 4288 case Type::ObjCInterface: 4289 case Type::ObjCObjectPointer: 4290 case Type::ObjCTypeParam: 4291 case Type::Pipe: 4292 case Type::ExtInt: 4293 llvm_unreachable("type class is never variably-modified!"); 4294 case Type::Adjusted: 4295 T = cast<AdjustedType>(Ty)->getOriginalType(); 4296 break; 4297 case Type::Decayed: 4298 T = cast<DecayedType>(Ty)->getPointeeType(); 4299 break; 4300 case Type::Pointer: 4301 T = cast<PointerType>(Ty)->getPointeeType(); 4302 break; 4303 case Type::BlockPointer: 4304 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4305 break; 4306 case Type::LValueReference: 4307 case Type::RValueReference: 4308 T = cast<ReferenceType>(Ty)->getPointeeType(); 4309 break; 4310 case Type::MemberPointer: 4311 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4312 break; 4313 case Type::ConstantArray: 4314 case Type::IncompleteArray: 4315 // Losing element qualification here is fine. 4316 T = cast<ArrayType>(Ty)->getElementType(); 4317 break; 4318 case Type::VariableArray: { 4319 // Losing element qualification here is fine. 4320 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4321 4322 // Unknown size indication requires no size computation. 4323 // Otherwise, evaluate and record it. 4324 auto Size = VAT->getSizeExpr(); 4325 if (Size && !CSI->isVLATypeCaptured(VAT) && 4326 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4327 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4328 4329 T = VAT->getElementType(); 4330 break; 4331 } 4332 case Type::FunctionProto: 4333 case Type::FunctionNoProto: 4334 T = cast<FunctionType>(Ty)->getReturnType(); 4335 break; 4336 case Type::Paren: 4337 case Type::TypeOf: 4338 case Type::UnaryTransform: 4339 case Type::Attributed: 4340 case Type::SubstTemplateTypeParm: 4341 case Type::PackExpansion: 4342 case Type::MacroQualified: 4343 // Keep walking after single level desugaring. 4344 T = T.getSingleStepDesugaredType(Context); 4345 break; 4346 case Type::Typedef: 4347 T = cast<TypedefType>(Ty)->desugar(); 4348 break; 4349 case Type::Decltype: 4350 T = cast<DecltypeType>(Ty)->desugar(); 4351 break; 4352 case Type::Auto: 4353 case Type::DeducedTemplateSpecialization: 4354 T = cast<DeducedType>(Ty)->getDeducedType(); 4355 break; 4356 case Type::TypeOfExpr: 4357 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4358 break; 4359 case Type::Atomic: 4360 T = cast<AtomicType>(Ty)->getValueType(); 4361 break; 4362 } 4363 } while (!T.isNull() && T->isVariablyModifiedType()); 4364 } 4365 4366 /// Build a sizeof or alignof expression given a type operand. 4367 ExprResult 4368 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4369 SourceLocation OpLoc, 4370 UnaryExprOrTypeTrait ExprKind, 4371 SourceRange R) { 4372 if (!TInfo) 4373 return ExprError(); 4374 4375 QualType T = TInfo->getType(); 4376 4377 if (!T->isDependentType() && 4378 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4379 return ExprError(); 4380 4381 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4382 if (auto *TT = T->getAs<TypedefType>()) { 4383 for (auto I = FunctionScopes.rbegin(), 4384 E = std::prev(FunctionScopes.rend()); 4385 I != E; ++I) { 4386 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4387 if (CSI == nullptr) 4388 break; 4389 DeclContext *DC = nullptr; 4390 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4391 DC = LSI->CallOperator; 4392 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4393 DC = CRSI->TheCapturedDecl; 4394 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4395 DC = BSI->TheDecl; 4396 if (DC) { 4397 if (DC->containsDecl(TT->getDecl())) 4398 break; 4399 captureVariablyModifiedType(Context, T, CSI); 4400 } 4401 } 4402 } 4403 } 4404 4405 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4406 return new (Context) UnaryExprOrTypeTraitExpr( 4407 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4408 } 4409 4410 /// Build a sizeof or alignof expression given an expression 4411 /// operand. 4412 ExprResult 4413 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4414 UnaryExprOrTypeTrait ExprKind) { 4415 ExprResult PE = CheckPlaceholderExpr(E); 4416 if (PE.isInvalid()) 4417 return ExprError(); 4418 4419 E = PE.get(); 4420 4421 // Verify that the operand is valid. 4422 bool isInvalid = false; 4423 if (E->isTypeDependent()) { 4424 // Delay type-checking for type-dependent expressions. 4425 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4426 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4427 } else if (ExprKind == UETT_VecStep) { 4428 isInvalid = CheckVecStepExpr(E); 4429 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4430 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4431 isInvalid = true; 4432 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4433 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4434 isInvalid = true; 4435 } else { 4436 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4437 } 4438 4439 if (isInvalid) 4440 return ExprError(); 4441 4442 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4443 PE = TransformToPotentiallyEvaluated(E); 4444 if (PE.isInvalid()) return ExprError(); 4445 E = PE.get(); 4446 } 4447 4448 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4449 return new (Context) UnaryExprOrTypeTraitExpr( 4450 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4451 } 4452 4453 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4454 /// expr and the same for @c alignof and @c __alignof 4455 /// Note that the ArgRange is invalid if isType is false. 4456 ExprResult 4457 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4458 UnaryExprOrTypeTrait ExprKind, bool IsType, 4459 void *TyOrEx, SourceRange ArgRange) { 4460 // If error parsing type, ignore. 4461 if (!TyOrEx) return ExprError(); 4462 4463 if (IsType) { 4464 TypeSourceInfo *TInfo; 4465 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4466 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4467 } 4468 4469 Expr *ArgEx = (Expr *)TyOrEx; 4470 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4471 return Result; 4472 } 4473 4474 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4475 bool IsReal) { 4476 if (V.get()->isTypeDependent()) 4477 return S.Context.DependentTy; 4478 4479 // _Real and _Imag are only l-values for normal l-values. 4480 if (V.get()->getObjectKind() != OK_Ordinary) { 4481 V = S.DefaultLvalueConversion(V.get()); 4482 if (V.isInvalid()) 4483 return QualType(); 4484 } 4485 4486 // These operators return the element type of a complex type. 4487 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4488 return CT->getElementType(); 4489 4490 // Otherwise they pass through real integer and floating point types here. 4491 if (V.get()->getType()->isArithmeticType()) 4492 return V.get()->getType(); 4493 4494 // Test for placeholders. 4495 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4496 if (PR.isInvalid()) return QualType(); 4497 if (PR.get() != V.get()) { 4498 V = PR; 4499 return CheckRealImagOperand(S, V, Loc, IsReal); 4500 } 4501 4502 // Reject anything else. 4503 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4504 << (IsReal ? "__real" : "__imag"); 4505 return QualType(); 4506 } 4507 4508 4509 4510 ExprResult 4511 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4512 tok::TokenKind Kind, Expr *Input) { 4513 UnaryOperatorKind Opc; 4514 switch (Kind) { 4515 default: llvm_unreachable("Unknown unary op!"); 4516 case tok::plusplus: Opc = UO_PostInc; break; 4517 case tok::minusminus: Opc = UO_PostDec; break; 4518 } 4519 4520 // Since this might is a postfix expression, get rid of ParenListExprs. 4521 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4522 if (Result.isInvalid()) return ExprError(); 4523 Input = Result.get(); 4524 4525 return BuildUnaryOp(S, OpLoc, Opc, Input); 4526 } 4527 4528 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4529 /// 4530 /// \return true on error 4531 static bool checkArithmeticOnObjCPointer(Sema &S, 4532 SourceLocation opLoc, 4533 Expr *op) { 4534 assert(op->getType()->isObjCObjectPointerType()); 4535 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4536 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4537 return false; 4538 4539 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4540 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4541 << op->getSourceRange(); 4542 return true; 4543 } 4544 4545 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4546 auto *BaseNoParens = Base->IgnoreParens(); 4547 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4548 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4549 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4550 } 4551 4552 ExprResult 4553 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4554 Expr *idx, SourceLocation rbLoc) { 4555 if (base && !base->getType().isNull() && 4556 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4557 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4558 /*Length=*/nullptr, rbLoc); 4559 4560 // Since this might be a postfix expression, get rid of ParenListExprs. 4561 if (isa<ParenListExpr>(base)) { 4562 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4563 if (result.isInvalid()) return ExprError(); 4564 base = result.get(); 4565 } 4566 4567 // Check if base and idx form a MatrixSubscriptExpr. 4568 // 4569 // Helper to check for comma expressions, which are not allowed as indices for 4570 // matrix subscript expressions. 4571 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4572 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4573 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4574 << SourceRange(base->getBeginLoc(), rbLoc); 4575 return true; 4576 } 4577 return false; 4578 }; 4579 // The matrix subscript operator ([][])is considered a single operator. 4580 // Separating the index expressions by parenthesis is not allowed. 4581 if (base->getType()->isSpecificPlaceholderType( 4582 BuiltinType::IncompleteMatrixIdx) && 4583 !isa<MatrixSubscriptExpr>(base)) { 4584 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4585 << SourceRange(base->getBeginLoc(), rbLoc); 4586 return ExprError(); 4587 } 4588 // If the base is either a MatrixSubscriptExpr or a matrix type, try to create 4589 // a new MatrixSubscriptExpr. 4590 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4591 if (matSubscriptE) { 4592 if (CheckAndReportCommaError(idx)) 4593 return ExprError(); 4594 4595 assert(matSubscriptE->isIncomplete() && 4596 "base has to be an incomplete matrix subscript"); 4597 return CreateBuiltinMatrixSubscriptExpr( 4598 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4599 } 4600 Expr *matrixBase = base; 4601 bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4602 if (!IsMSPropertySubscript) { 4603 ExprResult result = CheckPlaceholderExpr(base); 4604 if (!result.isInvalid()) 4605 matrixBase = result.get(); 4606 } 4607 if (matrixBase->getType()->isMatrixType()) { 4608 if (CheckAndReportCommaError(idx)) 4609 return ExprError(); 4610 4611 return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc); 4612 } 4613 4614 // A comma-expression as the index is deprecated in C++2a onwards. 4615 if (getLangOpts().CPlusPlus20 && 4616 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4617 (isa<CXXOperatorCallExpr>(idx) && 4618 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4619 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4620 << SourceRange(base->getBeginLoc(), rbLoc); 4621 } 4622 4623 // Handle any non-overload placeholder types in the base and index 4624 // expressions. We can't handle overloads here because the other 4625 // operand might be an overloadable type, in which case the overload 4626 // resolution for the operator overload should get the first crack 4627 // at the overload. 4628 if (base->getType()->isNonOverloadPlaceholderType()) { 4629 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4630 if (!IsMSPropertySubscript) { 4631 ExprResult result = CheckPlaceholderExpr(base); 4632 if (result.isInvalid()) 4633 return ExprError(); 4634 base = result.get(); 4635 } 4636 } 4637 if (idx->getType()->isNonOverloadPlaceholderType()) { 4638 ExprResult result = CheckPlaceholderExpr(idx); 4639 if (result.isInvalid()) return ExprError(); 4640 idx = result.get(); 4641 } 4642 4643 // Build an unanalyzed expression if either operand is type-dependent. 4644 if (getLangOpts().CPlusPlus && 4645 (base->isTypeDependent() || idx->isTypeDependent())) { 4646 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4647 VK_LValue, OK_Ordinary, rbLoc); 4648 } 4649 4650 // MSDN, property (C++) 4651 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4652 // This attribute can also be used in the declaration of an empty array in a 4653 // class or structure definition. For example: 4654 // __declspec(property(get=GetX, put=PutX)) int x[]; 4655 // The above statement indicates that x[] can be used with one or more array 4656 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4657 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4658 if (IsMSPropertySubscript) { 4659 // Build MS property subscript expression if base is MS property reference 4660 // or MS property subscript. 4661 return new (Context) MSPropertySubscriptExpr( 4662 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4663 } 4664 4665 // Use C++ overloaded-operator rules if either operand has record 4666 // type. The spec says to do this if either type is *overloadable*, 4667 // but enum types can't declare subscript operators or conversion 4668 // operators, so there's nothing interesting for overload resolution 4669 // to do if there aren't any record types involved. 4670 // 4671 // ObjC pointers have their own subscripting logic that is not tied 4672 // to overload resolution and so should not take this path. 4673 if (getLangOpts().CPlusPlus && 4674 (base->getType()->isRecordType() || 4675 (!base->getType()->isObjCObjectPointerType() && 4676 idx->getType()->isRecordType()))) { 4677 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4678 } 4679 4680 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4681 4682 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4683 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4684 4685 return Res; 4686 } 4687 4688 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4689 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4690 InitializationKind Kind = 4691 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4692 InitializationSequence InitSeq(*this, Entity, Kind, E); 4693 return InitSeq.Perform(*this, Entity, Kind, E); 4694 } 4695 4696 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4697 Expr *ColumnIdx, 4698 SourceLocation RBLoc) { 4699 ExprResult BaseR = CheckPlaceholderExpr(Base); 4700 if (BaseR.isInvalid()) 4701 return BaseR; 4702 Base = BaseR.get(); 4703 4704 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4705 if (RowR.isInvalid()) 4706 return RowR; 4707 RowIdx = RowR.get(); 4708 4709 if (!ColumnIdx) 4710 return new (Context) MatrixSubscriptExpr( 4711 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4712 4713 // Build an unanalyzed expression if any of the operands is type-dependent. 4714 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4715 ColumnIdx->isTypeDependent()) 4716 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4717 Context.DependentTy, RBLoc); 4718 4719 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4720 if (ColumnR.isInvalid()) 4721 return ColumnR; 4722 ColumnIdx = ColumnR.get(); 4723 4724 // Check that IndexExpr is an integer expression. If it is a constant 4725 // expression, check that it is less than Dim (= the number of elements in the 4726 // corresponding dimension). 4727 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4728 bool IsColumnIdx) -> Expr * { 4729 if (!IndexExpr->getType()->isIntegerType() && 4730 !IndexExpr->isTypeDependent()) { 4731 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4732 << IsColumnIdx; 4733 return nullptr; 4734 } 4735 4736 llvm::APSInt Idx; 4737 if (IndexExpr->isIntegerConstantExpr(Idx, Context) && 4738 (Idx < 0 || Idx >= Dim)) { 4739 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4740 << IsColumnIdx << Dim; 4741 return nullptr; 4742 } 4743 4744 ExprResult ConvExpr = 4745 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4746 assert(!ConvExpr.isInvalid() && 4747 "should be able to convert any integer type to size type"); 4748 return ConvExpr.get(); 4749 }; 4750 4751 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4752 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4753 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4754 if (!RowIdx || !ColumnIdx) 4755 return ExprError(); 4756 4757 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4758 MTy->getElementType(), RBLoc); 4759 } 4760 4761 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4762 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4763 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4764 4765 // For expressions like `&(*s).b`, the base is recorded and what should be 4766 // checked. 4767 const MemberExpr *Member = nullptr; 4768 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4769 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4770 4771 LastRecord.PossibleDerefs.erase(StrippedExpr); 4772 } 4773 4774 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4775 QualType ResultTy = E->getType(); 4776 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4777 4778 // Bail if the element is an array since it is not memory access. 4779 if (isa<ArrayType>(ResultTy)) 4780 return; 4781 4782 if (ResultTy->hasAttr(attr::NoDeref)) { 4783 LastRecord.PossibleDerefs.insert(E); 4784 return; 4785 } 4786 4787 // Check if the base type is a pointer to a member access of a struct 4788 // marked with noderef. 4789 const Expr *Base = E->getBase(); 4790 QualType BaseTy = Base->getType(); 4791 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4792 // Not a pointer access 4793 return; 4794 4795 const MemberExpr *Member = nullptr; 4796 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4797 Member->isArrow()) 4798 Base = Member->getBase(); 4799 4800 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4801 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4802 LastRecord.PossibleDerefs.insert(E); 4803 } 4804 } 4805 4806 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4807 Expr *LowerBound, 4808 SourceLocation ColonLoc, Expr *Length, 4809 SourceLocation RBLoc) { 4810 if (Base->getType()->isPlaceholderType() && 4811 !Base->getType()->isSpecificPlaceholderType( 4812 BuiltinType::OMPArraySection)) { 4813 ExprResult Result = CheckPlaceholderExpr(Base); 4814 if (Result.isInvalid()) 4815 return ExprError(); 4816 Base = Result.get(); 4817 } 4818 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4819 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4820 if (Result.isInvalid()) 4821 return ExprError(); 4822 Result = DefaultLvalueConversion(Result.get()); 4823 if (Result.isInvalid()) 4824 return ExprError(); 4825 LowerBound = Result.get(); 4826 } 4827 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4828 ExprResult Result = CheckPlaceholderExpr(Length); 4829 if (Result.isInvalid()) 4830 return ExprError(); 4831 Result = DefaultLvalueConversion(Result.get()); 4832 if (Result.isInvalid()) 4833 return ExprError(); 4834 Length = Result.get(); 4835 } 4836 4837 // Build an unanalyzed expression if either operand is type-dependent. 4838 if (Base->isTypeDependent() || 4839 (LowerBound && 4840 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4841 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4842 return new (Context) 4843 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4844 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4845 } 4846 4847 // Perform default conversions. 4848 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4849 QualType ResultTy; 4850 if (OriginalTy->isAnyPointerType()) { 4851 ResultTy = OriginalTy->getPointeeType(); 4852 } else if (OriginalTy->isArrayType()) { 4853 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4854 } else { 4855 return ExprError( 4856 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4857 << Base->getSourceRange()); 4858 } 4859 // C99 6.5.2.1p1 4860 if (LowerBound) { 4861 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4862 LowerBound); 4863 if (Res.isInvalid()) 4864 return ExprError(Diag(LowerBound->getExprLoc(), 4865 diag::err_omp_typecheck_section_not_integer) 4866 << 0 << LowerBound->getSourceRange()); 4867 LowerBound = Res.get(); 4868 4869 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4870 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4871 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4872 << 0 << LowerBound->getSourceRange(); 4873 } 4874 if (Length) { 4875 auto Res = 4876 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4877 if (Res.isInvalid()) 4878 return ExprError(Diag(Length->getExprLoc(), 4879 diag::err_omp_typecheck_section_not_integer) 4880 << 1 << Length->getSourceRange()); 4881 Length = Res.get(); 4882 4883 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4884 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4885 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4886 << 1 << Length->getSourceRange(); 4887 } 4888 4889 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4890 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4891 // type. Note that functions are not objects, and that (in C99 parlance) 4892 // incomplete types are not object types. 4893 if (ResultTy->isFunctionType()) { 4894 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4895 << ResultTy << Base->getSourceRange(); 4896 return ExprError(); 4897 } 4898 4899 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4900 diag::err_omp_section_incomplete_type, Base)) 4901 return ExprError(); 4902 4903 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4904 Expr::EvalResult Result; 4905 if (LowerBound->EvaluateAsInt(Result, Context)) { 4906 // OpenMP 4.5, [2.4 Array Sections] 4907 // The array section must be a subset of the original array. 4908 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4909 if (LowerBoundValue.isNegative()) { 4910 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4911 << LowerBound->getSourceRange(); 4912 return ExprError(); 4913 } 4914 } 4915 } 4916 4917 if (Length) { 4918 Expr::EvalResult Result; 4919 if (Length->EvaluateAsInt(Result, Context)) { 4920 // OpenMP 4.5, [2.4 Array Sections] 4921 // The length must evaluate to non-negative integers. 4922 llvm::APSInt LengthValue = Result.Val.getInt(); 4923 if (LengthValue.isNegative()) { 4924 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4925 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4926 << Length->getSourceRange(); 4927 return ExprError(); 4928 } 4929 } 4930 } else if (ColonLoc.isValid() && 4931 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4932 !OriginalTy->isVariableArrayType()))) { 4933 // OpenMP 4.5, [2.4 Array Sections] 4934 // When the size of the array dimension is not known, the length must be 4935 // specified explicitly. 4936 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4937 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4938 return ExprError(); 4939 } 4940 4941 if (!Base->getType()->isSpecificPlaceholderType( 4942 BuiltinType::OMPArraySection)) { 4943 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4944 if (Result.isInvalid()) 4945 return ExprError(); 4946 Base = Result.get(); 4947 } 4948 return new (Context) 4949 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4950 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4951 } 4952 4953 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4954 SourceLocation RParenLoc, 4955 ArrayRef<Expr *> Dims, 4956 ArrayRef<SourceRange> Brackets) { 4957 if (Base->getType()->isPlaceholderType()) { 4958 ExprResult Result = CheckPlaceholderExpr(Base); 4959 if (Result.isInvalid()) 4960 return ExprError(); 4961 Result = DefaultLvalueConversion(Result.get()); 4962 if (Result.isInvalid()) 4963 return ExprError(); 4964 Base = Result.get(); 4965 } 4966 QualType BaseTy = Base->getType(); 4967 // Delay analysis of the types/expressions if instantiation/specialization is 4968 // required. 4969 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4970 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4971 LParenLoc, RParenLoc, Dims, Brackets); 4972 if (!BaseTy->isPointerType() || 4973 (!Base->isTypeDependent() && 4974 BaseTy->getPointeeType()->isIncompleteType())) 4975 return ExprError(Diag(Base->getExprLoc(), 4976 diag::err_omp_non_pointer_type_array_shaping_base) 4977 << Base->getSourceRange()); 4978 4979 SmallVector<Expr *, 4> NewDims; 4980 bool ErrorFound = false; 4981 for (Expr *Dim : Dims) { 4982 if (Dim->getType()->isPlaceholderType()) { 4983 ExprResult Result = CheckPlaceholderExpr(Dim); 4984 if (Result.isInvalid()) { 4985 ErrorFound = true; 4986 continue; 4987 } 4988 Result = DefaultLvalueConversion(Result.get()); 4989 if (Result.isInvalid()) { 4990 ErrorFound = true; 4991 continue; 4992 } 4993 Dim = Result.get(); 4994 } 4995 if (!Dim->isTypeDependent()) { 4996 ExprResult Result = 4997 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 4998 if (Result.isInvalid()) { 4999 ErrorFound = true; 5000 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5001 << Dim->getSourceRange(); 5002 continue; 5003 } 5004 Dim = Result.get(); 5005 Expr::EvalResult EvResult; 5006 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5007 // OpenMP 5.0, [2.1.4 Array Shaping] 5008 // Each si is an integral type expression that must evaluate to a 5009 // positive integer. 5010 llvm::APSInt Value = EvResult.Val.getInt(); 5011 if (!Value.isStrictlyPositive()) { 5012 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5013 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5014 << Dim->getSourceRange(); 5015 ErrorFound = true; 5016 continue; 5017 } 5018 } 5019 } 5020 NewDims.push_back(Dim); 5021 } 5022 if (ErrorFound) 5023 return ExprError(); 5024 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5025 LParenLoc, RParenLoc, NewDims, Brackets); 5026 } 5027 5028 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5029 SourceLocation LLoc, SourceLocation RLoc, 5030 ArrayRef<OMPIteratorData> Data) { 5031 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5032 bool IsCorrect = true; 5033 for (const OMPIteratorData &D : Data) { 5034 TypeSourceInfo *TInfo = nullptr; 5035 SourceLocation StartLoc; 5036 QualType DeclTy; 5037 if (!D.Type.getAsOpaquePtr()) { 5038 // OpenMP 5.0, 2.1.6 Iterators 5039 // In an iterator-specifier, if the iterator-type is not specified then 5040 // the type of that iterator is of int type. 5041 DeclTy = Context.IntTy; 5042 StartLoc = D.DeclIdentLoc; 5043 } else { 5044 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5045 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5046 } 5047 5048 bool IsDeclTyDependent = DeclTy->isDependentType() || 5049 DeclTy->containsUnexpandedParameterPack() || 5050 DeclTy->isInstantiationDependentType(); 5051 if (!IsDeclTyDependent) { 5052 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5053 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5054 // The iterator-type must be an integral or pointer type. 5055 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5056 << DeclTy; 5057 IsCorrect = false; 5058 continue; 5059 } 5060 if (DeclTy.isConstant(Context)) { 5061 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5062 // The iterator-type must not be const qualified. 5063 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5064 << DeclTy; 5065 IsCorrect = false; 5066 continue; 5067 } 5068 } 5069 5070 // Iterator declaration. 5071 assert(D.DeclIdent && "Identifier expected."); 5072 // Always try to create iterator declarator to avoid extra error messages 5073 // about unknown declarations use. 5074 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5075 D.DeclIdent, DeclTy, TInfo, SC_None); 5076 VD->setImplicit(); 5077 if (S) { 5078 // Check for conflicting previous declaration. 5079 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5080 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5081 ForVisibleRedeclaration); 5082 Previous.suppressDiagnostics(); 5083 LookupName(Previous, S); 5084 5085 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5086 /*AllowInlineNamespace=*/false); 5087 if (!Previous.empty()) { 5088 NamedDecl *Old = Previous.getRepresentativeDecl(); 5089 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5090 Diag(Old->getLocation(), diag::note_previous_definition); 5091 } else { 5092 PushOnScopeChains(VD, S); 5093 } 5094 } else { 5095 CurContext->addDecl(VD); 5096 } 5097 Expr *Begin = D.Range.Begin; 5098 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5099 ExprResult BeginRes = 5100 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5101 Begin = BeginRes.get(); 5102 } 5103 Expr *End = D.Range.End; 5104 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5105 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5106 End = EndRes.get(); 5107 } 5108 Expr *Step = D.Range.Step; 5109 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5110 if (!Step->getType()->isIntegralType(Context)) { 5111 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5112 << Step << Step->getSourceRange(); 5113 IsCorrect = false; 5114 continue; 5115 } 5116 llvm::APSInt Result; 5117 bool IsConstant = Step->isIntegerConstantExpr(Result, Context); 5118 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5119 // If the step expression of a range-specification equals zero, the 5120 // behavior is unspecified. 5121 if (IsConstant && Result.isNullValue()) { 5122 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5123 << Step << Step->getSourceRange(); 5124 IsCorrect = false; 5125 continue; 5126 } 5127 } 5128 if (!Begin || !End || !IsCorrect) { 5129 IsCorrect = false; 5130 continue; 5131 } 5132 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5133 IDElem.IteratorDecl = VD; 5134 IDElem.AssignmentLoc = D.AssignLoc; 5135 IDElem.Range.Begin = Begin; 5136 IDElem.Range.End = End; 5137 IDElem.Range.Step = Step; 5138 IDElem.ColonLoc = D.ColonLoc; 5139 IDElem.SecondColonLoc = D.SecColonLoc; 5140 } 5141 if (!IsCorrect) { 5142 // Invalidate all created iterator declarations if error is found. 5143 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5144 if (Decl *ID = D.IteratorDecl) 5145 ID->setInvalidDecl(); 5146 } 5147 return ExprError(); 5148 } 5149 SmallVector<OMPIteratorHelperData, 4> Helpers; 5150 if (!CurContext->isDependentContext()) { 5151 // Build number of ityeration for each iteration range. 5152 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5153 // ((Begini-Stepi-1-Endi) / -Stepi); 5154 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5155 // (Endi - Begini) 5156 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5157 D.Range.Begin); 5158 if(!Res.isUsable()) { 5159 IsCorrect = false; 5160 continue; 5161 } 5162 ExprResult St, St1; 5163 if (D.Range.Step) { 5164 St = D.Range.Step; 5165 // (Endi - Begini) + Stepi 5166 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5167 if (!Res.isUsable()) { 5168 IsCorrect = false; 5169 continue; 5170 } 5171 // (Endi - Begini) + Stepi - 1 5172 Res = 5173 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5174 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5175 if (!Res.isUsable()) { 5176 IsCorrect = false; 5177 continue; 5178 } 5179 // ((Endi - Begini) + Stepi - 1) / Stepi 5180 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5181 if (!Res.isUsable()) { 5182 IsCorrect = false; 5183 continue; 5184 } 5185 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5186 // (Begini - Endi) 5187 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5188 D.Range.Begin, D.Range.End); 5189 if (!Res1.isUsable()) { 5190 IsCorrect = false; 5191 continue; 5192 } 5193 // (Begini - Endi) - Stepi 5194 Res1 = 5195 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5196 if (!Res1.isUsable()) { 5197 IsCorrect = false; 5198 continue; 5199 } 5200 // (Begini - Endi) - Stepi - 1 5201 Res1 = 5202 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5203 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5204 if (!Res1.isUsable()) { 5205 IsCorrect = false; 5206 continue; 5207 } 5208 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5209 Res1 = 5210 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5211 if (!Res1.isUsable()) { 5212 IsCorrect = false; 5213 continue; 5214 } 5215 // Stepi > 0. 5216 ExprResult CmpRes = 5217 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5218 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5219 if (!CmpRes.isUsable()) { 5220 IsCorrect = false; 5221 continue; 5222 } 5223 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5224 Res.get(), Res1.get()); 5225 if (!Res.isUsable()) { 5226 IsCorrect = false; 5227 continue; 5228 } 5229 } 5230 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5231 if (!Res.isUsable()) { 5232 IsCorrect = false; 5233 continue; 5234 } 5235 5236 // Build counter update. 5237 // Build counter. 5238 auto *CounterVD = 5239 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5240 D.IteratorDecl->getBeginLoc(), nullptr, 5241 Res.get()->getType(), nullptr, SC_None); 5242 CounterVD->setImplicit(); 5243 ExprResult RefRes = 5244 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5245 D.IteratorDecl->getBeginLoc()); 5246 // Build counter update. 5247 // I = Begini + counter * Stepi; 5248 ExprResult UpdateRes; 5249 if (D.Range.Step) { 5250 UpdateRes = CreateBuiltinBinOp( 5251 D.AssignmentLoc, BO_Mul, 5252 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5253 } else { 5254 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5255 } 5256 if (!UpdateRes.isUsable()) { 5257 IsCorrect = false; 5258 continue; 5259 } 5260 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5261 UpdateRes.get()); 5262 if (!UpdateRes.isUsable()) { 5263 IsCorrect = false; 5264 continue; 5265 } 5266 ExprResult VDRes = 5267 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5268 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5269 D.IteratorDecl->getBeginLoc()); 5270 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5271 UpdateRes.get()); 5272 if (!UpdateRes.isUsable()) { 5273 IsCorrect = false; 5274 continue; 5275 } 5276 UpdateRes = 5277 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5278 if (!UpdateRes.isUsable()) { 5279 IsCorrect = false; 5280 continue; 5281 } 5282 ExprResult CounterUpdateRes = 5283 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5284 if (!CounterUpdateRes.isUsable()) { 5285 IsCorrect = false; 5286 continue; 5287 } 5288 CounterUpdateRes = 5289 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5290 if (!CounterUpdateRes.isUsable()) { 5291 IsCorrect = false; 5292 continue; 5293 } 5294 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5295 HD.CounterVD = CounterVD; 5296 HD.Upper = Res.get(); 5297 HD.Update = UpdateRes.get(); 5298 HD.CounterUpdate = CounterUpdateRes.get(); 5299 } 5300 } else { 5301 Helpers.assign(ID.size(), {}); 5302 } 5303 if (!IsCorrect) { 5304 // Invalidate all created iterator declarations if error is found. 5305 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5306 if (Decl *ID = D.IteratorDecl) 5307 ID->setInvalidDecl(); 5308 } 5309 return ExprError(); 5310 } 5311 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5312 LLoc, RLoc, ID, Helpers); 5313 } 5314 5315 ExprResult 5316 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5317 Expr *Idx, SourceLocation RLoc) { 5318 Expr *LHSExp = Base; 5319 Expr *RHSExp = Idx; 5320 5321 ExprValueKind VK = VK_LValue; 5322 ExprObjectKind OK = OK_Ordinary; 5323 5324 // Per C++ core issue 1213, the result is an xvalue if either operand is 5325 // a non-lvalue array, and an lvalue otherwise. 5326 if (getLangOpts().CPlusPlus11) { 5327 for (auto *Op : {LHSExp, RHSExp}) { 5328 Op = Op->IgnoreImplicit(); 5329 if (Op->getType()->isArrayType() && !Op->isLValue()) 5330 VK = VK_XValue; 5331 } 5332 } 5333 5334 // Perform default conversions. 5335 if (!LHSExp->getType()->getAs<VectorType>()) { 5336 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5337 if (Result.isInvalid()) 5338 return ExprError(); 5339 LHSExp = Result.get(); 5340 } 5341 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5342 if (Result.isInvalid()) 5343 return ExprError(); 5344 RHSExp = Result.get(); 5345 5346 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5347 5348 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5349 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5350 // in the subscript position. As a result, we need to derive the array base 5351 // and index from the expression types. 5352 Expr *BaseExpr, *IndexExpr; 5353 QualType ResultType; 5354 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5355 BaseExpr = LHSExp; 5356 IndexExpr = RHSExp; 5357 ResultType = Context.DependentTy; 5358 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5359 BaseExpr = LHSExp; 5360 IndexExpr = RHSExp; 5361 ResultType = PTy->getPointeeType(); 5362 } else if (const ObjCObjectPointerType *PTy = 5363 LHSTy->getAs<ObjCObjectPointerType>()) { 5364 BaseExpr = LHSExp; 5365 IndexExpr = RHSExp; 5366 5367 // Use custom logic if this should be the pseudo-object subscript 5368 // expression. 5369 if (!LangOpts.isSubscriptPointerArithmetic()) 5370 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5371 nullptr); 5372 5373 ResultType = PTy->getPointeeType(); 5374 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5375 // Handle the uncommon case of "123[Ptr]". 5376 BaseExpr = RHSExp; 5377 IndexExpr = LHSExp; 5378 ResultType = PTy->getPointeeType(); 5379 } else if (const ObjCObjectPointerType *PTy = 5380 RHSTy->getAs<ObjCObjectPointerType>()) { 5381 // Handle the uncommon case of "123[Ptr]". 5382 BaseExpr = RHSExp; 5383 IndexExpr = LHSExp; 5384 ResultType = PTy->getPointeeType(); 5385 if (!LangOpts.isSubscriptPointerArithmetic()) { 5386 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5387 << ResultType << BaseExpr->getSourceRange(); 5388 return ExprError(); 5389 } 5390 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5391 BaseExpr = LHSExp; // vectors: V[123] 5392 IndexExpr = RHSExp; 5393 // We apply C++ DR1213 to vector subscripting too. 5394 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5395 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5396 if (Materialized.isInvalid()) 5397 return ExprError(); 5398 LHSExp = Materialized.get(); 5399 } 5400 VK = LHSExp->getValueKind(); 5401 if (VK != VK_RValue) 5402 OK = OK_VectorComponent; 5403 5404 ResultType = VTy->getElementType(); 5405 QualType BaseType = BaseExpr->getType(); 5406 Qualifiers BaseQuals = BaseType.getQualifiers(); 5407 Qualifiers MemberQuals = ResultType.getQualifiers(); 5408 Qualifiers Combined = BaseQuals + MemberQuals; 5409 if (Combined != MemberQuals) 5410 ResultType = Context.getQualifiedType(ResultType, Combined); 5411 } else if (LHSTy->isArrayType()) { 5412 // If we see an array that wasn't promoted by 5413 // DefaultFunctionArrayLvalueConversion, it must be an array that 5414 // wasn't promoted because of the C90 rule that doesn't 5415 // allow promoting non-lvalue arrays. Warn, then 5416 // force the promotion here. 5417 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5418 << LHSExp->getSourceRange(); 5419 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5420 CK_ArrayToPointerDecay).get(); 5421 LHSTy = LHSExp->getType(); 5422 5423 BaseExpr = LHSExp; 5424 IndexExpr = RHSExp; 5425 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5426 } else if (RHSTy->isArrayType()) { 5427 // Same as previous, except for 123[f().a] case 5428 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5429 << RHSExp->getSourceRange(); 5430 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5431 CK_ArrayToPointerDecay).get(); 5432 RHSTy = RHSExp->getType(); 5433 5434 BaseExpr = RHSExp; 5435 IndexExpr = LHSExp; 5436 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5437 } else { 5438 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5439 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5440 } 5441 // C99 6.5.2.1p1 5442 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5443 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5444 << IndexExpr->getSourceRange()); 5445 5446 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5447 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5448 && !IndexExpr->isTypeDependent()) 5449 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5450 5451 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5452 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5453 // type. Note that Functions are not objects, and that (in C99 parlance) 5454 // incomplete types are not object types. 5455 if (ResultType->isFunctionType()) { 5456 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5457 << ResultType << BaseExpr->getSourceRange(); 5458 return ExprError(); 5459 } 5460 5461 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5462 // GNU extension: subscripting on pointer to void 5463 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5464 << BaseExpr->getSourceRange(); 5465 5466 // C forbids expressions of unqualified void type from being l-values. 5467 // See IsCForbiddenLValueType. 5468 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5469 } else if (!ResultType->isDependentType() && 5470 RequireCompleteSizedType( 5471 LLoc, ResultType, 5472 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5473 return ExprError(); 5474 5475 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5476 !ResultType.isCForbiddenLValueType()); 5477 5478 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5479 FunctionScopes.size() > 1) { 5480 if (auto *TT = 5481 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5482 for (auto I = FunctionScopes.rbegin(), 5483 E = std::prev(FunctionScopes.rend()); 5484 I != E; ++I) { 5485 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5486 if (CSI == nullptr) 5487 break; 5488 DeclContext *DC = nullptr; 5489 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5490 DC = LSI->CallOperator; 5491 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5492 DC = CRSI->TheCapturedDecl; 5493 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5494 DC = BSI->TheDecl; 5495 if (DC) { 5496 if (DC->containsDecl(TT->getDecl())) 5497 break; 5498 captureVariablyModifiedType( 5499 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5500 } 5501 } 5502 } 5503 } 5504 5505 return new (Context) 5506 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5507 } 5508 5509 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5510 ParmVarDecl *Param) { 5511 if (Param->hasUnparsedDefaultArg()) { 5512 // If we've already cleared out the location for the default argument, 5513 // that means we're parsing it right now. 5514 if (!UnparsedDefaultArgLocs.count(Param)) { 5515 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5516 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5517 Param->setInvalidDecl(); 5518 return true; 5519 } 5520 5521 Diag(CallLoc, 5522 diag::err_use_of_default_argument_to_function_declared_later) << 5523 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5524 Diag(UnparsedDefaultArgLocs[Param], 5525 diag::note_default_argument_declared_here); 5526 return true; 5527 } 5528 5529 if (Param->hasUninstantiatedDefaultArg()) { 5530 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 5531 5532 EnterExpressionEvaluationContext EvalContext( 5533 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5534 5535 // Instantiate the expression. 5536 // 5537 // FIXME: Pass in a correct Pattern argument, otherwise 5538 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 5539 // 5540 // template<typename T> 5541 // struct A { 5542 // static int FooImpl(); 5543 // 5544 // template<typename Tp> 5545 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 5546 // // template argument list [[T], [Tp]], should be [[Tp]]. 5547 // friend A<Tp> Foo(int a); 5548 // }; 5549 // 5550 // template<typename T> 5551 // A<T> Foo(int a = A<T>::FooImpl()); 5552 MultiLevelTemplateArgumentList MutiLevelArgList 5553 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 5554 5555 InstantiatingTemplate Inst(*this, CallLoc, Param, 5556 MutiLevelArgList.getInnermost()); 5557 if (Inst.isInvalid()) 5558 return true; 5559 if (Inst.isAlreadyInstantiating()) { 5560 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5561 Param->setInvalidDecl(); 5562 return true; 5563 } 5564 5565 ExprResult Result; 5566 { 5567 // C++ [dcl.fct.default]p5: 5568 // The names in the [default argument] expression are bound, and 5569 // the semantic constraints are checked, at the point where the 5570 // default argument expression appears. 5571 ContextRAII SavedContext(*this, FD); 5572 LocalInstantiationScope Local(*this); 5573 runWithSufficientStackSpace(CallLoc, [&] { 5574 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 5575 /*DirectInit*/false); 5576 }); 5577 } 5578 if (Result.isInvalid()) 5579 return true; 5580 5581 // Check the expression as an initializer for the parameter. 5582 InitializedEntity Entity 5583 = InitializedEntity::InitializeParameter(Context, Param); 5584 InitializationKind Kind = InitializationKind::CreateCopy( 5585 Param->getLocation(), 5586 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 5587 Expr *ResultE = Result.getAs<Expr>(); 5588 5589 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 5590 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 5591 if (Result.isInvalid()) 5592 return true; 5593 5594 Result = 5595 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5596 /*DiscardedValue*/ false); 5597 if (Result.isInvalid()) 5598 return true; 5599 5600 // Remember the instantiated default argument. 5601 Param->setDefaultArg(Result.getAs<Expr>()); 5602 if (ASTMutationListener *L = getASTMutationListener()) { 5603 L->DefaultArgumentInstantiated(Param); 5604 } 5605 } 5606 5607 assert(Param->hasInit() && "default argument but no initializer?"); 5608 5609 // If the default expression creates temporaries, we need to 5610 // push them to the current stack of expression temporaries so they'll 5611 // be properly destroyed. 5612 // FIXME: We should really be rebuilding the default argument with new 5613 // bound temporaries; see the comment in PR5810. 5614 // We don't need to do that with block decls, though, because 5615 // blocks in default argument expression can never capture anything. 5616 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5617 // Set the "needs cleanups" bit regardless of whether there are 5618 // any explicit objects. 5619 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5620 5621 // Append all the objects to the cleanup list. Right now, this 5622 // should always be a no-op, because blocks in default argument 5623 // expressions should never be able to capture anything. 5624 assert(!Init->getNumObjects() && 5625 "default argument expression has capturing blocks?"); 5626 } 5627 5628 // We already type-checked the argument, so we know it works. 5629 // Just mark all of the declarations in this potentially-evaluated expression 5630 // as being "referenced". 5631 EnterExpressionEvaluationContext EvalContext( 5632 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5633 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5634 /*SkipLocalVariables=*/true); 5635 return false; 5636 } 5637 5638 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5639 FunctionDecl *FD, ParmVarDecl *Param) { 5640 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5641 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5642 return ExprError(); 5643 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5644 } 5645 5646 Sema::VariadicCallType 5647 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5648 Expr *Fn) { 5649 if (Proto && Proto->isVariadic()) { 5650 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5651 return VariadicConstructor; 5652 else if (Fn && Fn->getType()->isBlockPointerType()) 5653 return VariadicBlock; 5654 else if (FDecl) { 5655 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5656 if (Method->isInstance()) 5657 return VariadicMethod; 5658 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5659 return VariadicMethod; 5660 return VariadicFunction; 5661 } 5662 return VariadicDoesNotApply; 5663 } 5664 5665 namespace { 5666 class FunctionCallCCC final : public FunctionCallFilterCCC { 5667 public: 5668 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5669 unsigned NumArgs, MemberExpr *ME) 5670 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5671 FunctionName(FuncName) {} 5672 5673 bool ValidateCandidate(const TypoCorrection &candidate) override { 5674 if (!candidate.getCorrectionSpecifier() || 5675 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5676 return false; 5677 } 5678 5679 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5680 } 5681 5682 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5683 return std::make_unique<FunctionCallCCC>(*this); 5684 } 5685 5686 private: 5687 const IdentifierInfo *const FunctionName; 5688 }; 5689 } 5690 5691 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5692 FunctionDecl *FDecl, 5693 ArrayRef<Expr *> Args) { 5694 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5695 DeclarationName FuncName = FDecl->getDeclName(); 5696 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5697 5698 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5699 if (TypoCorrection Corrected = S.CorrectTypo( 5700 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5701 S.getScopeForContext(S.CurContext), nullptr, CCC, 5702 Sema::CTK_ErrorRecovery)) { 5703 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5704 if (Corrected.isOverloaded()) { 5705 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5706 OverloadCandidateSet::iterator Best; 5707 for (NamedDecl *CD : Corrected) { 5708 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5709 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5710 OCS); 5711 } 5712 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5713 case OR_Success: 5714 ND = Best->FoundDecl; 5715 Corrected.setCorrectionDecl(ND); 5716 break; 5717 default: 5718 break; 5719 } 5720 } 5721 ND = ND->getUnderlyingDecl(); 5722 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5723 return Corrected; 5724 } 5725 } 5726 return TypoCorrection(); 5727 } 5728 5729 /// ConvertArgumentsForCall - Converts the arguments specified in 5730 /// Args/NumArgs to the parameter types of the function FDecl with 5731 /// function prototype Proto. Call is the call expression itself, and 5732 /// Fn is the function expression. For a C++ member function, this 5733 /// routine does not attempt to convert the object argument. Returns 5734 /// true if the call is ill-formed. 5735 bool 5736 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5737 FunctionDecl *FDecl, 5738 const FunctionProtoType *Proto, 5739 ArrayRef<Expr *> Args, 5740 SourceLocation RParenLoc, 5741 bool IsExecConfig) { 5742 // Bail out early if calling a builtin with custom typechecking. 5743 if (FDecl) 5744 if (unsigned ID = FDecl->getBuiltinID()) 5745 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5746 return false; 5747 5748 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5749 // assignment, to the types of the corresponding parameter, ... 5750 unsigned NumParams = Proto->getNumParams(); 5751 bool Invalid = false; 5752 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5753 unsigned FnKind = Fn->getType()->isBlockPointerType() 5754 ? 1 /* block */ 5755 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5756 : 0 /* function */); 5757 5758 // If too few arguments are available (and we don't have default 5759 // arguments for the remaining parameters), don't make the call. 5760 if (Args.size() < NumParams) { 5761 if (Args.size() < MinArgs) { 5762 TypoCorrection TC; 5763 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5764 unsigned diag_id = 5765 MinArgs == NumParams && !Proto->isVariadic() 5766 ? diag::err_typecheck_call_too_few_args_suggest 5767 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5768 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5769 << static_cast<unsigned>(Args.size()) 5770 << TC.getCorrectionRange()); 5771 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5772 Diag(RParenLoc, 5773 MinArgs == NumParams && !Proto->isVariadic() 5774 ? diag::err_typecheck_call_too_few_args_one 5775 : diag::err_typecheck_call_too_few_args_at_least_one) 5776 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5777 else 5778 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5779 ? diag::err_typecheck_call_too_few_args 5780 : diag::err_typecheck_call_too_few_args_at_least) 5781 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5782 << Fn->getSourceRange(); 5783 5784 // Emit the location of the prototype. 5785 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5786 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5787 5788 return true; 5789 } 5790 // We reserve space for the default arguments when we create 5791 // the call expression, before calling ConvertArgumentsForCall. 5792 assert((Call->getNumArgs() == NumParams) && 5793 "We should have reserved space for the default arguments before!"); 5794 } 5795 5796 // If too many are passed and not variadic, error on the extras and drop 5797 // them. 5798 if (Args.size() > NumParams) { 5799 if (!Proto->isVariadic()) { 5800 TypoCorrection TC; 5801 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5802 unsigned diag_id = 5803 MinArgs == NumParams && !Proto->isVariadic() 5804 ? diag::err_typecheck_call_too_many_args_suggest 5805 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5806 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5807 << static_cast<unsigned>(Args.size()) 5808 << TC.getCorrectionRange()); 5809 } else if (NumParams == 1 && FDecl && 5810 FDecl->getParamDecl(0)->getDeclName()) 5811 Diag(Args[NumParams]->getBeginLoc(), 5812 MinArgs == NumParams 5813 ? diag::err_typecheck_call_too_many_args_one 5814 : diag::err_typecheck_call_too_many_args_at_most_one) 5815 << FnKind << FDecl->getParamDecl(0) 5816 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5817 << SourceRange(Args[NumParams]->getBeginLoc(), 5818 Args.back()->getEndLoc()); 5819 else 5820 Diag(Args[NumParams]->getBeginLoc(), 5821 MinArgs == NumParams 5822 ? diag::err_typecheck_call_too_many_args 5823 : diag::err_typecheck_call_too_many_args_at_most) 5824 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5825 << Fn->getSourceRange() 5826 << SourceRange(Args[NumParams]->getBeginLoc(), 5827 Args.back()->getEndLoc()); 5828 5829 // Emit the location of the prototype. 5830 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5831 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5832 5833 // This deletes the extra arguments. 5834 Call->shrinkNumArgs(NumParams); 5835 return true; 5836 } 5837 } 5838 SmallVector<Expr *, 8> AllArgs; 5839 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5840 5841 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5842 AllArgs, CallType); 5843 if (Invalid) 5844 return true; 5845 unsigned TotalNumArgs = AllArgs.size(); 5846 for (unsigned i = 0; i < TotalNumArgs; ++i) 5847 Call->setArg(i, AllArgs[i]); 5848 5849 return false; 5850 } 5851 5852 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5853 const FunctionProtoType *Proto, 5854 unsigned FirstParam, ArrayRef<Expr *> Args, 5855 SmallVectorImpl<Expr *> &AllArgs, 5856 VariadicCallType CallType, bool AllowExplicit, 5857 bool IsListInitialization) { 5858 unsigned NumParams = Proto->getNumParams(); 5859 bool Invalid = false; 5860 size_t ArgIx = 0; 5861 // Continue to check argument types (even if we have too few/many args). 5862 for (unsigned i = FirstParam; i < NumParams; i++) { 5863 QualType ProtoArgType = Proto->getParamType(i); 5864 5865 Expr *Arg; 5866 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5867 if (ArgIx < Args.size()) { 5868 Arg = Args[ArgIx++]; 5869 5870 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5871 diag::err_call_incomplete_argument, Arg)) 5872 return true; 5873 5874 // Strip the unbridged-cast placeholder expression off, if applicable. 5875 bool CFAudited = false; 5876 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5877 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5878 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5879 Arg = stripARCUnbridgedCast(Arg); 5880 else if (getLangOpts().ObjCAutoRefCount && 5881 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5882 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5883 CFAudited = true; 5884 5885 if (Proto->getExtParameterInfo(i).isNoEscape()) 5886 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5887 BE->getBlockDecl()->setDoesNotEscape(); 5888 5889 InitializedEntity Entity = 5890 Param ? InitializedEntity::InitializeParameter(Context, Param, 5891 ProtoArgType) 5892 : InitializedEntity::InitializeParameter( 5893 Context, ProtoArgType, Proto->isParamConsumed(i)); 5894 5895 // Remember that parameter belongs to a CF audited API. 5896 if (CFAudited) 5897 Entity.setParameterCFAudited(); 5898 5899 ExprResult ArgE = PerformCopyInitialization( 5900 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5901 if (ArgE.isInvalid()) 5902 return true; 5903 5904 Arg = ArgE.getAs<Expr>(); 5905 } else { 5906 assert(Param && "can't use default arguments without a known callee"); 5907 5908 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5909 if (ArgExpr.isInvalid()) 5910 return true; 5911 5912 Arg = ArgExpr.getAs<Expr>(); 5913 } 5914 5915 // Check for array bounds violations for each argument to the call. This 5916 // check only triggers warnings when the argument isn't a more complex Expr 5917 // with its own checking, such as a BinaryOperator. 5918 CheckArrayAccess(Arg); 5919 5920 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5921 CheckStaticArrayArgument(CallLoc, Param, Arg); 5922 5923 AllArgs.push_back(Arg); 5924 } 5925 5926 // If this is a variadic call, handle args passed through "...". 5927 if (CallType != VariadicDoesNotApply) { 5928 // Assume that extern "C" functions with variadic arguments that 5929 // return __unknown_anytype aren't *really* variadic. 5930 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5931 FDecl->isExternC()) { 5932 for (Expr *A : Args.slice(ArgIx)) { 5933 QualType paramType; // ignored 5934 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5935 Invalid |= arg.isInvalid(); 5936 AllArgs.push_back(arg.get()); 5937 } 5938 5939 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5940 } else { 5941 for (Expr *A : Args.slice(ArgIx)) { 5942 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5943 Invalid |= Arg.isInvalid(); 5944 // Copy blocks to the heap. 5945 if (A->getType()->isBlockPointerType()) 5946 maybeExtendBlockObject(Arg); 5947 AllArgs.push_back(Arg.get()); 5948 } 5949 } 5950 5951 // Check for array bounds violations. 5952 for (Expr *A : Args.slice(ArgIx)) 5953 CheckArrayAccess(A); 5954 } 5955 return Invalid; 5956 } 5957 5958 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5959 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5960 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5961 TL = DTL.getOriginalLoc(); 5962 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5963 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5964 << ATL.getLocalSourceRange(); 5965 } 5966 5967 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5968 /// array parameter, check that it is non-null, and that if it is formed by 5969 /// array-to-pointer decay, the underlying array is sufficiently large. 5970 /// 5971 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5972 /// array type derivation, then for each call to the function, the value of the 5973 /// corresponding actual argument shall provide access to the first element of 5974 /// an array with at least as many elements as specified by the size expression. 5975 void 5976 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5977 ParmVarDecl *Param, 5978 const Expr *ArgExpr) { 5979 // Static array parameters are not supported in C++. 5980 if (!Param || getLangOpts().CPlusPlus) 5981 return; 5982 5983 QualType OrigTy = Param->getOriginalType(); 5984 5985 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5986 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5987 return; 5988 5989 if (ArgExpr->isNullPointerConstant(Context, 5990 Expr::NPC_NeverValueDependent)) { 5991 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5992 DiagnoseCalleeStaticArrayParam(*this, Param); 5993 return; 5994 } 5995 5996 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5997 if (!CAT) 5998 return; 5999 6000 const ConstantArrayType *ArgCAT = 6001 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6002 if (!ArgCAT) 6003 return; 6004 6005 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6006 ArgCAT->getElementType())) { 6007 if (ArgCAT->getSize().ult(CAT->getSize())) { 6008 Diag(CallLoc, diag::warn_static_array_too_small) 6009 << ArgExpr->getSourceRange() 6010 << (unsigned)ArgCAT->getSize().getZExtValue() 6011 << (unsigned)CAT->getSize().getZExtValue() << 0; 6012 DiagnoseCalleeStaticArrayParam(*this, Param); 6013 } 6014 return; 6015 } 6016 6017 Optional<CharUnits> ArgSize = 6018 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6019 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6020 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6021 Diag(CallLoc, diag::warn_static_array_too_small) 6022 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6023 << (unsigned)ParmSize->getQuantity() << 1; 6024 DiagnoseCalleeStaticArrayParam(*this, Param); 6025 } 6026 } 6027 6028 /// Given a function expression of unknown-any type, try to rebuild it 6029 /// to have a function type. 6030 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6031 6032 /// Is the given type a placeholder that we need to lower out 6033 /// immediately during argument processing? 6034 static bool isPlaceholderToRemoveAsArg(QualType type) { 6035 // Placeholders are never sugared. 6036 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6037 if (!placeholder) return false; 6038 6039 switch (placeholder->getKind()) { 6040 // Ignore all the non-placeholder types. 6041 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6042 case BuiltinType::Id: 6043 #include "clang/Basic/OpenCLImageTypes.def" 6044 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6045 case BuiltinType::Id: 6046 #include "clang/Basic/OpenCLExtensionTypes.def" 6047 // In practice we'll never use this, since all SVE types are sugared 6048 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6049 #define SVE_TYPE(Name, Id, SingletonId) \ 6050 case BuiltinType::Id: 6051 #include "clang/Basic/AArch64SVEACLETypes.def" 6052 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6053 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6054 #include "clang/AST/BuiltinTypes.def" 6055 return false; 6056 6057 // We cannot lower out overload sets; they might validly be resolved 6058 // by the call machinery. 6059 case BuiltinType::Overload: 6060 return false; 6061 6062 // Unbridged casts in ARC can be handled in some call positions and 6063 // should be left in place. 6064 case BuiltinType::ARCUnbridgedCast: 6065 return false; 6066 6067 // Pseudo-objects should be converted as soon as possible. 6068 case BuiltinType::PseudoObject: 6069 return true; 6070 6071 // The debugger mode could theoretically but currently does not try 6072 // to resolve unknown-typed arguments based on known parameter types. 6073 case BuiltinType::UnknownAny: 6074 return true; 6075 6076 // These are always invalid as call arguments and should be reported. 6077 case BuiltinType::BoundMember: 6078 case BuiltinType::BuiltinFn: 6079 case BuiltinType::IncompleteMatrixIdx: 6080 case BuiltinType::OMPArraySection: 6081 case BuiltinType::OMPArrayShaping: 6082 case BuiltinType::OMPIterator: 6083 return true; 6084 6085 } 6086 llvm_unreachable("bad builtin type kind"); 6087 } 6088 6089 /// Check an argument list for placeholders that we won't try to 6090 /// handle later. 6091 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6092 // Apply this processing to all the arguments at once instead of 6093 // dying at the first failure. 6094 bool hasInvalid = false; 6095 for (size_t i = 0, e = args.size(); i != e; i++) { 6096 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6097 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6098 if (result.isInvalid()) hasInvalid = true; 6099 else args[i] = result.get(); 6100 } else if (hasInvalid) { 6101 (void)S.CorrectDelayedTyposInExpr(args[i]); 6102 } 6103 } 6104 return hasInvalid; 6105 } 6106 6107 /// If a builtin function has a pointer argument with no explicit address 6108 /// space, then it should be able to accept a pointer to any address 6109 /// space as input. In order to do this, we need to replace the 6110 /// standard builtin declaration with one that uses the same address space 6111 /// as the call. 6112 /// 6113 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6114 /// it does not contain any pointer arguments without 6115 /// an address space qualifer. Otherwise the rewritten 6116 /// FunctionDecl is returned. 6117 /// TODO: Handle pointer return types. 6118 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6119 FunctionDecl *FDecl, 6120 MultiExprArg ArgExprs) { 6121 6122 QualType DeclType = FDecl->getType(); 6123 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6124 6125 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6126 ArgExprs.size() < FT->getNumParams()) 6127 return nullptr; 6128 6129 bool NeedsNewDecl = false; 6130 unsigned i = 0; 6131 SmallVector<QualType, 8> OverloadParams; 6132 6133 for (QualType ParamType : FT->param_types()) { 6134 6135 // Convert array arguments to pointer to simplify type lookup. 6136 ExprResult ArgRes = 6137 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6138 if (ArgRes.isInvalid()) 6139 return nullptr; 6140 Expr *Arg = ArgRes.get(); 6141 QualType ArgType = Arg->getType(); 6142 if (!ParamType->isPointerType() || 6143 ParamType.hasAddressSpace() || 6144 !ArgType->isPointerType() || 6145 !ArgType->getPointeeType().hasAddressSpace()) { 6146 OverloadParams.push_back(ParamType); 6147 continue; 6148 } 6149 6150 QualType PointeeType = ParamType->getPointeeType(); 6151 if (PointeeType.hasAddressSpace()) 6152 continue; 6153 6154 NeedsNewDecl = true; 6155 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6156 6157 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6158 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6159 } 6160 6161 if (!NeedsNewDecl) 6162 return nullptr; 6163 6164 FunctionProtoType::ExtProtoInfo EPI; 6165 EPI.Variadic = FT->isVariadic(); 6166 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6167 OverloadParams, EPI); 6168 DeclContext *Parent = FDecl->getParent(); 6169 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6170 FDecl->getLocation(), 6171 FDecl->getLocation(), 6172 FDecl->getIdentifier(), 6173 OverloadTy, 6174 /*TInfo=*/nullptr, 6175 SC_Extern, false, 6176 /*hasPrototype=*/true); 6177 SmallVector<ParmVarDecl*, 16> Params; 6178 FT = cast<FunctionProtoType>(OverloadTy); 6179 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6180 QualType ParamType = FT->getParamType(i); 6181 ParmVarDecl *Parm = 6182 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6183 SourceLocation(), nullptr, ParamType, 6184 /*TInfo=*/nullptr, SC_None, nullptr); 6185 Parm->setScopeInfo(0, i); 6186 Params.push_back(Parm); 6187 } 6188 OverloadDecl->setParams(Params); 6189 return OverloadDecl; 6190 } 6191 6192 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6193 FunctionDecl *Callee, 6194 MultiExprArg ArgExprs) { 6195 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6196 // similar attributes) really don't like it when functions are called with an 6197 // invalid number of args. 6198 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6199 /*PartialOverloading=*/false) && 6200 !Callee->isVariadic()) 6201 return; 6202 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6203 return; 6204 6205 if (const EnableIfAttr *Attr = 6206 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6207 S.Diag(Fn->getBeginLoc(), 6208 isa<CXXMethodDecl>(Callee) 6209 ? diag::err_ovl_no_viable_member_function_in_call 6210 : diag::err_ovl_no_viable_function_in_call) 6211 << Callee << Callee->getSourceRange(); 6212 S.Diag(Callee->getLocation(), 6213 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6214 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6215 return; 6216 } 6217 } 6218 6219 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6220 const UnresolvedMemberExpr *const UME, Sema &S) { 6221 6222 const auto GetFunctionLevelDCIfCXXClass = 6223 [](Sema &S) -> const CXXRecordDecl * { 6224 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6225 if (!DC || !DC->getParent()) 6226 return nullptr; 6227 6228 // If the call to some member function was made from within a member 6229 // function body 'M' return return 'M's parent. 6230 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6231 return MD->getParent()->getCanonicalDecl(); 6232 // else the call was made from within a default member initializer of a 6233 // class, so return the class. 6234 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6235 return RD->getCanonicalDecl(); 6236 return nullptr; 6237 }; 6238 // If our DeclContext is neither a member function nor a class (in the 6239 // case of a lambda in a default member initializer), we can't have an 6240 // enclosing 'this'. 6241 6242 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6243 if (!CurParentClass) 6244 return false; 6245 6246 // The naming class for implicit member functions call is the class in which 6247 // name lookup starts. 6248 const CXXRecordDecl *const NamingClass = 6249 UME->getNamingClass()->getCanonicalDecl(); 6250 assert(NamingClass && "Must have naming class even for implicit access"); 6251 6252 // If the unresolved member functions were found in a 'naming class' that is 6253 // related (either the same or derived from) to the class that contains the 6254 // member function that itself contained the implicit member access. 6255 6256 return CurParentClass == NamingClass || 6257 CurParentClass->isDerivedFrom(NamingClass); 6258 } 6259 6260 static void 6261 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6262 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6263 6264 if (!UME) 6265 return; 6266 6267 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6268 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6269 // already been captured, or if this is an implicit member function call (if 6270 // it isn't, an attempt to capture 'this' should already have been made). 6271 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6272 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6273 return; 6274 6275 // Check if the naming class in which the unresolved members were found is 6276 // related (same as or is a base of) to the enclosing class. 6277 6278 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6279 return; 6280 6281 6282 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6283 // If the enclosing function is not dependent, then this lambda is 6284 // capture ready, so if we can capture this, do so. 6285 if (!EnclosingFunctionCtx->isDependentContext()) { 6286 // If the current lambda and all enclosing lambdas can capture 'this' - 6287 // then go ahead and capture 'this' (since our unresolved overload set 6288 // contains at least one non-static member function). 6289 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6290 S.CheckCXXThisCapture(CallLoc); 6291 } else if (S.CurContext->isDependentContext()) { 6292 // ... since this is an implicit member reference, that might potentially 6293 // involve a 'this' capture, mark 'this' for potential capture in 6294 // enclosing lambdas. 6295 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6296 CurLSI->addPotentialThisCapture(CallLoc); 6297 } 6298 } 6299 6300 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6301 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6302 Expr *ExecConfig) { 6303 ExprResult Call = 6304 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6305 if (Call.isInvalid()) 6306 return Call; 6307 6308 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6309 // language modes. 6310 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6311 if (ULE->hasExplicitTemplateArgs() && 6312 ULE->decls_begin() == ULE->decls_end()) { 6313 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6314 ? diag::warn_cxx17_compat_adl_only_template_id 6315 : diag::ext_adl_only_template_id) 6316 << ULE->getName(); 6317 } 6318 } 6319 6320 if (LangOpts.OpenMP) 6321 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6322 ExecConfig); 6323 6324 return Call; 6325 } 6326 6327 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6328 /// This provides the location of the left/right parens and a list of comma 6329 /// locations. 6330 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6331 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6332 Expr *ExecConfig, bool IsExecConfig) { 6333 // Since this might be a postfix expression, get rid of ParenListExprs. 6334 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6335 if (Result.isInvalid()) return ExprError(); 6336 Fn = Result.get(); 6337 6338 if (checkArgsForPlaceholders(*this, ArgExprs)) 6339 return ExprError(); 6340 6341 if (getLangOpts().CPlusPlus) { 6342 // If this is a pseudo-destructor expression, build the call immediately. 6343 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6344 if (!ArgExprs.empty()) { 6345 // Pseudo-destructor calls should not have any arguments. 6346 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6347 << FixItHint::CreateRemoval( 6348 SourceRange(ArgExprs.front()->getBeginLoc(), 6349 ArgExprs.back()->getEndLoc())); 6350 } 6351 6352 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6353 VK_RValue, RParenLoc); 6354 } 6355 if (Fn->getType() == Context.PseudoObjectTy) { 6356 ExprResult result = CheckPlaceholderExpr(Fn); 6357 if (result.isInvalid()) return ExprError(); 6358 Fn = result.get(); 6359 } 6360 6361 // Determine whether this is a dependent call inside a C++ template, 6362 // in which case we won't do any semantic analysis now. 6363 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6364 if (ExecConfig) { 6365 return CUDAKernelCallExpr::Create( 6366 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6367 Context.DependentTy, VK_RValue, RParenLoc); 6368 } else { 6369 6370 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6371 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6372 Fn->getBeginLoc()); 6373 6374 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6375 VK_RValue, RParenLoc); 6376 } 6377 } 6378 6379 // Determine whether this is a call to an object (C++ [over.call.object]). 6380 if (Fn->getType()->isRecordType()) 6381 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6382 RParenLoc); 6383 6384 if (Fn->getType() == Context.UnknownAnyTy) { 6385 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6386 if (result.isInvalid()) return ExprError(); 6387 Fn = result.get(); 6388 } 6389 6390 if (Fn->getType() == Context.BoundMemberTy) { 6391 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6392 RParenLoc); 6393 } 6394 } 6395 6396 // Check for overloaded calls. This can happen even in C due to extensions. 6397 if (Fn->getType() == Context.OverloadTy) { 6398 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6399 6400 // We aren't supposed to apply this logic if there's an '&' involved. 6401 if (!find.HasFormOfMemberPointer) { 6402 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6403 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6404 VK_RValue, RParenLoc); 6405 OverloadExpr *ovl = find.Expression; 6406 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6407 return BuildOverloadedCallExpr( 6408 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6409 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6410 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6411 RParenLoc); 6412 } 6413 } 6414 6415 // If we're directly calling a function, get the appropriate declaration. 6416 if (Fn->getType() == Context.UnknownAnyTy) { 6417 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6418 if (result.isInvalid()) return ExprError(); 6419 Fn = result.get(); 6420 } 6421 6422 Expr *NakedFn = Fn->IgnoreParens(); 6423 6424 bool CallingNDeclIndirectly = false; 6425 NamedDecl *NDecl = nullptr; 6426 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6427 if (UnOp->getOpcode() == UO_AddrOf) { 6428 CallingNDeclIndirectly = true; 6429 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6430 } 6431 } 6432 6433 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6434 NDecl = DRE->getDecl(); 6435 6436 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6437 if (FDecl && FDecl->getBuiltinID()) { 6438 // Rewrite the function decl for this builtin by replacing parameters 6439 // with no explicit address space with the address space of the arguments 6440 // in ArgExprs. 6441 if ((FDecl = 6442 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6443 NDecl = FDecl; 6444 Fn = DeclRefExpr::Create( 6445 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6446 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6447 nullptr, DRE->isNonOdrUse()); 6448 } 6449 } 6450 } else if (isa<MemberExpr>(NakedFn)) 6451 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6452 6453 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6454 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6455 FD, /*Complain=*/true, Fn->getBeginLoc())) 6456 return ExprError(); 6457 6458 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6459 return ExprError(); 6460 6461 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6462 } 6463 6464 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6465 ExecConfig, IsExecConfig); 6466 } 6467 6468 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6469 /// 6470 /// __builtin_astype( value, dst type ) 6471 /// 6472 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6473 SourceLocation BuiltinLoc, 6474 SourceLocation RParenLoc) { 6475 ExprValueKind VK = VK_RValue; 6476 ExprObjectKind OK = OK_Ordinary; 6477 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6478 QualType SrcTy = E->getType(); 6479 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6480 return ExprError(Diag(BuiltinLoc, 6481 diag::err_invalid_astype_of_different_size) 6482 << DstTy 6483 << SrcTy 6484 << E->getSourceRange()); 6485 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6486 } 6487 6488 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6489 /// provided arguments. 6490 /// 6491 /// __builtin_convertvector( value, dst type ) 6492 /// 6493 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6494 SourceLocation BuiltinLoc, 6495 SourceLocation RParenLoc) { 6496 TypeSourceInfo *TInfo; 6497 GetTypeFromParser(ParsedDestTy, &TInfo); 6498 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6499 } 6500 6501 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6502 /// i.e. an expression not of \p OverloadTy. The expression should 6503 /// unary-convert to an expression of function-pointer or 6504 /// block-pointer type. 6505 /// 6506 /// \param NDecl the declaration being called, if available 6507 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6508 SourceLocation LParenLoc, 6509 ArrayRef<Expr *> Args, 6510 SourceLocation RParenLoc, Expr *Config, 6511 bool IsExecConfig, ADLCallKind UsesADL) { 6512 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6513 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6514 6515 // Functions with 'interrupt' attribute cannot be called directly. 6516 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6517 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6518 return ExprError(); 6519 } 6520 6521 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6522 // so there's some risk when calling out to non-interrupt handler functions 6523 // that the callee might not preserve them. This is easy to diagnose here, 6524 // but can be very challenging to debug. 6525 if (auto *Caller = getCurFunctionDecl()) 6526 if (Caller->hasAttr<ARMInterruptAttr>()) { 6527 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6528 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6529 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6530 } 6531 6532 // Promote the function operand. 6533 // We special-case function promotion here because we only allow promoting 6534 // builtin functions to function pointers in the callee of a call. 6535 ExprResult Result; 6536 QualType ResultTy; 6537 if (BuiltinID && 6538 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6539 // Extract the return type from the (builtin) function pointer type. 6540 // FIXME Several builtins still have setType in 6541 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6542 // Builtins.def to ensure they are correct before removing setType calls. 6543 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6544 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6545 ResultTy = FDecl->getCallResultType(); 6546 } else { 6547 Result = CallExprUnaryConversions(Fn); 6548 ResultTy = Context.BoolTy; 6549 } 6550 if (Result.isInvalid()) 6551 return ExprError(); 6552 Fn = Result.get(); 6553 6554 // Check for a valid function type, but only if it is not a builtin which 6555 // requires custom type checking. These will be handled by 6556 // CheckBuiltinFunctionCall below just after creation of the call expression. 6557 const FunctionType *FuncT = nullptr; 6558 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6559 retry: 6560 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6561 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6562 // have type pointer to function". 6563 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6564 if (!FuncT) 6565 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6566 << Fn->getType() << Fn->getSourceRange()); 6567 } else if (const BlockPointerType *BPT = 6568 Fn->getType()->getAs<BlockPointerType>()) { 6569 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6570 } else { 6571 // Handle calls to expressions of unknown-any type. 6572 if (Fn->getType() == Context.UnknownAnyTy) { 6573 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6574 if (rewrite.isInvalid()) 6575 return ExprError(); 6576 Fn = rewrite.get(); 6577 goto retry; 6578 } 6579 6580 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6581 << Fn->getType() << Fn->getSourceRange()); 6582 } 6583 } 6584 6585 // Get the number of parameters in the function prototype, if any. 6586 // We will allocate space for max(Args.size(), NumParams) arguments 6587 // in the call expression. 6588 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6589 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6590 6591 CallExpr *TheCall; 6592 if (Config) { 6593 assert(UsesADL == ADLCallKind::NotADL && 6594 "CUDAKernelCallExpr should not use ADL"); 6595 TheCall = 6596 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6597 ResultTy, VK_RValue, RParenLoc, NumParams); 6598 } else { 6599 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6600 RParenLoc, NumParams, UsesADL); 6601 } 6602 6603 if (!getLangOpts().CPlusPlus) { 6604 // Forget about the nulled arguments since typo correction 6605 // do not handle them well. 6606 TheCall->shrinkNumArgs(Args.size()); 6607 // C cannot always handle TypoExpr nodes in builtin calls and direct 6608 // function calls as their argument checking don't necessarily handle 6609 // dependent types properly, so make sure any TypoExprs have been 6610 // dealt with. 6611 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6612 if (!Result.isUsable()) return ExprError(); 6613 CallExpr *TheOldCall = TheCall; 6614 TheCall = dyn_cast<CallExpr>(Result.get()); 6615 bool CorrectedTypos = TheCall != TheOldCall; 6616 if (!TheCall) return Result; 6617 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6618 6619 // A new call expression node was created if some typos were corrected. 6620 // However it may not have been constructed with enough storage. In this 6621 // case, rebuild the node with enough storage. The waste of space is 6622 // immaterial since this only happens when some typos were corrected. 6623 if (CorrectedTypos && Args.size() < NumParams) { 6624 if (Config) 6625 TheCall = CUDAKernelCallExpr::Create( 6626 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6627 RParenLoc, NumParams); 6628 else 6629 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6630 RParenLoc, NumParams, UsesADL); 6631 } 6632 // We can now handle the nulled arguments for the default arguments. 6633 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6634 } 6635 6636 // Bail out early if calling a builtin with custom type checking. 6637 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6638 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6639 6640 if (getLangOpts().CUDA) { 6641 if (Config) { 6642 // CUDA: Kernel calls must be to global functions 6643 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6644 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6645 << FDecl << Fn->getSourceRange()); 6646 6647 // CUDA: Kernel function must have 'void' return type 6648 if (!FuncT->getReturnType()->isVoidType() && 6649 !FuncT->getReturnType()->getAs<AutoType>() && 6650 !FuncT->getReturnType()->isInstantiationDependentType()) 6651 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6652 << Fn->getType() << Fn->getSourceRange()); 6653 } else { 6654 // CUDA: Calls to global functions must be configured 6655 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6656 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6657 << FDecl << Fn->getSourceRange()); 6658 } 6659 } 6660 6661 // Check for a valid return type 6662 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6663 FDecl)) 6664 return ExprError(); 6665 6666 // We know the result type of the call, set it. 6667 TheCall->setType(FuncT->getCallResultType(Context)); 6668 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6669 6670 if (Proto) { 6671 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6672 IsExecConfig)) 6673 return ExprError(); 6674 } else { 6675 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6676 6677 if (FDecl) { 6678 // Check if we have too few/too many template arguments, based 6679 // on our knowledge of the function definition. 6680 const FunctionDecl *Def = nullptr; 6681 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6682 Proto = Def->getType()->getAs<FunctionProtoType>(); 6683 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6684 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6685 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6686 } 6687 6688 // If the function we're calling isn't a function prototype, but we have 6689 // a function prototype from a prior declaratiom, use that prototype. 6690 if (!FDecl->hasPrototype()) 6691 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6692 } 6693 6694 // Promote the arguments (C99 6.5.2.2p6). 6695 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6696 Expr *Arg = Args[i]; 6697 6698 if (Proto && i < Proto->getNumParams()) { 6699 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6700 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6701 ExprResult ArgE = 6702 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6703 if (ArgE.isInvalid()) 6704 return true; 6705 6706 Arg = ArgE.getAs<Expr>(); 6707 6708 } else { 6709 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6710 6711 if (ArgE.isInvalid()) 6712 return true; 6713 6714 Arg = ArgE.getAs<Expr>(); 6715 } 6716 6717 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6718 diag::err_call_incomplete_argument, Arg)) 6719 return ExprError(); 6720 6721 TheCall->setArg(i, Arg); 6722 } 6723 } 6724 6725 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6726 if (!Method->isStatic()) 6727 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6728 << Fn->getSourceRange()); 6729 6730 // Check for sentinels 6731 if (NDecl) 6732 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6733 6734 // Warn for unions passing across security boundary (CMSE). 6735 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6736 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6737 if (const auto *RT = 6738 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6739 if (RT->getDecl()->isOrContainsUnion()) 6740 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6741 << 0 << i; 6742 } 6743 } 6744 } 6745 6746 // Do special checking on direct calls to functions. 6747 if (FDecl) { 6748 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6749 return ExprError(); 6750 6751 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6752 6753 if (BuiltinID) 6754 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6755 } else if (NDecl) { 6756 if (CheckPointerCall(NDecl, TheCall, Proto)) 6757 return ExprError(); 6758 } else { 6759 if (CheckOtherCall(TheCall, Proto)) 6760 return ExprError(); 6761 } 6762 6763 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6764 } 6765 6766 ExprResult 6767 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6768 SourceLocation RParenLoc, Expr *InitExpr) { 6769 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6770 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6771 6772 TypeSourceInfo *TInfo; 6773 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6774 if (!TInfo) 6775 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6776 6777 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6778 } 6779 6780 ExprResult 6781 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6782 SourceLocation RParenLoc, Expr *LiteralExpr) { 6783 QualType literalType = TInfo->getType(); 6784 6785 if (literalType->isArrayType()) { 6786 if (RequireCompleteSizedType( 6787 LParenLoc, Context.getBaseElementType(literalType), 6788 diag::err_array_incomplete_or_sizeless_type, 6789 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6790 return ExprError(); 6791 if (literalType->isVariableArrayType()) 6792 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6793 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6794 } else if (!literalType->isDependentType() && 6795 RequireCompleteType(LParenLoc, literalType, 6796 diag::err_typecheck_decl_incomplete_type, 6797 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6798 return ExprError(); 6799 6800 InitializedEntity Entity 6801 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6802 InitializationKind Kind 6803 = InitializationKind::CreateCStyleCast(LParenLoc, 6804 SourceRange(LParenLoc, RParenLoc), 6805 /*InitList=*/true); 6806 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6807 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6808 &literalType); 6809 if (Result.isInvalid()) 6810 return ExprError(); 6811 LiteralExpr = Result.get(); 6812 6813 bool isFileScope = !CurContext->isFunctionOrMethod(); 6814 6815 // In C, compound literals are l-values for some reason. 6816 // For GCC compatibility, in C++, file-scope array compound literals with 6817 // constant initializers are also l-values, and compound literals are 6818 // otherwise prvalues. 6819 // 6820 // (GCC also treats C++ list-initialized file-scope array prvalues with 6821 // constant initializers as l-values, but that's non-conforming, so we don't 6822 // follow it there.) 6823 // 6824 // FIXME: It would be better to handle the lvalue cases as materializing and 6825 // lifetime-extending a temporary object, but our materialized temporaries 6826 // representation only supports lifetime extension from a variable, not "out 6827 // of thin air". 6828 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6829 // is bound to the result of applying array-to-pointer decay to the compound 6830 // literal. 6831 // FIXME: GCC supports compound literals of reference type, which should 6832 // obviously have a value kind derived from the kind of reference involved. 6833 ExprValueKind VK = 6834 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6835 ? VK_RValue 6836 : VK_LValue; 6837 6838 if (isFileScope) 6839 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6840 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6841 Expr *Init = ILE->getInit(i); 6842 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6843 } 6844 6845 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6846 VK, LiteralExpr, isFileScope); 6847 if (isFileScope) { 6848 if (!LiteralExpr->isTypeDependent() && 6849 !LiteralExpr->isValueDependent() && 6850 !literalType->isDependentType()) // C99 6.5.2.5p3 6851 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6852 return ExprError(); 6853 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6854 literalType.getAddressSpace() != LangAS::Default) { 6855 // Embedded-C extensions to C99 6.5.2.5: 6856 // "If the compound literal occurs inside the body of a function, the 6857 // type name shall not be qualified by an address-space qualifier." 6858 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6859 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6860 return ExprError(); 6861 } 6862 6863 if (!isFileScope && !getLangOpts().CPlusPlus) { 6864 // Compound literals that have automatic storage duration are destroyed at 6865 // the end of the scope in C; in C++, they're just temporaries. 6866 6867 // Emit diagnostics if it is or contains a C union type that is non-trivial 6868 // to destruct. 6869 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6870 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6871 NTCUC_CompoundLiteral, NTCUK_Destruct); 6872 6873 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6874 if (literalType.isDestructedType()) { 6875 Cleanup.setExprNeedsCleanups(true); 6876 ExprCleanupObjects.push_back(E); 6877 getCurFunction()->setHasBranchProtectedScope(); 6878 } 6879 } 6880 6881 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6882 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6883 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6884 E->getInitializer()->getExprLoc()); 6885 6886 return MaybeBindToTemporary(E); 6887 } 6888 6889 ExprResult 6890 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6891 SourceLocation RBraceLoc) { 6892 // Only produce each kind of designated initialization diagnostic once. 6893 SourceLocation FirstDesignator; 6894 bool DiagnosedArrayDesignator = false; 6895 bool DiagnosedNestedDesignator = false; 6896 bool DiagnosedMixedDesignator = false; 6897 6898 // Check that any designated initializers are syntactically valid in the 6899 // current language mode. 6900 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6901 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6902 if (FirstDesignator.isInvalid()) 6903 FirstDesignator = DIE->getBeginLoc(); 6904 6905 if (!getLangOpts().CPlusPlus) 6906 break; 6907 6908 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6909 DiagnosedNestedDesignator = true; 6910 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6911 << DIE->getDesignatorsSourceRange(); 6912 } 6913 6914 for (auto &Desig : DIE->designators()) { 6915 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6916 DiagnosedArrayDesignator = true; 6917 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6918 << Desig.getSourceRange(); 6919 } 6920 } 6921 6922 if (!DiagnosedMixedDesignator && 6923 !isa<DesignatedInitExpr>(InitArgList[0])) { 6924 DiagnosedMixedDesignator = true; 6925 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6926 << DIE->getSourceRange(); 6927 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6928 << InitArgList[0]->getSourceRange(); 6929 } 6930 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6931 isa<DesignatedInitExpr>(InitArgList[0])) { 6932 DiagnosedMixedDesignator = true; 6933 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6934 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6935 << DIE->getSourceRange(); 6936 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6937 << InitArgList[I]->getSourceRange(); 6938 } 6939 } 6940 6941 if (FirstDesignator.isValid()) { 6942 // Only diagnose designated initiaization as a C++20 extension if we didn't 6943 // already diagnose use of (non-C++20) C99 designator syntax. 6944 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6945 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6946 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6947 ? diag::warn_cxx17_compat_designated_init 6948 : diag::ext_cxx_designated_init); 6949 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6950 Diag(FirstDesignator, diag::ext_designated_init); 6951 } 6952 } 6953 6954 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6955 } 6956 6957 ExprResult 6958 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6959 SourceLocation RBraceLoc) { 6960 // Semantic analysis for initializers is done by ActOnDeclarator() and 6961 // CheckInitializer() - it requires knowledge of the object being initialized. 6962 6963 // Immediately handle non-overload placeholders. Overloads can be 6964 // resolved contextually, but everything else here can't. 6965 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6966 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6967 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6968 6969 // Ignore failures; dropping the entire initializer list because 6970 // of one failure would be terrible for indexing/etc. 6971 if (result.isInvalid()) continue; 6972 6973 InitArgList[I] = result.get(); 6974 } 6975 } 6976 6977 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6978 RBraceLoc); 6979 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6980 return E; 6981 } 6982 6983 /// Do an explicit extend of the given block pointer if we're in ARC. 6984 void Sema::maybeExtendBlockObject(ExprResult &E) { 6985 assert(E.get()->getType()->isBlockPointerType()); 6986 assert(E.get()->isRValue()); 6987 6988 // Only do this in an r-value context. 6989 if (!getLangOpts().ObjCAutoRefCount) return; 6990 6991 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6992 CK_ARCExtendBlockObject, E.get(), 6993 /*base path*/ nullptr, VK_RValue); 6994 Cleanup.setExprNeedsCleanups(true); 6995 } 6996 6997 /// Prepare a conversion of the given expression to an ObjC object 6998 /// pointer type. 6999 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7000 QualType type = E.get()->getType(); 7001 if (type->isObjCObjectPointerType()) { 7002 return CK_BitCast; 7003 } else if (type->isBlockPointerType()) { 7004 maybeExtendBlockObject(E); 7005 return CK_BlockPointerToObjCPointerCast; 7006 } else { 7007 assert(type->isPointerType()); 7008 return CK_CPointerToObjCPointerCast; 7009 } 7010 } 7011 7012 /// Prepares for a scalar cast, performing all the necessary stages 7013 /// except the final cast and returning the kind required. 7014 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7015 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7016 // Also, callers should have filtered out the invalid cases with 7017 // pointers. Everything else should be possible. 7018 7019 QualType SrcTy = Src.get()->getType(); 7020 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7021 return CK_NoOp; 7022 7023 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7024 case Type::STK_MemberPointer: 7025 llvm_unreachable("member pointer type in C"); 7026 7027 case Type::STK_CPointer: 7028 case Type::STK_BlockPointer: 7029 case Type::STK_ObjCObjectPointer: 7030 switch (DestTy->getScalarTypeKind()) { 7031 case Type::STK_CPointer: { 7032 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7033 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7034 if (SrcAS != DestAS) 7035 return CK_AddressSpaceConversion; 7036 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7037 return CK_NoOp; 7038 return CK_BitCast; 7039 } 7040 case Type::STK_BlockPointer: 7041 return (SrcKind == Type::STK_BlockPointer 7042 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7043 case Type::STK_ObjCObjectPointer: 7044 if (SrcKind == Type::STK_ObjCObjectPointer) 7045 return CK_BitCast; 7046 if (SrcKind == Type::STK_CPointer) 7047 return CK_CPointerToObjCPointerCast; 7048 maybeExtendBlockObject(Src); 7049 return CK_BlockPointerToObjCPointerCast; 7050 case Type::STK_Bool: 7051 return CK_PointerToBoolean; 7052 case Type::STK_Integral: 7053 return CK_PointerToIntegral; 7054 case Type::STK_Floating: 7055 case Type::STK_FloatingComplex: 7056 case Type::STK_IntegralComplex: 7057 case Type::STK_MemberPointer: 7058 case Type::STK_FixedPoint: 7059 llvm_unreachable("illegal cast from pointer"); 7060 } 7061 llvm_unreachable("Should have returned before this"); 7062 7063 case Type::STK_FixedPoint: 7064 switch (DestTy->getScalarTypeKind()) { 7065 case Type::STK_FixedPoint: 7066 return CK_FixedPointCast; 7067 case Type::STK_Bool: 7068 return CK_FixedPointToBoolean; 7069 case Type::STK_Integral: 7070 return CK_FixedPointToIntegral; 7071 case Type::STK_Floating: 7072 case Type::STK_IntegralComplex: 7073 case Type::STK_FloatingComplex: 7074 Diag(Src.get()->getExprLoc(), 7075 diag::err_unimplemented_conversion_with_fixed_point_type) 7076 << DestTy; 7077 return CK_IntegralCast; 7078 case Type::STK_CPointer: 7079 case Type::STK_ObjCObjectPointer: 7080 case Type::STK_BlockPointer: 7081 case Type::STK_MemberPointer: 7082 llvm_unreachable("illegal cast to pointer type"); 7083 } 7084 llvm_unreachable("Should have returned before this"); 7085 7086 case Type::STK_Bool: // casting from bool is like casting from an integer 7087 case Type::STK_Integral: 7088 switch (DestTy->getScalarTypeKind()) { 7089 case Type::STK_CPointer: 7090 case Type::STK_ObjCObjectPointer: 7091 case Type::STK_BlockPointer: 7092 if (Src.get()->isNullPointerConstant(Context, 7093 Expr::NPC_ValueDependentIsNull)) 7094 return CK_NullToPointer; 7095 return CK_IntegralToPointer; 7096 case Type::STK_Bool: 7097 return CK_IntegralToBoolean; 7098 case Type::STK_Integral: 7099 return CK_IntegralCast; 7100 case Type::STK_Floating: 7101 return CK_IntegralToFloating; 7102 case Type::STK_IntegralComplex: 7103 Src = ImpCastExprToType(Src.get(), 7104 DestTy->castAs<ComplexType>()->getElementType(), 7105 CK_IntegralCast); 7106 return CK_IntegralRealToComplex; 7107 case Type::STK_FloatingComplex: 7108 Src = ImpCastExprToType(Src.get(), 7109 DestTy->castAs<ComplexType>()->getElementType(), 7110 CK_IntegralToFloating); 7111 return CK_FloatingRealToComplex; 7112 case Type::STK_MemberPointer: 7113 llvm_unreachable("member pointer type in C"); 7114 case Type::STK_FixedPoint: 7115 return CK_IntegralToFixedPoint; 7116 } 7117 llvm_unreachable("Should have returned before this"); 7118 7119 case Type::STK_Floating: 7120 switch (DestTy->getScalarTypeKind()) { 7121 case Type::STK_Floating: 7122 return CK_FloatingCast; 7123 case Type::STK_Bool: 7124 return CK_FloatingToBoolean; 7125 case Type::STK_Integral: 7126 return CK_FloatingToIntegral; 7127 case Type::STK_FloatingComplex: 7128 Src = ImpCastExprToType(Src.get(), 7129 DestTy->castAs<ComplexType>()->getElementType(), 7130 CK_FloatingCast); 7131 return CK_FloatingRealToComplex; 7132 case Type::STK_IntegralComplex: 7133 Src = ImpCastExprToType(Src.get(), 7134 DestTy->castAs<ComplexType>()->getElementType(), 7135 CK_FloatingToIntegral); 7136 return CK_IntegralRealToComplex; 7137 case Type::STK_CPointer: 7138 case Type::STK_ObjCObjectPointer: 7139 case Type::STK_BlockPointer: 7140 llvm_unreachable("valid float->pointer cast?"); 7141 case Type::STK_MemberPointer: 7142 llvm_unreachable("member pointer type in C"); 7143 case Type::STK_FixedPoint: 7144 Diag(Src.get()->getExprLoc(), 7145 diag::err_unimplemented_conversion_with_fixed_point_type) 7146 << SrcTy; 7147 return CK_IntegralCast; 7148 } 7149 llvm_unreachable("Should have returned before this"); 7150 7151 case Type::STK_FloatingComplex: 7152 switch (DestTy->getScalarTypeKind()) { 7153 case Type::STK_FloatingComplex: 7154 return CK_FloatingComplexCast; 7155 case Type::STK_IntegralComplex: 7156 return CK_FloatingComplexToIntegralComplex; 7157 case Type::STK_Floating: { 7158 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7159 if (Context.hasSameType(ET, DestTy)) 7160 return CK_FloatingComplexToReal; 7161 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7162 return CK_FloatingCast; 7163 } 7164 case Type::STK_Bool: 7165 return CK_FloatingComplexToBoolean; 7166 case Type::STK_Integral: 7167 Src = ImpCastExprToType(Src.get(), 7168 SrcTy->castAs<ComplexType>()->getElementType(), 7169 CK_FloatingComplexToReal); 7170 return CK_FloatingToIntegral; 7171 case Type::STK_CPointer: 7172 case Type::STK_ObjCObjectPointer: 7173 case Type::STK_BlockPointer: 7174 llvm_unreachable("valid complex float->pointer cast?"); 7175 case Type::STK_MemberPointer: 7176 llvm_unreachable("member pointer type in C"); 7177 case Type::STK_FixedPoint: 7178 Diag(Src.get()->getExprLoc(), 7179 diag::err_unimplemented_conversion_with_fixed_point_type) 7180 << SrcTy; 7181 return CK_IntegralCast; 7182 } 7183 llvm_unreachable("Should have returned before this"); 7184 7185 case Type::STK_IntegralComplex: 7186 switch (DestTy->getScalarTypeKind()) { 7187 case Type::STK_FloatingComplex: 7188 return CK_IntegralComplexToFloatingComplex; 7189 case Type::STK_IntegralComplex: 7190 return CK_IntegralComplexCast; 7191 case Type::STK_Integral: { 7192 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7193 if (Context.hasSameType(ET, DestTy)) 7194 return CK_IntegralComplexToReal; 7195 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7196 return CK_IntegralCast; 7197 } 7198 case Type::STK_Bool: 7199 return CK_IntegralComplexToBoolean; 7200 case Type::STK_Floating: 7201 Src = ImpCastExprToType(Src.get(), 7202 SrcTy->castAs<ComplexType>()->getElementType(), 7203 CK_IntegralComplexToReal); 7204 return CK_IntegralToFloating; 7205 case Type::STK_CPointer: 7206 case Type::STK_ObjCObjectPointer: 7207 case Type::STK_BlockPointer: 7208 llvm_unreachable("valid complex int->pointer cast?"); 7209 case Type::STK_MemberPointer: 7210 llvm_unreachable("member pointer type in C"); 7211 case Type::STK_FixedPoint: 7212 Diag(Src.get()->getExprLoc(), 7213 diag::err_unimplemented_conversion_with_fixed_point_type) 7214 << SrcTy; 7215 return CK_IntegralCast; 7216 } 7217 llvm_unreachable("Should have returned before this"); 7218 } 7219 7220 llvm_unreachable("Unhandled scalar cast"); 7221 } 7222 7223 static bool breakDownVectorType(QualType type, uint64_t &len, 7224 QualType &eltType) { 7225 // Vectors are simple. 7226 if (const VectorType *vecType = type->getAs<VectorType>()) { 7227 len = vecType->getNumElements(); 7228 eltType = vecType->getElementType(); 7229 assert(eltType->isScalarType()); 7230 return true; 7231 } 7232 7233 // We allow lax conversion to and from non-vector types, but only if 7234 // they're real types (i.e. non-complex, non-pointer scalar types). 7235 if (!type->isRealType()) return false; 7236 7237 len = 1; 7238 eltType = type; 7239 return true; 7240 } 7241 7242 /// Are the two types lax-compatible vector types? That is, given 7243 /// that one of them is a vector, do they have equal storage sizes, 7244 /// where the storage size is the number of elements times the element 7245 /// size? 7246 /// 7247 /// This will also return false if either of the types is neither a 7248 /// vector nor a real type. 7249 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7250 assert(destTy->isVectorType() || srcTy->isVectorType()); 7251 7252 // Disallow lax conversions between scalars and ExtVectors (these 7253 // conversions are allowed for other vector types because common headers 7254 // depend on them). Most scalar OP ExtVector cases are handled by the 7255 // splat path anyway, which does what we want (convert, not bitcast). 7256 // What this rules out for ExtVectors is crazy things like char4*float. 7257 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7258 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7259 7260 uint64_t srcLen, destLen; 7261 QualType srcEltTy, destEltTy; 7262 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7263 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7264 7265 // ASTContext::getTypeSize will return the size rounded up to a 7266 // power of 2, so instead of using that, we need to use the raw 7267 // element size multiplied by the element count. 7268 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7269 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7270 7271 return (srcLen * srcEltSize == destLen * destEltSize); 7272 } 7273 7274 /// Is this a legal conversion between two types, one of which is 7275 /// known to be a vector type? 7276 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7277 assert(destTy->isVectorType() || srcTy->isVectorType()); 7278 7279 switch (Context.getLangOpts().getLaxVectorConversions()) { 7280 case LangOptions::LaxVectorConversionKind::None: 7281 return false; 7282 7283 case LangOptions::LaxVectorConversionKind::Integer: 7284 if (!srcTy->isIntegralOrEnumerationType()) { 7285 auto *Vec = srcTy->getAs<VectorType>(); 7286 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7287 return false; 7288 } 7289 if (!destTy->isIntegralOrEnumerationType()) { 7290 auto *Vec = destTy->getAs<VectorType>(); 7291 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7292 return false; 7293 } 7294 // OK, integer (vector) -> integer (vector) bitcast. 7295 break; 7296 7297 case LangOptions::LaxVectorConversionKind::All: 7298 break; 7299 } 7300 7301 return areLaxCompatibleVectorTypes(srcTy, destTy); 7302 } 7303 7304 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7305 CastKind &Kind) { 7306 assert(VectorTy->isVectorType() && "Not a vector type!"); 7307 7308 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7309 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7310 return Diag(R.getBegin(), 7311 Ty->isVectorType() ? 7312 diag::err_invalid_conversion_between_vectors : 7313 diag::err_invalid_conversion_between_vector_and_integer) 7314 << VectorTy << Ty << R; 7315 } else 7316 return Diag(R.getBegin(), 7317 diag::err_invalid_conversion_between_vector_and_scalar) 7318 << VectorTy << Ty << R; 7319 7320 Kind = CK_BitCast; 7321 return false; 7322 } 7323 7324 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7325 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7326 7327 if (DestElemTy == SplattedExpr->getType()) 7328 return SplattedExpr; 7329 7330 assert(DestElemTy->isFloatingType() || 7331 DestElemTy->isIntegralOrEnumerationType()); 7332 7333 CastKind CK; 7334 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7335 // OpenCL requires that we convert `true` boolean expressions to -1, but 7336 // only when splatting vectors. 7337 if (DestElemTy->isFloatingType()) { 7338 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7339 // in two steps: boolean to signed integral, then to floating. 7340 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7341 CK_BooleanToSignedIntegral); 7342 SplattedExpr = CastExprRes.get(); 7343 CK = CK_IntegralToFloating; 7344 } else { 7345 CK = CK_BooleanToSignedIntegral; 7346 } 7347 } else { 7348 ExprResult CastExprRes = SplattedExpr; 7349 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7350 if (CastExprRes.isInvalid()) 7351 return ExprError(); 7352 SplattedExpr = CastExprRes.get(); 7353 } 7354 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7355 } 7356 7357 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7358 Expr *CastExpr, CastKind &Kind) { 7359 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7360 7361 QualType SrcTy = CastExpr->getType(); 7362 7363 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7364 // an ExtVectorType. 7365 // In OpenCL, casts between vectors of different types are not allowed. 7366 // (See OpenCL 6.2). 7367 if (SrcTy->isVectorType()) { 7368 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7369 (getLangOpts().OpenCL && 7370 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7371 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7372 << DestTy << SrcTy << R; 7373 return ExprError(); 7374 } 7375 Kind = CK_BitCast; 7376 return CastExpr; 7377 } 7378 7379 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7380 // conversion will take place first from scalar to elt type, and then 7381 // splat from elt type to vector. 7382 if (SrcTy->isPointerType()) 7383 return Diag(R.getBegin(), 7384 diag::err_invalid_conversion_between_vector_and_scalar) 7385 << DestTy << SrcTy << R; 7386 7387 Kind = CK_VectorSplat; 7388 return prepareVectorSplat(DestTy, CastExpr); 7389 } 7390 7391 ExprResult 7392 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7393 Declarator &D, ParsedType &Ty, 7394 SourceLocation RParenLoc, Expr *CastExpr) { 7395 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7396 "ActOnCastExpr(): missing type or expr"); 7397 7398 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7399 if (D.isInvalidType()) 7400 return ExprError(); 7401 7402 if (getLangOpts().CPlusPlus) { 7403 // Check that there are no default arguments (C++ only). 7404 CheckExtraCXXDefaultArguments(D); 7405 } else { 7406 // Make sure any TypoExprs have been dealt with. 7407 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7408 if (!Res.isUsable()) 7409 return ExprError(); 7410 CastExpr = Res.get(); 7411 } 7412 7413 checkUnusedDeclAttributes(D); 7414 7415 QualType castType = castTInfo->getType(); 7416 Ty = CreateParsedType(castType, castTInfo); 7417 7418 bool isVectorLiteral = false; 7419 7420 // Check for an altivec or OpenCL literal, 7421 // i.e. all the elements are integer constants. 7422 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7423 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7424 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7425 && castType->isVectorType() && (PE || PLE)) { 7426 if (PLE && PLE->getNumExprs() == 0) { 7427 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7428 return ExprError(); 7429 } 7430 if (PE || PLE->getNumExprs() == 1) { 7431 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7432 if (!E->getType()->isVectorType()) 7433 isVectorLiteral = true; 7434 } 7435 else 7436 isVectorLiteral = true; 7437 } 7438 7439 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7440 // then handle it as such. 7441 if (isVectorLiteral) 7442 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7443 7444 // If the Expr being casted is a ParenListExpr, handle it specially. 7445 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7446 // sequence of BinOp comma operators. 7447 if (isa<ParenListExpr>(CastExpr)) { 7448 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7449 if (Result.isInvalid()) return ExprError(); 7450 CastExpr = Result.get(); 7451 } 7452 7453 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7454 !getSourceManager().isInSystemMacro(LParenLoc)) 7455 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7456 7457 CheckTollFreeBridgeCast(castType, CastExpr); 7458 7459 CheckObjCBridgeRelatedCast(castType, CastExpr); 7460 7461 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7462 7463 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7464 } 7465 7466 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7467 SourceLocation RParenLoc, Expr *E, 7468 TypeSourceInfo *TInfo) { 7469 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7470 "Expected paren or paren list expression"); 7471 7472 Expr **exprs; 7473 unsigned numExprs; 7474 Expr *subExpr; 7475 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7476 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7477 LiteralLParenLoc = PE->getLParenLoc(); 7478 LiteralRParenLoc = PE->getRParenLoc(); 7479 exprs = PE->getExprs(); 7480 numExprs = PE->getNumExprs(); 7481 } else { // isa<ParenExpr> by assertion at function entrance 7482 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7483 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7484 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7485 exprs = &subExpr; 7486 numExprs = 1; 7487 } 7488 7489 QualType Ty = TInfo->getType(); 7490 assert(Ty->isVectorType() && "Expected vector type"); 7491 7492 SmallVector<Expr *, 8> initExprs; 7493 const VectorType *VTy = Ty->castAs<VectorType>(); 7494 unsigned numElems = VTy->getNumElements(); 7495 7496 // '(...)' form of vector initialization in AltiVec: the number of 7497 // initializers must be one or must match the size of the vector. 7498 // If a single value is specified in the initializer then it will be 7499 // replicated to all the components of the vector 7500 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7501 // The number of initializers must be one or must match the size of the 7502 // vector. If a single value is specified in the initializer then it will 7503 // be replicated to all the components of the vector 7504 if (numExprs == 1) { 7505 QualType ElemTy = VTy->getElementType(); 7506 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7507 if (Literal.isInvalid()) 7508 return ExprError(); 7509 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7510 PrepareScalarCast(Literal, ElemTy)); 7511 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7512 } 7513 else if (numExprs < numElems) { 7514 Diag(E->getExprLoc(), 7515 diag::err_incorrect_number_of_vector_initializers); 7516 return ExprError(); 7517 } 7518 else 7519 initExprs.append(exprs, exprs + numExprs); 7520 } 7521 else { 7522 // For OpenCL, when the number of initializers is a single value, 7523 // it will be replicated to all components of the vector. 7524 if (getLangOpts().OpenCL && 7525 VTy->getVectorKind() == VectorType::GenericVector && 7526 numExprs == 1) { 7527 QualType ElemTy = VTy->getElementType(); 7528 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7529 if (Literal.isInvalid()) 7530 return ExprError(); 7531 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7532 PrepareScalarCast(Literal, ElemTy)); 7533 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7534 } 7535 7536 initExprs.append(exprs, exprs + numExprs); 7537 } 7538 // FIXME: This means that pretty-printing the final AST will produce curly 7539 // braces instead of the original commas. 7540 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7541 initExprs, LiteralRParenLoc); 7542 initE->setType(Ty); 7543 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7544 } 7545 7546 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7547 /// the ParenListExpr into a sequence of comma binary operators. 7548 ExprResult 7549 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7550 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7551 if (!E) 7552 return OrigExpr; 7553 7554 ExprResult Result(E->getExpr(0)); 7555 7556 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7557 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7558 E->getExpr(i)); 7559 7560 if (Result.isInvalid()) return ExprError(); 7561 7562 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7563 } 7564 7565 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7566 SourceLocation R, 7567 MultiExprArg Val) { 7568 return ParenListExpr::Create(Context, L, Val, R); 7569 } 7570 7571 /// Emit a specialized diagnostic when one expression is a null pointer 7572 /// constant and the other is not a pointer. Returns true if a diagnostic is 7573 /// emitted. 7574 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7575 SourceLocation QuestionLoc) { 7576 Expr *NullExpr = LHSExpr; 7577 Expr *NonPointerExpr = RHSExpr; 7578 Expr::NullPointerConstantKind NullKind = 7579 NullExpr->isNullPointerConstant(Context, 7580 Expr::NPC_ValueDependentIsNotNull); 7581 7582 if (NullKind == Expr::NPCK_NotNull) { 7583 NullExpr = RHSExpr; 7584 NonPointerExpr = LHSExpr; 7585 NullKind = 7586 NullExpr->isNullPointerConstant(Context, 7587 Expr::NPC_ValueDependentIsNotNull); 7588 } 7589 7590 if (NullKind == Expr::NPCK_NotNull) 7591 return false; 7592 7593 if (NullKind == Expr::NPCK_ZeroExpression) 7594 return false; 7595 7596 if (NullKind == Expr::NPCK_ZeroLiteral) { 7597 // In this case, check to make sure that we got here from a "NULL" 7598 // string in the source code. 7599 NullExpr = NullExpr->IgnoreParenImpCasts(); 7600 SourceLocation loc = NullExpr->getExprLoc(); 7601 if (!findMacroSpelling(loc, "NULL")) 7602 return false; 7603 } 7604 7605 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7606 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7607 << NonPointerExpr->getType() << DiagType 7608 << NonPointerExpr->getSourceRange(); 7609 return true; 7610 } 7611 7612 /// Return false if the condition expression is valid, true otherwise. 7613 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7614 QualType CondTy = Cond->getType(); 7615 7616 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7617 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7618 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7619 << CondTy << Cond->getSourceRange(); 7620 return true; 7621 } 7622 7623 // C99 6.5.15p2 7624 if (CondTy->isScalarType()) return false; 7625 7626 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7627 << CondTy << Cond->getSourceRange(); 7628 return true; 7629 } 7630 7631 /// Handle when one or both operands are void type. 7632 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7633 ExprResult &RHS) { 7634 Expr *LHSExpr = LHS.get(); 7635 Expr *RHSExpr = RHS.get(); 7636 7637 if (!LHSExpr->getType()->isVoidType()) 7638 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7639 << RHSExpr->getSourceRange(); 7640 if (!RHSExpr->getType()->isVoidType()) 7641 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7642 << LHSExpr->getSourceRange(); 7643 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7644 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7645 return S.Context.VoidTy; 7646 } 7647 7648 /// Return false if the NullExpr can be promoted to PointerTy, 7649 /// true otherwise. 7650 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7651 QualType PointerTy) { 7652 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7653 !NullExpr.get()->isNullPointerConstant(S.Context, 7654 Expr::NPC_ValueDependentIsNull)) 7655 return true; 7656 7657 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7658 return false; 7659 } 7660 7661 /// Checks compatibility between two pointers and return the resulting 7662 /// type. 7663 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7664 ExprResult &RHS, 7665 SourceLocation Loc) { 7666 QualType LHSTy = LHS.get()->getType(); 7667 QualType RHSTy = RHS.get()->getType(); 7668 7669 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7670 // Two identical pointers types are always compatible. 7671 return LHSTy; 7672 } 7673 7674 QualType lhptee, rhptee; 7675 7676 // Get the pointee types. 7677 bool IsBlockPointer = false; 7678 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7679 lhptee = LHSBTy->getPointeeType(); 7680 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7681 IsBlockPointer = true; 7682 } else { 7683 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7684 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7685 } 7686 7687 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7688 // differently qualified versions of compatible types, the result type is 7689 // a pointer to an appropriately qualified version of the composite 7690 // type. 7691 7692 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7693 // clause doesn't make sense for our extensions. E.g. address space 2 should 7694 // be incompatible with address space 3: they may live on different devices or 7695 // anything. 7696 Qualifiers lhQual = lhptee.getQualifiers(); 7697 Qualifiers rhQual = rhptee.getQualifiers(); 7698 7699 LangAS ResultAddrSpace = LangAS::Default; 7700 LangAS LAddrSpace = lhQual.getAddressSpace(); 7701 LangAS RAddrSpace = rhQual.getAddressSpace(); 7702 7703 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7704 // spaces is disallowed. 7705 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7706 ResultAddrSpace = LAddrSpace; 7707 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7708 ResultAddrSpace = RAddrSpace; 7709 else { 7710 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7711 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7712 << RHS.get()->getSourceRange(); 7713 return QualType(); 7714 } 7715 7716 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7717 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7718 lhQual.removeCVRQualifiers(); 7719 rhQual.removeCVRQualifiers(); 7720 7721 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7722 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7723 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7724 // qual types are compatible iff 7725 // * corresponded types are compatible 7726 // * CVR qualifiers are equal 7727 // * address spaces are equal 7728 // Thus for conditional operator we merge CVR and address space unqualified 7729 // pointees and if there is a composite type we return a pointer to it with 7730 // merged qualifiers. 7731 LHSCastKind = 7732 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7733 RHSCastKind = 7734 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7735 lhQual.removeAddressSpace(); 7736 rhQual.removeAddressSpace(); 7737 7738 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7739 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7740 7741 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7742 7743 if (CompositeTy.isNull()) { 7744 // In this situation, we assume void* type. No especially good 7745 // reason, but this is what gcc does, and we do have to pick 7746 // to get a consistent AST. 7747 QualType incompatTy; 7748 incompatTy = S.Context.getPointerType( 7749 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7750 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7751 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7752 7753 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7754 // for casts between types with incompatible address space qualifiers. 7755 // For the following code the compiler produces casts between global and 7756 // local address spaces of the corresponded innermost pointees: 7757 // local int *global *a; 7758 // global int *global *b; 7759 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7760 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7761 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7762 << RHS.get()->getSourceRange(); 7763 7764 return incompatTy; 7765 } 7766 7767 // The pointer types are compatible. 7768 // In case of OpenCL ResultTy should have the address space qualifier 7769 // which is a superset of address spaces of both the 2nd and the 3rd 7770 // operands of the conditional operator. 7771 QualType ResultTy = [&, ResultAddrSpace]() { 7772 if (S.getLangOpts().OpenCL) { 7773 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7774 CompositeQuals.setAddressSpace(ResultAddrSpace); 7775 return S.Context 7776 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7777 .withCVRQualifiers(MergedCVRQual); 7778 } 7779 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7780 }(); 7781 if (IsBlockPointer) 7782 ResultTy = S.Context.getBlockPointerType(ResultTy); 7783 else 7784 ResultTy = S.Context.getPointerType(ResultTy); 7785 7786 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7787 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7788 return ResultTy; 7789 } 7790 7791 /// Return the resulting type when the operands are both block pointers. 7792 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7793 ExprResult &LHS, 7794 ExprResult &RHS, 7795 SourceLocation Loc) { 7796 QualType LHSTy = LHS.get()->getType(); 7797 QualType RHSTy = RHS.get()->getType(); 7798 7799 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7800 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7801 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7802 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7803 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7804 return destType; 7805 } 7806 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7807 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7808 << RHS.get()->getSourceRange(); 7809 return QualType(); 7810 } 7811 7812 // We have 2 block pointer types. 7813 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7814 } 7815 7816 /// Return the resulting type when the operands are both pointers. 7817 static QualType 7818 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7819 ExprResult &RHS, 7820 SourceLocation Loc) { 7821 // get the pointer types 7822 QualType LHSTy = LHS.get()->getType(); 7823 QualType RHSTy = RHS.get()->getType(); 7824 7825 // get the "pointed to" types 7826 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7827 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7828 7829 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7830 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7831 // Figure out necessary qualifiers (C99 6.5.15p6) 7832 QualType destPointee 7833 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7834 QualType destType = S.Context.getPointerType(destPointee); 7835 // Add qualifiers if necessary. 7836 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7837 // Promote to void*. 7838 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7839 return destType; 7840 } 7841 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7842 QualType destPointee 7843 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7844 QualType destType = S.Context.getPointerType(destPointee); 7845 // Add qualifiers if necessary. 7846 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7847 // Promote to void*. 7848 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7849 return destType; 7850 } 7851 7852 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7853 } 7854 7855 /// Return false if the first expression is not an integer and the second 7856 /// expression is not a pointer, true otherwise. 7857 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7858 Expr* PointerExpr, SourceLocation Loc, 7859 bool IsIntFirstExpr) { 7860 if (!PointerExpr->getType()->isPointerType() || 7861 !Int.get()->getType()->isIntegerType()) 7862 return false; 7863 7864 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7865 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7866 7867 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7868 << Expr1->getType() << Expr2->getType() 7869 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7870 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7871 CK_IntegralToPointer); 7872 return true; 7873 } 7874 7875 /// Simple conversion between integer and floating point types. 7876 /// 7877 /// Used when handling the OpenCL conditional operator where the 7878 /// condition is a vector while the other operands are scalar. 7879 /// 7880 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7881 /// types are either integer or floating type. Between the two 7882 /// operands, the type with the higher rank is defined as the "result 7883 /// type". The other operand needs to be promoted to the same type. No 7884 /// other type promotion is allowed. We cannot use 7885 /// UsualArithmeticConversions() for this purpose, since it always 7886 /// promotes promotable types. 7887 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7888 ExprResult &RHS, 7889 SourceLocation QuestionLoc) { 7890 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7891 if (LHS.isInvalid()) 7892 return QualType(); 7893 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7894 if (RHS.isInvalid()) 7895 return QualType(); 7896 7897 // For conversion purposes, we ignore any qualifiers. 7898 // For example, "const float" and "float" are equivalent. 7899 QualType LHSType = 7900 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7901 QualType RHSType = 7902 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7903 7904 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7905 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7906 << LHSType << LHS.get()->getSourceRange(); 7907 return QualType(); 7908 } 7909 7910 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7911 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7912 << RHSType << RHS.get()->getSourceRange(); 7913 return QualType(); 7914 } 7915 7916 // If both types are identical, no conversion is needed. 7917 if (LHSType == RHSType) 7918 return LHSType; 7919 7920 // Now handle "real" floating types (i.e. float, double, long double). 7921 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7922 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7923 /*IsCompAssign = */ false); 7924 7925 // Finally, we have two differing integer types. 7926 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7927 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7928 } 7929 7930 /// Convert scalar operands to a vector that matches the 7931 /// condition in length. 7932 /// 7933 /// Used when handling the OpenCL conditional operator where the 7934 /// condition is a vector while the other operands are scalar. 7935 /// 7936 /// We first compute the "result type" for the scalar operands 7937 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7938 /// into a vector of that type where the length matches the condition 7939 /// vector type. s6.11.6 requires that the element types of the result 7940 /// and the condition must have the same number of bits. 7941 static QualType 7942 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7943 QualType CondTy, SourceLocation QuestionLoc) { 7944 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7945 if (ResTy.isNull()) return QualType(); 7946 7947 const VectorType *CV = CondTy->getAs<VectorType>(); 7948 assert(CV); 7949 7950 // Determine the vector result type 7951 unsigned NumElements = CV->getNumElements(); 7952 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7953 7954 // Ensure that all types have the same number of bits 7955 if (S.Context.getTypeSize(CV->getElementType()) 7956 != S.Context.getTypeSize(ResTy)) { 7957 // Since VectorTy is created internally, it does not pretty print 7958 // with an OpenCL name. Instead, we just print a description. 7959 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7960 SmallString<64> Str; 7961 llvm::raw_svector_ostream OS(Str); 7962 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7963 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7964 << CondTy << OS.str(); 7965 return QualType(); 7966 } 7967 7968 // Convert operands to the vector result type 7969 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7970 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7971 7972 return VectorTy; 7973 } 7974 7975 /// Return false if this is a valid OpenCL condition vector 7976 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7977 SourceLocation QuestionLoc) { 7978 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7979 // integral type. 7980 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7981 assert(CondTy); 7982 QualType EleTy = CondTy->getElementType(); 7983 if (EleTy->isIntegerType()) return false; 7984 7985 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7986 << Cond->getType() << Cond->getSourceRange(); 7987 return true; 7988 } 7989 7990 /// Return false if the vector condition type and the vector 7991 /// result type are compatible. 7992 /// 7993 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7994 /// number of elements, and their element types have the same number 7995 /// of bits. 7996 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7997 SourceLocation QuestionLoc) { 7998 const VectorType *CV = CondTy->getAs<VectorType>(); 7999 const VectorType *RV = VecResTy->getAs<VectorType>(); 8000 assert(CV && RV); 8001 8002 if (CV->getNumElements() != RV->getNumElements()) { 8003 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8004 << CondTy << VecResTy; 8005 return true; 8006 } 8007 8008 QualType CVE = CV->getElementType(); 8009 QualType RVE = RV->getElementType(); 8010 8011 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8012 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8013 << CondTy << VecResTy; 8014 return true; 8015 } 8016 8017 return false; 8018 } 8019 8020 /// Return the resulting type for the conditional operator in 8021 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8022 /// s6.3.i) when the condition is a vector type. 8023 static QualType 8024 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8025 ExprResult &LHS, ExprResult &RHS, 8026 SourceLocation QuestionLoc) { 8027 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8028 if (Cond.isInvalid()) 8029 return QualType(); 8030 QualType CondTy = Cond.get()->getType(); 8031 8032 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8033 return QualType(); 8034 8035 // If either operand is a vector then find the vector type of the 8036 // result as specified in OpenCL v1.1 s6.3.i. 8037 if (LHS.get()->getType()->isVectorType() || 8038 RHS.get()->getType()->isVectorType()) { 8039 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8040 /*isCompAssign*/false, 8041 /*AllowBothBool*/true, 8042 /*AllowBoolConversions*/false); 8043 if (VecResTy.isNull()) return QualType(); 8044 // The result type must match the condition type as specified in 8045 // OpenCL v1.1 s6.11.6. 8046 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8047 return QualType(); 8048 return VecResTy; 8049 } 8050 8051 // Both operands are scalar. 8052 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8053 } 8054 8055 /// Return true if the Expr is block type 8056 static bool checkBlockType(Sema &S, const Expr *E) { 8057 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8058 QualType Ty = CE->getCallee()->getType(); 8059 if (Ty->isBlockPointerType()) { 8060 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8061 return true; 8062 } 8063 } 8064 return false; 8065 } 8066 8067 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8068 /// In that case, LHS = cond. 8069 /// C99 6.5.15 8070 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8071 ExprResult &RHS, ExprValueKind &VK, 8072 ExprObjectKind &OK, 8073 SourceLocation QuestionLoc) { 8074 8075 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8076 if (!LHSResult.isUsable()) return QualType(); 8077 LHS = LHSResult; 8078 8079 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8080 if (!RHSResult.isUsable()) return QualType(); 8081 RHS = RHSResult; 8082 8083 // C++ is sufficiently different to merit its own checker. 8084 if (getLangOpts().CPlusPlus) 8085 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8086 8087 VK = VK_RValue; 8088 OK = OK_Ordinary; 8089 8090 // The OpenCL operator with a vector condition is sufficiently 8091 // different to merit its own checker. 8092 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8093 Cond.get()->getType()->isExtVectorType()) 8094 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8095 8096 // First, check the condition. 8097 Cond = UsualUnaryConversions(Cond.get()); 8098 if (Cond.isInvalid()) 8099 return QualType(); 8100 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8101 return QualType(); 8102 8103 // Now check the two expressions. 8104 if (LHS.get()->getType()->isVectorType() || 8105 RHS.get()->getType()->isVectorType()) 8106 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8107 /*AllowBothBool*/true, 8108 /*AllowBoolConversions*/false); 8109 8110 QualType ResTy = 8111 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8112 if (LHS.isInvalid() || RHS.isInvalid()) 8113 return QualType(); 8114 8115 QualType LHSTy = LHS.get()->getType(); 8116 QualType RHSTy = RHS.get()->getType(); 8117 8118 // Diagnose attempts to convert between __float128 and long double where 8119 // such conversions currently can't be handled. 8120 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8121 Diag(QuestionLoc, 8122 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8123 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8124 return QualType(); 8125 } 8126 8127 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8128 // selection operator (?:). 8129 if (getLangOpts().OpenCL && 8130 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8131 return QualType(); 8132 } 8133 8134 // If both operands have arithmetic type, do the usual arithmetic conversions 8135 // to find a common type: C99 6.5.15p3,5. 8136 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8137 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8138 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8139 8140 return ResTy; 8141 } 8142 8143 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8144 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8145 return LHSTy; 8146 } 8147 8148 // If both operands are the same structure or union type, the result is that 8149 // type. 8150 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8151 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8152 if (LHSRT->getDecl() == RHSRT->getDecl()) 8153 // "If both the operands have structure or union type, the result has 8154 // that type." This implies that CV qualifiers are dropped. 8155 return LHSTy.getUnqualifiedType(); 8156 // FIXME: Type of conditional expression must be complete in C mode. 8157 } 8158 8159 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8160 // The following || allows only one side to be void (a GCC-ism). 8161 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8162 return checkConditionalVoidType(*this, LHS, RHS); 8163 } 8164 8165 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8166 // the type of the other operand." 8167 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8168 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8169 8170 // All objective-c pointer type analysis is done here. 8171 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8172 QuestionLoc); 8173 if (LHS.isInvalid() || RHS.isInvalid()) 8174 return QualType(); 8175 if (!compositeType.isNull()) 8176 return compositeType; 8177 8178 8179 // Handle block pointer types. 8180 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8181 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8182 QuestionLoc); 8183 8184 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8185 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8186 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8187 QuestionLoc); 8188 8189 // GCC compatibility: soften pointer/integer mismatch. Note that 8190 // null pointers have been filtered out by this point. 8191 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8192 /*IsIntFirstExpr=*/true)) 8193 return RHSTy; 8194 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8195 /*IsIntFirstExpr=*/false)) 8196 return LHSTy; 8197 8198 // Allow ?: operations in which both operands have the same 8199 // built-in sizeless type. 8200 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8201 return LHSTy; 8202 8203 // Emit a better diagnostic if one of the expressions is a null pointer 8204 // constant and the other is not a pointer type. In this case, the user most 8205 // likely forgot to take the address of the other expression. 8206 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8207 return QualType(); 8208 8209 // Otherwise, the operands are not compatible. 8210 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8211 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8212 << RHS.get()->getSourceRange(); 8213 return QualType(); 8214 } 8215 8216 /// FindCompositeObjCPointerType - Helper method to find composite type of 8217 /// two objective-c pointer types of the two input expressions. 8218 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8219 SourceLocation QuestionLoc) { 8220 QualType LHSTy = LHS.get()->getType(); 8221 QualType RHSTy = RHS.get()->getType(); 8222 8223 // Handle things like Class and struct objc_class*. Here we case the result 8224 // to the pseudo-builtin, because that will be implicitly cast back to the 8225 // redefinition type if an attempt is made to access its fields. 8226 if (LHSTy->isObjCClassType() && 8227 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8228 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8229 return LHSTy; 8230 } 8231 if (RHSTy->isObjCClassType() && 8232 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8233 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8234 return RHSTy; 8235 } 8236 // And the same for struct objc_object* / id 8237 if (LHSTy->isObjCIdType() && 8238 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8239 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8240 return LHSTy; 8241 } 8242 if (RHSTy->isObjCIdType() && 8243 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8244 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8245 return RHSTy; 8246 } 8247 // And the same for struct objc_selector* / SEL 8248 if (Context.isObjCSelType(LHSTy) && 8249 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8250 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8251 return LHSTy; 8252 } 8253 if (Context.isObjCSelType(RHSTy) && 8254 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8255 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8256 return RHSTy; 8257 } 8258 // Check constraints for Objective-C object pointers types. 8259 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8260 8261 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8262 // Two identical object pointer types are always compatible. 8263 return LHSTy; 8264 } 8265 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8266 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8267 QualType compositeType = LHSTy; 8268 8269 // If both operands are interfaces and either operand can be 8270 // assigned to the other, use that type as the composite 8271 // type. This allows 8272 // xxx ? (A*) a : (B*) b 8273 // where B is a subclass of A. 8274 // 8275 // Additionally, as for assignment, if either type is 'id' 8276 // allow silent coercion. Finally, if the types are 8277 // incompatible then make sure to use 'id' as the composite 8278 // type so the result is acceptable for sending messages to. 8279 8280 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8281 // It could return the composite type. 8282 if (!(compositeType = 8283 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8284 // Nothing more to do. 8285 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8286 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8287 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8288 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8289 } else if ((LHSOPT->isObjCQualifiedIdType() || 8290 RHSOPT->isObjCQualifiedIdType()) && 8291 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8292 true)) { 8293 // Need to handle "id<xx>" explicitly. 8294 // GCC allows qualified id and any Objective-C type to devolve to 8295 // id. Currently localizing to here until clear this should be 8296 // part of ObjCQualifiedIdTypesAreCompatible. 8297 compositeType = Context.getObjCIdType(); 8298 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8299 compositeType = Context.getObjCIdType(); 8300 } else { 8301 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8302 << LHSTy << RHSTy 8303 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8304 QualType incompatTy = Context.getObjCIdType(); 8305 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8306 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8307 return incompatTy; 8308 } 8309 // The object pointer types are compatible. 8310 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8311 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8312 return compositeType; 8313 } 8314 // Check Objective-C object pointer types and 'void *' 8315 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8316 if (getLangOpts().ObjCAutoRefCount) { 8317 // ARC forbids the implicit conversion of object pointers to 'void *', 8318 // so these types are not compatible. 8319 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8320 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8321 LHS = RHS = true; 8322 return QualType(); 8323 } 8324 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8325 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8326 QualType destPointee 8327 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8328 QualType destType = Context.getPointerType(destPointee); 8329 // Add qualifiers if necessary. 8330 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8331 // Promote to void*. 8332 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8333 return destType; 8334 } 8335 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8336 if (getLangOpts().ObjCAutoRefCount) { 8337 // ARC forbids the implicit conversion of object pointers to 'void *', 8338 // so these types are not compatible. 8339 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8340 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8341 LHS = RHS = true; 8342 return QualType(); 8343 } 8344 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8345 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8346 QualType destPointee 8347 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8348 QualType destType = Context.getPointerType(destPointee); 8349 // Add qualifiers if necessary. 8350 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8351 // Promote to void*. 8352 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8353 return destType; 8354 } 8355 return QualType(); 8356 } 8357 8358 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8359 /// ParenRange in parentheses. 8360 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8361 const PartialDiagnostic &Note, 8362 SourceRange ParenRange) { 8363 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8364 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8365 EndLoc.isValid()) { 8366 Self.Diag(Loc, Note) 8367 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8368 << FixItHint::CreateInsertion(EndLoc, ")"); 8369 } else { 8370 // We can't display the parentheses, so just show the bare note. 8371 Self.Diag(Loc, Note) << ParenRange; 8372 } 8373 } 8374 8375 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8376 return BinaryOperator::isAdditiveOp(Opc) || 8377 BinaryOperator::isMultiplicativeOp(Opc) || 8378 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8379 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8380 // not any of the logical operators. Bitwise-xor is commonly used as a 8381 // logical-xor because there is no logical-xor operator. The logical 8382 // operators, including uses of xor, have a high false positive rate for 8383 // precedence warnings. 8384 } 8385 8386 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8387 /// expression, either using a built-in or overloaded operator, 8388 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8389 /// expression. 8390 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8391 Expr **RHSExprs) { 8392 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8393 E = E->IgnoreImpCasts(); 8394 E = E->IgnoreConversionOperator(); 8395 E = E->IgnoreImpCasts(); 8396 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8397 E = MTE->getSubExpr(); 8398 E = E->IgnoreImpCasts(); 8399 } 8400 8401 // Built-in binary operator. 8402 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8403 if (IsArithmeticOp(OP->getOpcode())) { 8404 *Opcode = OP->getOpcode(); 8405 *RHSExprs = OP->getRHS(); 8406 return true; 8407 } 8408 } 8409 8410 // Overloaded operator. 8411 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8412 if (Call->getNumArgs() != 2) 8413 return false; 8414 8415 // Make sure this is really a binary operator that is safe to pass into 8416 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8417 OverloadedOperatorKind OO = Call->getOperator(); 8418 if (OO < OO_Plus || OO > OO_Arrow || 8419 OO == OO_PlusPlus || OO == OO_MinusMinus) 8420 return false; 8421 8422 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8423 if (IsArithmeticOp(OpKind)) { 8424 *Opcode = OpKind; 8425 *RHSExprs = Call->getArg(1); 8426 return true; 8427 } 8428 } 8429 8430 return false; 8431 } 8432 8433 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8434 /// or is a logical expression such as (x==y) which has int type, but is 8435 /// commonly interpreted as boolean. 8436 static bool ExprLooksBoolean(Expr *E) { 8437 E = E->IgnoreParenImpCasts(); 8438 8439 if (E->getType()->isBooleanType()) 8440 return true; 8441 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8442 return OP->isComparisonOp() || OP->isLogicalOp(); 8443 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8444 return OP->getOpcode() == UO_LNot; 8445 if (E->getType()->isPointerType()) 8446 return true; 8447 // FIXME: What about overloaded operator calls returning "unspecified boolean 8448 // type"s (commonly pointer-to-members)? 8449 8450 return false; 8451 } 8452 8453 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8454 /// and binary operator are mixed in a way that suggests the programmer assumed 8455 /// the conditional operator has higher precedence, for example: 8456 /// "int x = a + someBinaryCondition ? 1 : 2". 8457 static void DiagnoseConditionalPrecedence(Sema &Self, 8458 SourceLocation OpLoc, 8459 Expr *Condition, 8460 Expr *LHSExpr, 8461 Expr *RHSExpr) { 8462 BinaryOperatorKind CondOpcode; 8463 Expr *CondRHS; 8464 8465 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8466 return; 8467 if (!ExprLooksBoolean(CondRHS)) 8468 return; 8469 8470 // The condition is an arithmetic binary expression, with a right- 8471 // hand side that looks boolean, so warn. 8472 8473 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8474 ? diag::warn_precedence_bitwise_conditional 8475 : diag::warn_precedence_conditional; 8476 8477 Self.Diag(OpLoc, DiagID) 8478 << Condition->getSourceRange() 8479 << BinaryOperator::getOpcodeStr(CondOpcode); 8480 8481 SuggestParentheses( 8482 Self, OpLoc, 8483 Self.PDiag(diag::note_precedence_silence) 8484 << BinaryOperator::getOpcodeStr(CondOpcode), 8485 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8486 8487 SuggestParentheses(Self, OpLoc, 8488 Self.PDiag(diag::note_precedence_conditional_first), 8489 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8490 } 8491 8492 /// Compute the nullability of a conditional expression. 8493 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8494 QualType LHSTy, QualType RHSTy, 8495 ASTContext &Ctx) { 8496 if (!ResTy->isAnyPointerType()) 8497 return ResTy; 8498 8499 auto GetNullability = [&Ctx](QualType Ty) { 8500 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8501 if (Kind) 8502 return *Kind; 8503 return NullabilityKind::Unspecified; 8504 }; 8505 8506 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8507 NullabilityKind MergedKind; 8508 8509 // Compute nullability of a binary conditional expression. 8510 if (IsBin) { 8511 if (LHSKind == NullabilityKind::NonNull) 8512 MergedKind = NullabilityKind::NonNull; 8513 else 8514 MergedKind = RHSKind; 8515 // Compute nullability of a normal conditional expression. 8516 } else { 8517 if (LHSKind == NullabilityKind::Nullable || 8518 RHSKind == NullabilityKind::Nullable) 8519 MergedKind = NullabilityKind::Nullable; 8520 else if (LHSKind == NullabilityKind::NonNull) 8521 MergedKind = RHSKind; 8522 else if (RHSKind == NullabilityKind::NonNull) 8523 MergedKind = LHSKind; 8524 else 8525 MergedKind = NullabilityKind::Unspecified; 8526 } 8527 8528 // Return if ResTy already has the correct nullability. 8529 if (GetNullability(ResTy) == MergedKind) 8530 return ResTy; 8531 8532 // Strip all nullability from ResTy. 8533 while (ResTy->getNullability(Ctx)) 8534 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8535 8536 // Create a new AttributedType with the new nullability kind. 8537 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8538 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8539 } 8540 8541 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8542 /// in the case of a the GNU conditional expr extension. 8543 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8544 SourceLocation ColonLoc, 8545 Expr *CondExpr, Expr *LHSExpr, 8546 Expr *RHSExpr) { 8547 if (!getLangOpts().CPlusPlus) { 8548 // C cannot handle TypoExpr nodes in the condition because it 8549 // doesn't handle dependent types properly, so make sure any TypoExprs have 8550 // been dealt with before checking the operands. 8551 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8552 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8553 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8554 8555 if (!CondResult.isUsable()) 8556 return ExprError(); 8557 8558 if (LHSExpr) { 8559 if (!LHSResult.isUsable()) 8560 return ExprError(); 8561 } 8562 8563 if (!RHSResult.isUsable()) 8564 return ExprError(); 8565 8566 CondExpr = CondResult.get(); 8567 LHSExpr = LHSResult.get(); 8568 RHSExpr = RHSResult.get(); 8569 } 8570 8571 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8572 // was the condition. 8573 OpaqueValueExpr *opaqueValue = nullptr; 8574 Expr *commonExpr = nullptr; 8575 if (!LHSExpr) { 8576 commonExpr = CondExpr; 8577 // Lower out placeholder types first. This is important so that we don't 8578 // try to capture a placeholder. This happens in few cases in C++; such 8579 // as Objective-C++'s dictionary subscripting syntax. 8580 if (commonExpr->hasPlaceholderType()) { 8581 ExprResult result = CheckPlaceholderExpr(commonExpr); 8582 if (!result.isUsable()) return ExprError(); 8583 commonExpr = result.get(); 8584 } 8585 // We usually want to apply unary conversions *before* saving, except 8586 // in the special case of a C++ l-value conditional. 8587 if (!(getLangOpts().CPlusPlus 8588 && !commonExpr->isTypeDependent() 8589 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8590 && commonExpr->isGLValue() 8591 && commonExpr->isOrdinaryOrBitFieldObject() 8592 && RHSExpr->isOrdinaryOrBitFieldObject() 8593 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8594 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8595 if (commonRes.isInvalid()) 8596 return ExprError(); 8597 commonExpr = commonRes.get(); 8598 } 8599 8600 // If the common expression is a class or array prvalue, materialize it 8601 // so that we can safely refer to it multiple times. 8602 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8603 commonExpr->getType()->isArrayType())) { 8604 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8605 if (MatExpr.isInvalid()) 8606 return ExprError(); 8607 commonExpr = MatExpr.get(); 8608 } 8609 8610 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8611 commonExpr->getType(), 8612 commonExpr->getValueKind(), 8613 commonExpr->getObjectKind(), 8614 commonExpr); 8615 LHSExpr = CondExpr = opaqueValue; 8616 } 8617 8618 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8619 ExprValueKind VK = VK_RValue; 8620 ExprObjectKind OK = OK_Ordinary; 8621 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8622 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8623 VK, OK, QuestionLoc); 8624 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8625 RHS.isInvalid()) 8626 return ExprError(); 8627 8628 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8629 RHS.get()); 8630 8631 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8632 8633 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8634 Context); 8635 8636 if (!commonExpr) 8637 return new (Context) 8638 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8639 RHS.get(), result, VK, OK); 8640 8641 return new (Context) BinaryConditionalOperator( 8642 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8643 ColonLoc, result, VK, OK); 8644 } 8645 8646 // Check if we have a conversion between incompatible cmse function pointer 8647 // types, that is, a conversion between a function pointer with the 8648 // cmse_nonsecure_call attribute and one without. 8649 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8650 QualType ToType) { 8651 if (const auto *ToFn = 8652 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8653 if (const auto *FromFn = 8654 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8655 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8656 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8657 8658 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8659 } 8660 } 8661 return false; 8662 } 8663 8664 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8665 // being closely modeled after the C99 spec:-). The odd characteristic of this 8666 // routine is it effectively iqnores the qualifiers on the top level pointee. 8667 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8668 // FIXME: add a couple examples in this comment. 8669 static Sema::AssignConvertType 8670 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8671 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8672 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8673 8674 // get the "pointed to" type (ignoring qualifiers at the top level) 8675 const Type *lhptee, *rhptee; 8676 Qualifiers lhq, rhq; 8677 std::tie(lhptee, lhq) = 8678 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8679 std::tie(rhptee, rhq) = 8680 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8681 8682 Sema::AssignConvertType ConvTy = Sema::Compatible; 8683 8684 // C99 6.5.16.1p1: This following citation is common to constraints 8685 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8686 // qualifiers of the type *pointed to* by the right; 8687 8688 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8689 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8690 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8691 // Ignore lifetime for further calculation. 8692 lhq.removeObjCLifetime(); 8693 rhq.removeObjCLifetime(); 8694 } 8695 8696 if (!lhq.compatiblyIncludes(rhq)) { 8697 // Treat address-space mismatches as fatal. 8698 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8699 return Sema::IncompatiblePointerDiscardsQualifiers; 8700 8701 // It's okay to add or remove GC or lifetime qualifiers when converting to 8702 // and from void*. 8703 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8704 .compatiblyIncludes( 8705 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8706 && (lhptee->isVoidType() || rhptee->isVoidType())) 8707 ; // keep old 8708 8709 // Treat lifetime mismatches as fatal. 8710 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8711 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8712 8713 // For GCC/MS compatibility, other qualifier mismatches are treated 8714 // as still compatible in C. 8715 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8716 } 8717 8718 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8719 // incomplete type and the other is a pointer to a qualified or unqualified 8720 // version of void... 8721 if (lhptee->isVoidType()) { 8722 if (rhptee->isIncompleteOrObjectType()) 8723 return ConvTy; 8724 8725 // As an extension, we allow cast to/from void* to function pointer. 8726 assert(rhptee->isFunctionType()); 8727 return Sema::FunctionVoidPointer; 8728 } 8729 8730 if (rhptee->isVoidType()) { 8731 if (lhptee->isIncompleteOrObjectType()) 8732 return ConvTy; 8733 8734 // As an extension, we allow cast to/from void* to function pointer. 8735 assert(lhptee->isFunctionType()); 8736 return Sema::FunctionVoidPointer; 8737 } 8738 8739 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8740 // unqualified versions of compatible types, ... 8741 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8742 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8743 // Check if the pointee types are compatible ignoring the sign. 8744 // We explicitly check for char so that we catch "char" vs 8745 // "unsigned char" on systems where "char" is unsigned. 8746 if (lhptee->isCharType()) 8747 ltrans = S.Context.UnsignedCharTy; 8748 else if (lhptee->hasSignedIntegerRepresentation()) 8749 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8750 8751 if (rhptee->isCharType()) 8752 rtrans = S.Context.UnsignedCharTy; 8753 else if (rhptee->hasSignedIntegerRepresentation()) 8754 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8755 8756 if (ltrans == rtrans) { 8757 // Types are compatible ignoring the sign. Qualifier incompatibility 8758 // takes priority over sign incompatibility because the sign 8759 // warning can be disabled. 8760 if (ConvTy != Sema::Compatible) 8761 return ConvTy; 8762 8763 return Sema::IncompatiblePointerSign; 8764 } 8765 8766 // If we are a multi-level pointer, it's possible that our issue is simply 8767 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8768 // the eventual target type is the same and the pointers have the same 8769 // level of indirection, this must be the issue. 8770 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8771 do { 8772 std::tie(lhptee, lhq) = 8773 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8774 std::tie(rhptee, rhq) = 8775 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8776 8777 // Inconsistent address spaces at this point is invalid, even if the 8778 // address spaces would be compatible. 8779 // FIXME: This doesn't catch address space mismatches for pointers of 8780 // different nesting levels, like: 8781 // __local int *** a; 8782 // int ** b = a; 8783 // It's not clear how to actually determine when such pointers are 8784 // invalidly incompatible. 8785 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8786 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8787 8788 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8789 8790 if (lhptee == rhptee) 8791 return Sema::IncompatibleNestedPointerQualifiers; 8792 } 8793 8794 // General pointer incompatibility takes priority over qualifiers. 8795 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8796 return Sema::IncompatibleFunctionPointer; 8797 return Sema::IncompatiblePointer; 8798 } 8799 if (!S.getLangOpts().CPlusPlus && 8800 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8801 return Sema::IncompatibleFunctionPointer; 8802 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8803 return Sema::IncompatibleFunctionPointer; 8804 return ConvTy; 8805 } 8806 8807 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8808 /// block pointer types are compatible or whether a block and normal pointer 8809 /// are compatible. It is more restrict than comparing two function pointer 8810 // types. 8811 static Sema::AssignConvertType 8812 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8813 QualType RHSType) { 8814 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8815 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8816 8817 QualType lhptee, rhptee; 8818 8819 // get the "pointed to" type (ignoring qualifiers at the top level) 8820 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8821 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8822 8823 // In C++, the types have to match exactly. 8824 if (S.getLangOpts().CPlusPlus) 8825 return Sema::IncompatibleBlockPointer; 8826 8827 Sema::AssignConvertType ConvTy = Sema::Compatible; 8828 8829 // For blocks we enforce that qualifiers are identical. 8830 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8831 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8832 if (S.getLangOpts().OpenCL) { 8833 LQuals.removeAddressSpace(); 8834 RQuals.removeAddressSpace(); 8835 } 8836 if (LQuals != RQuals) 8837 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8838 8839 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8840 // assignment. 8841 // The current behavior is similar to C++ lambdas. A block might be 8842 // assigned to a variable iff its return type and parameters are compatible 8843 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8844 // an assignment. Presumably it should behave in way that a function pointer 8845 // assignment does in C, so for each parameter and return type: 8846 // * CVR and address space of LHS should be a superset of CVR and address 8847 // space of RHS. 8848 // * unqualified types should be compatible. 8849 if (S.getLangOpts().OpenCL) { 8850 if (!S.Context.typesAreBlockPointerCompatible( 8851 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8852 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8853 return Sema::IncompatibleBlockPointer; 8854 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8855 return Sema::IncompatibleBlockPointer; 8856 8857 return ConvTy; 8858 } 8859 8860 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8861 /// for assignment compatibility. 8862 static Sema::AssignConvertType 8863 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8864 QualType RHSType) { 8865 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8866 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8867 8868 if (LHSType->isObjCBuiltinType()) { 8869 // Class is not compatible with ObjC object pointers. 8870 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8871 !RHSType->isObjCQualifiedClassType()) 8872 return Sema::IncompatiblePointer; 8873 return Sema::Compatible; 8874 } 8875 if (RHSType->isObjCBuiltinType()) { 8876 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8877 !LHSType->isObjCQualifiedClassType()) 8878 return Sema::IncompatiblePointer; 8879 return Sema::Compatible; 8880 } 8881 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8882 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8883 8884 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8885 // make an exception for id<P> 8886 !LHSType->isObjCQualifiedIdType()) 8887 return Sema::CompatiblePointerDiscardsQualifiers; 8888 8889 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8890 return Sema::Compatible; 8891 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8892 return Sema::IncompatibleObjCQualifiedId; 8893 return Sema::IncompatiblePointer; 8894 } 8895 8896 Sema::AssignConvertType 8897 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8898 QualType LHSType, QualType RHSType) { 8899 // Fake up an opaque expression. We don't actually care about what 8900 // cast operations are required, so if CheckAssignmentConstraints 8901 // adds casts to this they'll be wasted, but fortunately that doesn't 8902 // usually happen on valid code. 8903 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8904 ExprResult RHSPtr = &RHSExpr; 8905 CastKind K; 8906 8907 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8908 } 8909 8910 /// This helper function returns true if QT is a vector type that has element 8911 /// type ElementType. 8912 static bool isVector(QualType QT, QualType ElementType) { 8913 if (const VectorType *VT = QT->getAs<VectorType>()) 8914 return VT->getElementType().getCanonicalType() == ElementType; 8915 return false; 8916 } 8917 8918 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8919 /// has code to accommodate several GCC extensions when type checking 8920 /// pointers. Here are some objectionable examples that GCC considers warnings: 8921 /// 8922 /// int a, *pint; 8923 /// short *pshort; 8924 /// struct foo *pfoo; 8925 /// 8926 /// pint = pshort; // warning: assignment from incompatible pointer type 8927 /// a = pint; // warning: assignment makes integer from pointer without a cast 8928 /// pint = a; // warning: assignment makes pointer from integer without a cast 8929 /// pint = pfoo; // warning: assignment from incompatible pointer type 8930 /// 8931 /// As a result, the code for dealing with pointers is more complex than the 8932 /// C99 spec dictates. 8933 /// 8934 /// Sets 'Kind' for any result kind except Incompatible. 8935 Sema::AssignConvertType 8936 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8937 CastKind &Kind, bool ConvertRHS) { 8938 QualType RHSType = RHS.get()->getType(); 8939 QualType OrigLHSType = LHSType; 8940 8941 // Get canonical types. We're not formatting these types, just comparing 8942 // them. 8943 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8944 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8945 8946 // Common case: no conversion required. 8947 if (LHSType == RHSType) { 8948 Kind = CK_NoOp; 8949 return Compatible; 8950 } 8951 8952 // If we have an atomic type, try a non-atomic assignment, then just add an 8953 // atomic qualification step. 8954 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8955 Sema::AssignConvertType result = 8956 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8957 if (result != Compatible) 8958 return result; 8959 if (Kind != CK_NoOp && ConvertRHS) 8960 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8961 Kind = CK_NonAtomicToAtomic; 8962 return Compatible; 8963 } 8964 8965 // If the left-hand side is a reference type, then we are in a 8966 // (rare!) case where we've allowed the use of references in C, 8967 // e.g., as a parameter type in a built-in function. In this case, 8968 // just make sure that the type referenced is compatible with the 8969 // right-hand side type. The caller is responsible for adjusting 8970 // LHSType so that the resulting expression does not have reference 8971 // type. 8972 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8973 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8974 Kind = CK_LValueBitCast; 8975 return Compatible; 8976 } 8977 return Incompatible; 8978 } 8979 8980 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8981 // to the same ExtVector type. 8982 if (LHSType->isExtVectorType()) { 8983 if (RHSType->isExtVectorType()) 8984 return Incompatible; 8985 if (RHSType->isArithmeticType()) { 8986 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8987 if (ConvertRHS) 8988 RHS = prepareVectorSplat(LHSType, RHS.get()); 8989 Kind = CK_VectorSplat; 8990 return Compatible; 8991 } 8992 } 8993 8994 // Conversions to or from vector type. 8995 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8996 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8997 // Allow assignments of an AltiVec vector type to an equivalent GCC 8998 // vector type and vice versa 8999 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9000 Kind = CK_BitCast; 9001 return Compatible; 9002 } 9003 9004 // If we are allowing lax vector conversions, and LHS and RHS are both 9005 // vectors, the total size only needs to be the same. This is a bitcast; 9006 // no bits are changed but the result type is different. 9007 if (isLaxVectorConversion(RHSType, LHSType)) { 9008 Kind = CK_BitCast; 9009 return IncompatibleVectors; 9010 } 9011 } 9012 9013 // When the RHS comes from another lax conversion (e.g. binops between 9014 // scalars and vectors) the result is canonicalized as a vector. When the 9015 // LHS is also a vector, the lax is allowed by the condition above. Handle 9016 // the case where LHS is a scalar. 9017 if (LHSType->isScalarType()) { 9018 const VectorType *VecType = RHSType->getAs<VectorType>(); 9019 if (VecType && VecType->getNumElements() == 1 && 9020 isLaxVectorConversion(RHSType, LHSType)) { 9021 ExprResult *VecExpr = &RHS; 9022 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9023 Kind = CK_BitCast; 9024 return Compatible; 9025 } 9026 } 9027 9028 return Incompatible; 9029 } 9030 9031 // Diagnose attempts to convert between __float128 and long double where 9032 // such conversions currently can't be handled. 9033 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9034 return Incompatible; 9035 9036 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9037 // discards the imaginary part. 9038 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9039 !LHSType->getAs<ComplexType>()) 9040 return Incompatible; 9041 9042 // Arithmetic conversions. 9043 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9044 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9045 if (ConvertRHS) 9046 Kind = PrepareScalarCast(RHS, LHSType); 9047 return Compatible; 9048 } 9049 9050 // Conversions to normal pointers. 9051 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9052 // U* -> T* 9053 if (isa<PointerType>(RHSType)) { 9054 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9055 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9056 if (AddrSpaceL != AddrSpaceR) 9057 Kind = CK_AddressSpaceConversion; 9058 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9059 Kind = CK_NoOp; 9060 else 9061 Kind = CK_BitCast; 9062 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9063 } 9064 9065 // int -> T* 9066 if (RHSType->isIntegerType()) { 9067 Kind = CK_IntegralToPointer; // FIXME: null? 9068 return IntToPointer; 9069 } 9070 9071 // C pointers are not compatible with ObjC object pointers, 9072 // with two exceptions: 9073 if (isa<ObjCObjectPointerType>(RHSType)) { 9074 // - conversions to void* 9075 if (LHSPointer->getPointeeType()->isVoidType()) { 9076 Kind = CK_BitCast; 9077 return Compatible; 9078 } 9079 9080 // - conversions from 'Class' to the redefinition type 9081 if (RHSType->isObjCClassType() && 9082 Context.hasSameType(LHSType, 9083 Context.getObjCClassRedefinitionType())) { 9084 Kind = CK_BitCast; 9085 return Compatible; 9086 } 9087 9088 Kind = CK_BitCast; 9089 return IncompatiblePointer; 9090 } 9091 9092 // U^ -> void* 9093 if (RHSType->getAs<BlockPointerType>()) { 9094 if (LHSPointer->getPointeeType()->isVoidType()) { 9095 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9096 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9097 ->getPointeeType() 9098 .getAddressSpace(); 9099 Kind = 9100 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9101 return Compatible; 9102 } 9103 } 9104 9105 return Incompatible; 9106 } 9107 9108 // Conversions to block pointers. 9109 if (isa<BlockPointerType>(LHSType)) { 9110 // U^ -> T^ 9111 if (RHSType->isBlockPointerType()) { 9112 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9113 ->getPointeeType() 9114 .getAddressSpace(); 9115 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9116 ->getPointeeType() 9117 .getAddressSpace(); 9118 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9119 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9120 } 9121 9122 // int or null -> T^ 9123 if (RHSType->isIntegerType()) { 9124 Kind = CK_IntegralToPointer; // FIXME: null 9125 return IntToBlockPointer; 9126 } 9127 9128 // id -> T^ 9129 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9130 Kind = CK_AnyPointerToBlockPointerCast; 9131 return Compatible; 9132 } 9133 9134 // void* -> T^ 9135 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9136 if (RHSPT->getPointeeType()->isVoidType()) { 9137 Kind = CK_AnyPointerToBlockPointerCast; 9138 return Compatible; 9139 } 9140 9141 return Incompatible; 9142 } 9143 9144 // Conversions to Objective-C pointers. 9145 if (isa<ObjCObjectPointerType>(LHSType)) { 9146 // A* -> B* 9147 if (RHSType->isObjCObjectPointerType()) { 9148 Kind = CK_BitCast; 9149 Sema::AssignConvertType result = 9150 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9151 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9152 result == Compatible && 9153 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9154 result = IncompatibleObjCWeakRef; 9155 return result; 9156 } 9157 9158 // int or null -> A* 9159 if (RHSType->isIntegerType()) { 9160 Kind = CK_IntegralToPointer; // FIXME: null 9161 return IntToPointer; 9162 } 9163 9164 // In general, C pointers are not compatible with ObjC object pointers, 9165 // with two exceptions: 9166 if (isa<PointerType>(RHSType)) { 9167 Kind = CK_CPointerToObjCPointerCast; 9168 9169 // - conversions from 'void*' 9170 if (RHSType->isVoidPointerType()) { 9171 return Compatible; 9172 } 9173 9174 // - conversions to 'Class' from its redefinition type 9175 if (LHSType->isObjCClassType() && 9176 Context.hasSameType(RHSType, 9177 Context.getObjCClassRedefinitionType())) { 9178 return Compatible; 9179 } 9180 9181 return IncompatiblePointer; 9182 } 9183 9184 // Only under strict condition T^ is compatible with an Objective-C pointer. 9185 if (RHSType->isBlockPointerType() && 9186 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9187 if (ConvertRHS) 9188 maybeExtendBlockObject(RHS); 9189 Kind = CK_BlockPointerToObjCPointerCast; 9190 return Compatible; 9191 } 9192 9193 return Incompatible; 9194 } 9195 9196 // Conversions from pointers that are not covered by the above. 9197 if (isa<PointerType>(RHSType)) { 9198 // T* -> _Bool 9199 if (LHSType == Context.BoolTy) { 9200 Kind = CK_PointerToBoolean; 9201 return Compatible; 9202 } 9203 9204 // T* -> int 9205 if (LHSType->isIntegerType()) { 9206 Kind = CK_PointerToIntegral; 9207 return PointerToInt; 9208 } 9209 9210 return Incompatible; 9211 } 9212 9213 // Conversions from Objective-C pointers that are not covered by the above. 9214 if (isa<ObjCObjectPointerType>(RHSType)) { 9215 // T* -> _Bool 9216 if (LHSType == Context.BoolTy) { 9217 Kind = CK_PointerToBoolean; 9218 return Compatible; 9219 } 9220 9221 // T* -> int 9222 if (LHSType->isIntegerType()) { 9223 Kind = CK_PointerToIntegral; 9224 return PointerToInt; 9225 } 9226 9227 return Incompatible; 9228 } 9229 9230 // struct A -> struct B 9231 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9232 if (Context.typesAreCompatible(LHSType, RHSType)) { 9233 Kind = CK_NoOp; 9234 return Compatible; 9235 } 9236 } 9237 9238 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9239 Kind = CK_IntToOCLSampler; 9240 return Compatible; 9241 } 9242 9243 return Incompatible; 9244 } 9245 9246 /// Constructs a transparent union from an expression that is 9247 /// used to initialize the transparent union. 9248 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9249 ExprResult &EResult, QualType UnionType, 9250 FieldDecl *Field) { 9251 // Build an initializer list that designates the appropriate member 9252 // of the transparent union. 9253 Expr *E = EResult.get(); 9254 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9255 E, SourceLocation()); 9256 Initializer->setType(UnionType); 9257 Initializer->setInitializedFieldInUnion(Field); 9258 9259 // Build a compound literal constructing a value of the transparent 9260 // union type from this initializer list. 9261 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9262 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9263 VK_RValue, Initializer, false); 9264 } 9265 9266 Sema::AssignConvertType 9267 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9268 ExprResult &RHS) { 9269 QualType RHSType = RHS.get()->getType(); 9270 9271 // If the ArgType is a Union type, we want to handle a potential 9272 // transparent_union GCC extension. 9273 const RecordType *UT = ArgType->getAsUnionType(); 9274 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9275 return Incompatible; 9276 9277 // The field to initialize within the transparent union. 9278 RecordDecl *UD = UT->getDecl(); 9279 FieldDecl *InitField = nullptr; 9280 // It's compatible if the expression matches any of the fields. 9281 for (auto *it : UD->fields()) { 9282 if (it->getType()->isPointerType()) { 9283 // If the transparent union contains a pointer type, we allow: 9284 // 1) void pointer 9285 // 2) null pointer constant 9286 if (RHSType->isPointerType()) 9287 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9288 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9289 InitField = it; 9290 break; 9291 } 9292 9293 if (RHS.get()->isNullPointerConstant(Context, 9294 Expr::NPC_ValueDependentIsNull)) { 9295 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9296 CK_NullToPointer); 9297 InitField = it; 9298 break; 9299 } 9300 } 9301 9302 CastKind Kind; 9303 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9304 == Compatible) { 9305 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9306 InitField = it; 9307 break; 9308 } 9309 } 9310 9311 if (!InitField) 9312 return Incompatible; 9313 9314 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9315 return Compatible; 9316 } 9317 9318 Sema::AssignConvertType 9319 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9320 bool Diagnose, 9321 bool DiagnoseCFAudited, 9322 bool ConvertRHS) { 9323 // We need to be able to tell the caller whether we diagnosed a problem, if 9324 // they ask us to issue diagnostics. 9325 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9326 9327 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9328 // we can't avoid *all* modifications at the moment, so we need some somewhere 9329 // to put the updated value. 9330 ExprResult LocalRHS = CallerRHS; 9331 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9332 9333 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9334 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9335 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9336 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9337 Diag(RHS.get()->getExprLoc(), 9338 diag::warn_noderef_to_dereferenceable_pointer) 9339 << RHS.get()->getSourceRange(); 9340 } 9341 } 9342 } 9343 9344 if (getLangOpts().CPlusPlus) { 9345 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9346 // C++ 5.17p3: If the left operand is not of class type, the 9347 // expression is implicitly converted (C++ 4) to the 9348 // cv-unqualified type of the left operand. 9349 QualType RHSType = RHS.get()->getType(); 9350 if (Diagnose) { 9351 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9352 AA_Assigning); 9353 } else { 9354 ImplicitConversionSequence ICS = 9355 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9356 /*SuppressUserConversions=*/false, 9357 AllowedExplicit::None, 9358 /*InOverloadResolution=*/false, 9359 /*CStyle=*/false, 9360 /*AllowObjCWritebackConversion=*/false); 9361 if (ICS.isFailure()) 9362 return Incompatible; 9363 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9364 ICS, AA_Assigning); 9365 } 9366 if (RHS.isInvalid()) 9367 return Incompatible; 9368 Sema::AssignConvertType result = Compatible; 9369 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9370 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9371 result = IncompatibleObjCWeakRef; 9372 return result; 9373 } 9374 9375 // FIXME: Currently, we fall through and treat C++ classes like C 9376 // structures. 9377 // FIXME: We also fall through for atomics; not sure what should 9378 // happen there, though. 9379 } else if (RHS.get()->getType() == Context.OverloadTy) { 9380 // As a set of extensions to C, we support overloading on functions. These 9381 // functions need to be resolved here. 9382 DeclAccessPair DAP; 9383 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9384 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9385 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9386 else 9387 return Incompatible; 9388 } 9389 9390 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9391 // a null pointer constant. 9392 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9393 LHSType->isBlockPointerType()) && 9394 RHS.get()->isNullPointerConstant(Context, 9395 Expr::NPC_ValueDependentIsNull)) { 9396 if (Diagnose || ConvertRHS) { 9397 CastKind Kind; 9398 CXXCastPath Path; 9399 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9400 /*IgnoreBaseAccess=*/false, Diagnose); 9401 if (ConvertRHS) 9402 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9403 } 9404 return Compatible; 9405 } 9406 9407 // OpenCL queue_t type assignment. 9408 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9409 Context, Expr::NPC_ValueDependentIsNull)) { 9410 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9411 return Compatible; 9412 } 9413 9414 // This check seems unnatural, however it is necessary to ensure the proper 9415 // conversion of functions/arrays. If the conversion were done for all 9416 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9417 // expressions that suppress this implicit conversion (&, sizeof). 9418 // 9419 // Suppress this for references: C++ 8.5.3p5. 9420 if (!LHSType->isReferenceType()) { 9421 // FIXME: We potentially allocate here even if ConvertRHS is false. 9422 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9423 if (RHS.isInvalid()) 9424 return Incompatible; 9425 } 9426 CastKind Kind; 9427 Sema::AssignConvertType result = 9428 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9429 9430 // C99 6.5.16.1p2: The value of the right operand is converted to the 9431 // type of the assignment expression. 9432 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9433 // so that we can use references in built-in functions even in C. 9434 // The getNonReferenceType() call makes sure that the resulting expression 9435 // does not have reference type. 9436 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9437 QualType Ty = LHSType.getNonLValueExprType(Context); 9438 Expr *E = RHS.get(); 9439 9440 // Check for various Objective-C errors. If we are not reporting 9441 // diagnostics and just checking for errors, e.g., during overload 9442 // resolution, return Incompatible to indicate the failure. 9443 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9444 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9445 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9446 if (!Diagnose) 9447 return Incompatible; 9448 } 9449 if (getLangOpts().ObjC && 9450 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9451 E->getType(), E, Diagnose) || 9452 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9453 if (!Diagnose) 9454 return Incompatible; 9455 // Replace the expression with a corrected version and continue so we 9456 // can find further errors. 9457 RHS = E; 9458 return Compatible; 9459 } 9460 9461 if (ConvertRHS) 9462 RHS = ImpCastExprToType(E, Ty, Kind); 9463 } 9464 9465 return result; 9466 } 9467 9468 namespace { 9469 /// The original operand to an operator, prior to the application of the usual 9470 /// arithmetic conversions and converting the arguments of a builtin operator 9471 /// candidate. 9472 struct OriginalOperand { 9473 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9474 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9475 Op = MTE->getSubExpr(); 9476 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9477 Op = BTE->getSubExpr(); 9478 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9479 Orig = ICE->getSubExprAsWritten(); 9480 Conversion = ICE->getConversionFunction(); 9481 } 9482 } 9483 9484 QualType getType() const { return Orig->getType(); } 9485 9486 Expr *Orig; 9487 NamedDecl *Conversion; 9488 }; 9489 } 9490 9491 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9492 ExprResult &RHS) { 9493 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9494 9495 Diag(Loc, diag::err_typecheck_invalid_operands) 9496 << OrigLHS.getType() << OrigRHS.getType() 9497 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9498 9499 // If a user-defined conversion was applied to either of the operands prior 9500 // to applying the built-in operator rules, tell the user about it. 9501 if (OrigLHS.Conversion) { 9502 Diag(OrigLHS.Conversion->getLocation(), 9503 diag::note_typecheck_invalid_operands_converted) 9504 << 0 << LHS.get()->getType(); 9505 } 9506 if (OrigRHS.Conversion) { 9507 Diag(OrigRHS.Conversion->getLocation(), 9508 diag::note_typecheck_invalid_operands_converted) 9509 << 1 << RHS.get()->getType(); 9510 } 9511 9512 return QualType(); 9513 } 9514 9515 // Diagnose cases where a scalar was implicitly converted to a vector and 9516 // diagnose the underlying types. Otherwise, diagnose the error 9517 // as invalid vector logical operands for non-C++ cases. 9518 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9519 ExprResult &RHS) { 9520 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9521 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9522 9523 bool LHSNatVec = LHSType->isVectorType(); 9524 bool RHSNatVec = RHSType->isVectorType(); 9525 9526 if (!(LHSNatVec && RHSNatVec)) { 9527 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9528 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9529 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9530 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9531 << Vector->getSourceRange(); 9532 return QualType(); 9533 } 9534 9535 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9536 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9537 << RHS.get()->getSourceRange(); 9538 9539 return QualType(); 9540 } 9541 9542 /// Try to convert a value of non-vector type to a vector type by converting 9543 /// the type to the element type of the vector and then performing a splat. 9544 /// If the language is OpenCL, we only use conversions that promote scalar 9545 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9546 /// for float->int. 9547 /// 9548 /// OpenCL V2.0 6.2.6.p2: 9549 /// An error shall occur if any scalar operand type has greater rank 9550 /// than the type of the vector element. 9551 /// 9552 /// \param scalar - if non-null, actually perform the conversions 9553 /// \return true if the operation fails (but without diagnosing the failure) 9554 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9555 QualType scalarTy, 9556 QualType vectorEltTy, 9557 QualType vectorTy, 9558 unsigned &DiagID) { 9559 // The conversion to apply to the scalar before splatting it, 9560 // if necessary. 9561 CastKind scalarCast = CK_NoOp; 9562 9563 if (vectorEltTy->isIntegralType(S.Context)) { 9564 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9565 (scalarTy->isIntegerType() && 9566 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9567 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9568 return true; 9569 } 9570 if (!scalarTy->isIntegralType(S.Context)) 9571 return true; 9572 scalarCast = CK_IntegralCast; 9573 } else if (vectorEltTy->isRealFloatingType()) { 9574 if (scalarTy->isRealFloatingType()) { 9575 if (S.getLangOpts().OpenCL && 9576 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9577 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9578 return true; 9579 } 9580 scalarCast = CK_FloatingCast; 9581 } 9582 else if (scalarTy->isIntegralType(S.Context)) 9583 scalarCast = CK_IntegralToFloating; 9584 else 9585 return true; 9586 } else { 9587 return true; 9588 } 9589 9590 // Adjust scalar if desired. 9591 if (scalar) { 9592 if (scalarCast != CK_NoOp) 9593 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9594 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9595 } 9596 return false; 9597 } 9598 9599 /// Convert vector E to a vector with the same number of elements but different 9600 /// element type. 9601 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9602 const auto *VecTy = E->getType()->getAs<VectorType>(); 9603 assert(VecTy && "Expression E must be a vector"); 9604 QualType NewVecTy = S.Context.getVectorType(ElementType, 9605 VecTy->getNumElements(), 9606 VecTy->getVectorKind()); 9607 9608 // Look through the implicit cast. Return the subexpression if its type is 9609 // NewVecTy. 9610 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9611 if (ICE->getSubExpr()->getType() == NewVecTy) 9612 return ICE->getSubExpr(); 9613 9614 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9615 return S.ImpCastExprToType(E, NewVecTy, Cast); 9616 } 9617 9618 /// Test if a (constant) integer Int can be casted to another integer type 9619 /// IntTy without losing precision. 9620 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9621 QualType OtherIntTy) { 9622 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9623 9624 // Reject cases where the value of the Int is unknown as that would 9625 // possibly cause truncation, but accept cases where the scalar can be 9626 // demoted without loss of precision. 9627 Expr::EvalResult EVResult; 9628 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9629 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9630 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9631 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9632 9633 if (CstInt) { 9634 // If the scalar is constant and is of a higher order and has more active 9635 // bits that the vector element type, reject it. 9636 llvm::APSInt Result = EVResult.Val.getInt(); 9637 unsigned NumBits = IntSigned 9638 ? (Result.isNegative() ? Result.getMinSignedBits() 9639 : Result.getActiveBits()) 9640 : Result.getActiveBits(); 9641 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9642 return true; 9643 9644 // If the signedness of the scalar type and the vector element type 9645 // differs and the number of bits is greater than that of the vector 9646 // element reject it. 9647 return (IntSigned != OtherIntSigned && 9648 NumBits > S.Context.getIntWidth(OtherIntTy)); 9649 } 9650 9651 // Reject cases where the value of the scalar is not constant and it's 9652 // order is greater than that of the vector element type. 9653 return (Order < 0); 9654 } 9655 9656 /// Test if a (constant) integer Int can be casted to floating point type 9657 /// FloatTy without losing precision. 9658 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9659 QualType FloatTy) { 9660 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9661 9662 // Determine if the integer constant can be expressed as a floating point 9663 // number of the appropriate type. 9664 Expr::EvalResult EVResult; 9665 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9666 9667 uint64_t Bits = 0; 9668 if (CstInt) { 9669 // Reject constants that would be truncated if they were converted to 9670 // the floating point type. Test by simple to/from conversion. 9671 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9672 // could be avoided if there was a convertFromAPInt method 9673 // which could signal back if implicit truncation occurred. 9674 llvm::APSInt Result = EVResult.Val.getInt(); 9675 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9676 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9677 llvm::APFloat::rmTowardZero); 9678 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9679 !IntTy->hasSignedIntegerRepresentation()); 9680 bool Ignored = false; 9681 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9682 &Ignored); 9683 if (Result != ConvertBack) 9684 return true; 9685 } else { 9686 // Reject types that cannot be fully encoded into the mantissa of 9687 // the float. 9688 Bits = S.Context.getTypeSize(IntTy); 9689 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9690 S.Context.getFloatTypeSemantics(FloatTy)); 9691 if (Bits > FloatPrec) 9692 return true; 9693 } 9694 9695 return false; 9696 } 9697 9698 /// Attempt to convert and splat Scalar into a vector whose types matches 9699 /// Vector following GCC conversion rules. The rule is that implicit 9700 /// conversion can occur when Scalar can be casted to match Vector's element 9701 /// type without causing truncation of Scalar. 9702 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9703 ExprResult *Vector) { 9704 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9705 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9706 const VectorType *VT = VectorTy->getAs<VectorType>(); 9707 9708 assert(!isa<ExtVectorType>(VT) && 9709 "ExtVectorTypes should not be handled here!"); 9710 9711 QualType VectorEltTy = VT->getElementType(); 9712 9713 // Reject cases where the vector element type or the scalar element type are 9714 // not integral or floating point types. 9715 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9716 return true; 9717 9718 // The conversion to apply to the scalar before splatting it, 9719 // if necessary. 9720 CastKind ScalarCast = CK_NoOp; 9721 9722 // Accept cases where the vector elements are integers and the scalar is 9723 // an integer. 9724 // FIXME: Notionally if the scalar was a floating point value with a precise 9725 // integral representation, we could cast it to an appropriate integer 9726 // type and then perform the rest of the checks here. GCC will perform 9727 // this conversion in some cases as determined by the input language. 9728 // We should accept it on a language independent basis. 9729 if (VectorEltTy->isIntegralType(S.Context) && 9730 ScalarTy->isIntegralType(S.Context) && 9731 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9732 9733 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9734 return true; 9735 9736 ScalarCast = CK_IntegralCast; 9737 } else if (VectorEltTy->isIntegralType(S.Context) && 9738 ScalarTy->isRealFloatingType()) { 9739 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9740 ScalarCast = CK_FloatingToIntegral; 9741 else 9742 return true; 9743 } else if (VectorEltTy->isRealFloatingType()) { 9744 if (ScalarTy->isRealFloatingType()) { 9745 9746 // Reject cases where the scalar type is not a constant and has a higher 9747 // Order than the vector element type. 9748 llvm::APFloat Result(0.0); 9749 9750 // Determine whether this is a constant scalar. In the event that the 9751 // value is dependent (and thus cannot be evaluated by the constant 9752 // evaluator), skip the evaluation. This will then diagnose once the 9753 // expression is instantiated. 9754 bool CstScalar = Scalar->get()->isValueDependent() || 9755 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9756 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9757 if (!CstScalar && Order < 0) 9758 return true; 9759 9760 // If the scalar cannot be safely casted to the vector element type, 9761 // reject it. 9762 if (CstScalar) { 9763 bool Truncated = false; 9764 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9765 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9766 if (Truncated) 9767 return true; 9768 } 9769 9770 ScalarCast = CK_FloatingCast; 9771 } else if (ScalarTy->isIntegralType(S.Context)) { 9772 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9773 return true; 9774 9775 ScalarCast = CK_IntegralToFloating; 9776 } else 9777 return true; 9778 } else if (ScalarTy->isEnumeralType()) 9779 return true; 9780 9781 // Adjust scalar if desired. 9782 if (Scalar) { 9783 if (ScalarCast != CK_NoOp) 9784 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9785 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9786 } 9787 return false; 9788 } 9789 9790 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9791 SourceLocation Loc, bool IsCompAssign, 9792 bool AllowBothBool, 9793 bool AllowBoolConversions) { 9794 if (!IsCompAssign) { 9795 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9796 if (LHS.isInvalid()) 9797 return QualType(); 9798 } 9799 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9800 if (RHS.isInvalid()) 9801 return QualType(); 9802 9803 // For conversion purposes, we ignore any qualifiers. 9804 // For example, "const float" and "float" are equivalent. 9805 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9806 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9807 9808 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9809 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9810 assert(LHSVecType || RHSVecType); 9811 9812 // AltiVec-style "vector bool op vector bool" combinations are allowed 9813 // for some operators but not others. 9814 if (!AllowBothBool && 9815 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9816 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9817 return InvalidOperands(Loc, LHS, RHS); 9818 9819 // If the vector types are identical, return. 9820 if (Context.hasSameType(LHSType, RHSType)) 9821 return LHSType; 9822 9823 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9824 if (LHSVecType && RHSVecType && 9825 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9826 if (isa<ExtVectorType>(LHSVecType)) { 9827 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9828 return LHSType; 9829 } 9830 9831 if (!IsCompAssign) 9832 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9833 return RHSType; 9834 } 9835 9836 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9837 // can be mixed, with the result being the non-bool type. The non-bool 9838 // operand must have integer element type. 9839 if (AllowBoolConversions && LHSVecType && RHSVecType && 9840 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9841 (Context.getTypeSize(LHSVecType->getElementType()) == 9842 Context.getTypeSize(RHSVecType->getElementType()))) { 9843 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9844 LHSVecType->getElementType()->isIntegerType() && 9845 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9846 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9847 return LHSType; 9848 } 9849 if (!IsCompAssign && 9850 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9851 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9852 RHSVecType->getElementType()->isIntegerType()) { 9853 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9854 return RHSType; 9855 } 9856 } 9857 9858 // If there's a vector type and a scalar, try to convert the scalar to 9859 // the vector element type and splat. 9860 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9861 if (!RHSVecType) { 9862 if (isa<ExtVectorType>(LHSVecType)) { 9863 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9864 LHSVecType->getElementType(), LHSType, 9865 DiagID)) 9866 return LHSType; 9867 } else { 9868 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9869 return LHSType; 9870 } 9871 } 9872 if (!LHSVecType) { 9873 if (isa<ExtVectorType>(RHSVecType)) { 9874 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9875 LHSType, RHSVecType->getElementType(), 9876 RHSType, DiagID)) 9877 return RHSType; 9878 } else { 9879 if (LHS.get()->getValueKind() == VK_LValue || 9880 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9881 return RHSType; 9882 } 9883 } 9884 9885 // FIXME: The code below also handles conversion between vectors and 9886 // non-scalars, we should break this down into fine grained specific checks 9887 // and emit proper diagnostics. 9888 QualType VecType = LHSVecType ? LHSType : RHSType; 9889 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9890 QualType OtherType = LHSVecType ? RHSType : LHSType; 9891 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9892 if (isLaxVectorConversion(OtherType, VecType)) { 9893 // If we're allowing lax vector conversions, only the total (data) size 9894 // needs to be the same. For non compound assignment, if one of the types is 9895 // scalar, the result is always the vector type. 9896 if (!IsCompAssign) { 9897 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9898 return VecType; 9899 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9900 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9901 // type. Note that this is already done by non-compound assignments in 9902 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9903 // <1 x T> -> T. The result is also a vector type. 9904 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9905 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9906 ExprResult *RHSExpr = &RHS; 9907 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9908 return VecType; 9909 } 9910 } 9911 9912 // Okay, the expression is invalid. 9913 9914 // If there's a non-vector, non-real operand, diagnose that. 9915 if ((!RHSVecType && !RHSType->isRealType()) || 9916 (!LHSVecType && !LHSType->isRealType())) { 9917 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9918 << LHSType << RHSType 9919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9920 return QualType(); 9921 } 9922 9923 // OpenCL V1.1 6.2.6.p1: 9924 // If the operands are of more than one vector type, then an error shall 9925 // occur. Implicit conversions between vector types are not permitted, per 9926 // section 6.2.1. 9927 if (getLangOpts().OpenCL && 9928 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9929 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9930 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9931 << RHSType; 9932 return QualType(); 9933 } 9934 9935 9936 // If there is a vector type that is not a ExtVector and a scalar, we reach 9937 // this point if scalar could not be converted to the vector's element type 9938 // without truncation. 9939 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9940 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9941 QualType Scalar = LHSVecType ? RHSType : LHSType; 9942 QualType Vector = LHSVecType ? LHSType : RHSType; 9943 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9944 Diag(Loc, 9945 diag::err_typecheck_vector_not_convertable_implict_truncation) 9946 << ScalarOrVector << Scalar << Vector; 9947 9948 return QualType(); 9949 } 9950 9951 // Otherwise, use the generic diagnostic. 9952 Diag(Loc, DiagID) 9953 << LHSType << RHSType 9954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9955 return QualType(); 9956 } 9957 9958 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9959 // expression. These are mainly cases where the null pointer is used as an 9960 // integer instead of a pointer. 9961 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9962 SourceLocation Loc, bool IsCompare) { 9963 // The canonical way to check for a GNU null is with isNullPointerConstant, 9964 // but we use a bit of a hack here for speed; this is a relatively 9965 // hot path, and isNullPointerConstant is slow. 9966 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9967 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9968 9969 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9970 9971 // Avoid analyzing cases where the result will either be invalid (and 9972 // diagnosed as such) or entirely valid and not something to warn about. 9973 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9974 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9975 return; 9976 9977 // Comparison operations would not make sense with a null pointer no matter 9978 // what the other expression is. 9979 if (!IsCompare) { 9980 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9981 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9982 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9983 return; 9984 } 9985 9986 // The rest of the operations only make sense with a null pointer 9987 // if the other expression is a pointer. 9988 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9989 NonNullType->canDecayToPointerType()) 9990 return; 9991 9992 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9993 << LHSNull /* LHS is NULL */ << NonNullType 9994 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9995 } 9996 9997 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9998 SourceLocation Loc) { 9999 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10000 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10001 if (!LUE || !RUE) 10002 return; 10003 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10004 RUE->getKind() != UETT_SizeOf) 10005 return; 10006 10007 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10008 QualType LHSTy = LHSArg->getType(); 10009 QualType RHSTy; 10010 10011 if (RUE->isArgumentType()) 10012 RHSTy = RUE->getArgumentType(); 10013 else 10014 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10015 10016 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10017 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10018 return; 10019 10020 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10021 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10022 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10023 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10024 << LHSArgDecl; 10025 } 10026 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10027 QualType ArrayElemTy = ArrayTy->getElementType(); 10028 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10029 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10030 ArrayElemTy->isCharType() || 10031 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10032 return; 10033 S.Diag(Loc, diag::warn_division_sizeof_array) 10034 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10035 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10036 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10037 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10038 << LHSArgDecl; 10039 } 10040 10041 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10042 } 10043 } 10044 10045 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10046 ExprResult &RHS, 10047 SourceLocation Loc, bool IsDiv) { 10048 // Check for division/remainder by zero. 10049 Expr::EvalResult RHSValue; 10050 if (!RHS.get()->isValueDependent() && 10051 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10052 RHSValue.Val.getInt() == 0) 10053 S.DiagRuntimeBehavior(Loc, RHS.get(), 10054 S.PDiag(diag::warn_remainder_division_by_zero) 10055 << IsDiv << RHS.get()->getSourceRange()); 10056 } 10057 10058 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10059 SourceLocation Loc, 10060 bool IsCompAssign, bool IsDiv) { 10061 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10062 10063 if (LHS.get()->getType()->isVectorType() || 10064 RHS.get()->getType()->isVectorType()) 10065 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10066 /*AllowBothBool*/getLangOpts().AltiVec, 10067 /*AllowBoolConversions*/false); 10068 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10069 RHS.get()->getType()->isConstantMatrixType())) 10070 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10071 10072 QualType compType = UsualArithmeticConversions( 10073 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10074 if (LHS.isInvalid() || RHS.isInvalid()) 10075 return QualType(); 10076 10077 10078 if (compType.isNull() || !compType->isArithmeticType()) 10079 return InvalidOperands(Loc, LHS, RHS); 10080 if (IsDiv) { 10081 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10082 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10083 } 10084 return compType; 10085 } 10086 10087 QualType Sema::CheckRemainderOperands( 10088 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10089 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10090 10091 if (LHS.get()->getType()->isVectorType() || 10092 RHS.get()->getType()->isVectorType()) { 10093 if (LHS.get()->getType()->hasIntegerRepresentation() && 10094 RHS.get()->getType()->hasIntegerRepresentation()) 10095 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10096 /*AllowBothBool*/getLangOpts().AltiVec, 10097 /*AllowBoolConversions*/false); 10098 return InvalidOperands(Loc, LHS, RHS); 10099 } 10100 10101 QualType compType = UsualArithmeticConversions( 10102 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10103 if (LHS.isInvalid() || RHS.isInvalid()) 10104 return QualType(); 10105 10106 if (compType.isNull() || !compType->isIntegerType()) 10107 return InvalidOperands(Loc, LHS, RHS); 10108 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10109 return compType; 10110 } 10111 10112 /// Diagnose invalid arithmetic on two void pointers. 10113 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10114 Expr *LHSExpr, Expr *RHSExpr) { 10115 S.Diag(Loc, S.getLangOpts().CPlusPlus 10116 ? diag::err_typecheck_pointer_arith_void_type 10117 : diag::ext_gnu_void_ptr) 10118 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10119 << RHSExpr->getSourceRange(); 10120 } 10121 10122 /// Diagnose invalid arithmetic on a void pointer. 10123 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10124 Expr *Pointer) { 10125 S.Diag(Loc, S.getLangOpts().CPlusPlus 10126 ? diag::err_typecheck_pointer_arith_void_type 10127 : diag::ext_gnu_void_ptr) 10128 << 0 /* one pointer */ << Pointer->getSourceRange(); 10129 } 10130 10131 /// Diagnose invalid arithmetic on a null pointer. 10132 /// 10133 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10134 /// idiom, which we recognize as a GNU extension. 10135 /// 10136 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10137 Expr *Pointer, bool IsGNUIdiom) { 10138 if (IsGNUIdiom) 10139 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10140 << Pointer->getSourceRange(); 10141 else 10142 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10143 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10144 } 10145 10146 /// Diagnose invalid arithmetic on two function pointers. 10147 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10148 Expr *LHS, Expr *RHS) { 10149 assert(LHS->getType()->isAnyPointerType()); 10150 assert(RHS->getType()->isAnyPointerType()); 10151 S.Diag(Loc, S.getLangOpts().CPlusPlus 10152 ? diag::err_typecheck_pointer_arith_function_type 10153 : diag::ext_gnu_ptr_func_arith) 10154 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10155 // We only show the second type if it differs from the first. 10156 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10157 RHS->getType()) 10158 << RHS->getType()->getPointeeType() 10159 << LHS->getSourceRange() << RHS->getSourceRange(); 10160 } 10161 10162 /// Diagnose invalid arithmetic on a function pointer. 10163 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10164 Expr *Pointer) { 10165 assert(Pointer->getType()->isAnyPointerType()); 10166 S.Diag(Loc, S.getLangOpts().CPlusPlus 10167 ? diag::err_typecheck_pointer_arith_function_type 10168 : diag::ext_gnu_ptr_func_arith) 10169 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10170 << 0 /* one pointer, so only one type */ 10171 << Pointer->getSourceRange(); 10172 } 10173 10174 /// Emit error if Operand is incomplete pointer type 10175 /// 10176 /// \returns True if pointer has incomplete type 10177 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10178 Expr *Operand) { 10179 QualType ResType = Operand->getType(); 10180 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10181 ResType = ResAtomicType->getValueType(); 10182 10183 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10184 QualType PointeeTy = ResType->getPointeeType(); 10185 return S.RequireCompleteSizedType( 10186 Loc, PointeeTy, 10187 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10188 Operand->getSourceRange()); 10189 } 10190 10191 /// Check the validity of an arithmetic pointer operand. 10192 /// 10193 /// If the operand has pointer type, this code will check for pointer types 10194 /// which are invalid in arithmetic operations. These will be diagnosed 10195 /// appropriately, including whether or not the use is supported as an 10196 /// extension. 10197 /// 10198 /// \returns True when the operand is valid to use (even if as an extension). 10199 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10200 Expr *Operand) { 10201 QualType ResType = Operand->getType(); 10202 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10203 ResType = ResAtomicType->getValueType(); 10204 10205 if (!ResType->isAnyPointerType()) return true; 10206 10207 QualType PointeeTy = ResType->getPointeeType(); 10208 if (PointeeTy->isVoidType()) { 10209 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10210 return !S.getLangOpts().CPlusPlus; 10211 } 10212 if (PointeeTy->isFunctionType()) { 10213 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10214 return !S.getLangOpts().CPlusPlus; 10215 } 10216 10217 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10218 10219 return true; 10220 } 10221 10222 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10223 /// operands. 10224 /// 10225 /// This routine will diagnose any invalid arithmetic on pointer operands much 10226 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10227 /// for emitting a single diagnostic even for operations where both LHS and RHS 10228 /// are (potentially problematic) pointers. 10229 /// 10230 /// \returns True when the operand is valid to use (even if as an extension). 10231 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10232 Expr *LHSExpr, Expr *RHSExpr) { 10233 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10234 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10235 if (!isLHSPointer && !isRHSPointer) return true; 10236 10237 QualType LHSPointeeTy, RHSPointeeTy; 10238 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10239 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10240 10241 // if both are pointers check if operation is valid wrt address spaces 10242 if (isLHSPointer && isRHSPointer) { 10243 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10244 S.Diag(Loc, 10245 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10246 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10247 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10248 return false; 10249 } 10250 } 10251 10252 // Check for arithmetic on pointers to incomplete types. 10253 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10254 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10255 if (isLHSVoidPtr || isRHSVoidPtr) { 10256 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10257 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10258 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10259 10260 return !S.getLangOpts().CPlusPlus; 10261 } 10262 10263 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10264 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10265 if (isLHSFuncPtr || isRHSFuncPtr) { 10266 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10267 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10268 RHSExpr); 10269 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10270 10271 return !S.getLangOpts().CPlusPlus; 10272 } 10273 10274 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10275 return false; 10276 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10277 return false; 10278 10279 return true; 10280 } 10281 10282 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10283 /// literal. 10284 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10285 Expr *LHSExpr, Expr *RHSExpr) { 10286 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10287 Expr* IndexExpr = RHSExpr; 10288 if (!StrExpr) { 10289 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10290 IndexExpr = LHSExpr; 10291 } 10292 10293 bool IsStringPlusInt = StrExpr && 10294 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10295 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10296 return; 10297 10298 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10299 Self.Diag(OpLoc, diag::warn_string_plus_int) 10300 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10301 10302 // Only print a fixit for "str" + int, not for int + "str". 10303 if (IndexExpr == RHSExpr) { 10304 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10305 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10306 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10307 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10308 << FixItHint::CreateInsertion(EndLoc, "]"); 10309 } else 10310 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10311 } 10312 10313 /// Emit a warning when adding a char literal to a string. 10314 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10315 Expr *LHSExpr, Expr *RHSExpr) { 10316 const Expr *StringRefExpr = LHSExpr; 10317 const CharacterLiteral *CharExpr = 10318 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10319 10320 if (!CharExpr) { 10321 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10322 StringRefExpr = RHSExpr; 10323 } 10324 10325 if (!CharExpr || !StringRefExpr) 10326 return; 10327 10328 const QualType StringType = StringRefExpr->getType(); 10329 10330 // Return if not a PointerType. 10331 if (!StringType->isAnyPointerType()) 10332 return; 10333 10334 // Return if not a CharacterType. 10335 if (!StringType->getPointeeType()->isAnyCharacterType()) 10336 return; 10337 10338 ASTContext &Ctx = Self.getASTContext(); 10339 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10340 10341 const QualType CharType = CharExpr->getType(); 10342 if (!CharType->isAnyCharacterType() && 10343 CharType->isIntegerType() && 10344 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10345 Self.Diag(OpLoc, diag::warn_string_plus_char) 10346 << DiagRange << Ctx.CharTy; 10347 } else { 10348 Self.Diag(OpLoc, diag::warn_string_plus_char) 10349 << DiagRange << CharExpr->getType(); 10350 } 10351 10352 // Only print a fixit for str + char, not for char + str. 10353 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10354 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10355 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10356 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10357 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10358 << FixItHint::CreateInsertion(EndLoc, "]"); 10359 } else { 10360 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10361 } 10362 } 10363 10364 /// Emit error when two pointers are incompatible. 10365 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10366 Expr *LHSExpr, Expr *RHSExpr) { 10367 assert(LHSExpr->getType()->isAnyPointerType()); 10368 assert(RHSExpr->getType()->isAnyPointerType()); 10369 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10370 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10371 << RHSExpr->getSourceRange(); 10372 } 10373 10374 // C99 6.5.6 10375 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10376 SourceLocation Loc, BinaryOperatorKind Opc, 10377 QualType* CompLHSTy) { 10378 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10379 10380 if (LHS.get()->getType()->isVectorType() || 10381 RHS.get()->getType()->isVectorType()) { 10382 QualType compType = CheckVectorOperands( 10383 LHS, RHS, Loc, CompLHSTy, 10384 /*AllowBothBool*/getLangOpts().AltiVec, 10385 /*AllowBoolConversions*/getLangOpts().ZVector); 10386 if (CompLHSTy) *CompLHSTy = compType; 10387 return compType; 10388 } 10389 10390 if (LHS.get()->getType()->isConstantMatrixType() || 10391 RHS.get()->getType()->isConstantMatrixType()) { 10392 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10393 } 10394 10395 QualType compType = UsualArithmeticConversions( 10396 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10397 if (LHS.isInvalid() || RHS.isInvalid()) 10398 return QualType(); 10399 10400 // Diagnose "string literal" '+' int and string '+' "char literal". 10401 if (Opc == BO_Add) { 10402 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10403 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10404 } 10405 10406 // handle the common case first (both operands are arithmetic). 10407 if (!compType.isNull() && compType->isArithmeticType()) { 10408 if (CompLHSTy) *CompLHSTy = compType; 10409 return compType; 10410 } 10411 10412 // Type-checking. Ultimately the pointer's going to be in PExp; 10413 // note that we bias towards the LHS being the pointer. 10414 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10415 10416 bool isObjCPointer; 10417 if (PExp->getType()->isPointerType()) { 10418 isObjCPointer = false; 10419 } else if (PExp->getType()->isObjCObjectPointerType()) { 10420 isObjCPointer = true; 10421 } else { 10422 std::swap(PExp, IExp); 10423 if (PExp->getType()->isPointerType()) { 10424 isObjCPointer = false; 10425 } else if (PExp->getType()->isObjCObjectPointerType()) { 10426 isObjCPointer = true; 10427 } else { 10428 return InvalidOperands(Loc, LHS, RHS); 10429 } 10430 } 10431 assert(PExp->getType()->isAnyPointerType()); 10432 10433 if (!IExp->getType()->isIntegerType()) 10434 return InvalidOperands(Loc, LHS, RHS); 10435 10436 // Adding to a null pointer results in undefined behavior. 10437 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10438 Context, Expr::NPC_ValueDependentIsNotNull)) { 10439 // In C++ adding zero to a null pointer is defined. 10440 Expr::EvalResult KnownVal; 10441 if (!getLangOpts().CPlusPlus || 10442 (!IExp->isValueDependent() && 10443 (!IExp->EvaluateAsInt(KnownVal, Context) || 10444 KnownVal.Val.getInt() != 0))) { 10445 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10446 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10447 Context, BO_Add, PExp, IExp); 10448 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10449 } 10450 } 10451 10452 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10453 return QualType(); 10454 10455 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10456 return QualType(); 10457 10458 // Check array bounds for pointer arithemtic 10459 CheckArrayAccess(PExp, IExp); 10460 10461 if (CompLHSTy) { 10462 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10463 if (LHSTy.isNull()) { 10464 LHSTy = LHS.get()->getType(); 10465 if (LHSTy->isPromotableIntegerType()) 10466 LHSTy = Context.getPromotedIntegerType(LHSTy); 10467 } 10468 *CompLHSTy = LHSTy; 10469 } 10470 10471 return PExp->getType(); 10472 } 10473 10474 // C99 6.5.6 10475 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10476 SourceLocation Loc, 10477 QualType* CompLHSTy) { 10478 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10479 10480 if (LHS.get()->getType()->isVectorType() || 10481 RHS.get()->getType()->isVectorType()) { 10482 QualType compType = CheckVectorOperands( 10483 LHS, RHS, Loc, CompLHSTy, 10484 /*AllowBothBool*/getLangOpts().AltiVec, 10485 /*AllowBoolConversions*/getLangOpts().ZVector); 10486 if (CompLHSTy) *CompLHSTy = compType; 10487 return compType; 10488 } 10489 10490 if (LHS.get()->getType()->isConstantMatrixType() || 10491 RHS.get()->getType()->isConstantMatrixType()) { 10492 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10493 } 10494 10495 QualType compType = UsualArithmeticConversions( 10496 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10497 if (LHS.isInvalid() || RHS.isInvalid()) 10498 return QualType(); 10499 10500 // Enforce type constraints: C99 6.5.6p3. 10501 10502 // Handle the common case first (both operands are arithmetic). 10503 if (!compType.isNull() && compType->isArithmeticType()) { 10504 if (CompLHSTy) *CompLHSTy = compType; 10505 return compType; 10506 } 10507 10508 // Either ptr - int or ptr - ptr. 10509 if (LHS.get()->getType()->isAnyPointerType()) { 10510 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10511 10512 // Diagnose bad cases where we step over interface counts. 10513 if (LHS.get()->getType()->isObjCObjectPointerType() && 10514 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10515 return QualType(); 10516 10517 // The result type of a pointer-int computation is the pointer type. 10518 if (RHS.get()->getType()->isIntegerType()) { 10519 // Subtracting from a null pointer should produce a warning. 10520 // The last argument to the diagnose call says this doesn't match the 10521 // GNU int-to-pointer idiom. 10522 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10523 Expr::NPC_ValueDependentIsNotNull)) { 10524 // In C++ adding zero to a null pointer is defined. 10525 Expr::EvalResult KnownVal; 10526 if (!getLangOpts().CPlusPlus || 10527 (!RHS.get()->isValueDependent() && 10528 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10529 KnownVal.Val.getInt() != 0))) { 10530 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10531 } 10532 } 10533 10534 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10535 return QualType(); 10536 10537 // Check array bounds for pointer arithemtic 10538 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10539 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10540 10541 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10542 return LHS.get()->getType(); 10543 } 10544 10545 // Handle pointer-pointer subtractions. 10546 if (const PointerType *RHSPTy 10547 = RHS.get()->getType()->getAs<PointerType>()) { 10548 QualType rpointee = RHSPTy->getPointeeType(); 10549 10550 if (getLangOpts().CPlusPlus) { 10551 // Pointee types must be the same: C++ [expr.add] 10552 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10553 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10554 } 10555 } else { 10556 // Pointee types must be compatible C99 6.5.6p3 10557 if (!Context.typesAreCompatible( 10558 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10559 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10560 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10561 return QualType(); 10562 } 10563 } 10564 10565 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10566 LHS.get(), RHS.get())) 10567 return QualType(); 10568 10569 // FIXME: Add warnings for nullptr - ptr. 10570 10571 // The pointee type may have zero size. As an extension, a structure or 10572 // union may have zero size or an array may have zero length. In this 10573 // case subtraction does not make sense. 10574 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10575 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10576 if (ElementSize.isZero()) { 10577 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10578 << rpointee.getUnqualifiedType() 10579 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10580 } 10581 } 10582 10583 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10584 return Context.getPointerDiffType(); 10585 } 10586 } 10587 10588 return InvalidOperands(Loc, LHS, RHS); 10589 } 10590 10591 static bool isScopedEnumerationType(QualType T) { 10592 if (const EnumType *ET = T->getAs<EnumType>()) 10593 return ET->getDecl()->isScoped(); 10594 return false; 10595 } 10596 10597 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10598 SourceLocation Loc, BinaryOperatorKind Opc, 10599 QualType LHSType) { 10600 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10601 // so skip remaining warnings as we don't want to modify values within Sema. 10602 if (S.getLangOpts().OpenCL) 10603 return; 10604 10605 // Check right/shifter operand 10606 Expr::EvalResult RHSResult; 10607 if (RHS.get()->isValueDependent() || 10608 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10609 return; 10610 llvm::APSInt Right = RHSResult.Val.getInt(); 10611 10612 if (Right.isNegative()) { 10613 S.DiagRuntimeBehavior(Loc, RHS.get(), 10614 S.PDiag(diag::warn_shift_negative) 10615 << RHS.get()->getSourceRange()); 10616 return; 10617 } 10618 10619 QualType LHSExprType = LHS.get()->getType(); 10620 uint64_t LeftSize = LHSExprType->isExtIntType() 10621 ? S.Context.getIntWidth(LHSExprType) 10622 : S.Context.getTypeSize(LHSExprType); 10623 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10624 if (Right.uge(LeftBits)) { 10625 S.DiagRuntimeBehavior(Loc, RHS.get(), 10626 S.PDiag(diag::warn_shift_gt_typewidth) 10627 << RHS.get()->getSourceRange()); 10628 return; 10629 } 10630 10631 if (Opc != BO_Shl) 10632 return; 10633 10634 // When left shifting an ICE which is signed, we can check for overflow which 10635 // according to C++ standards prior to C++2a has undefined behavior 10636 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10637 // more than the maximum value representable in the result type, so never 10638 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10639 // expression is still probably a bug.) 10640 Expr::EvalResult LHSResult; 10641 if (LHS.get()->isValueDependent() || 10642 LHSType->hasUnsignedIntegerRepresentation() || 10643 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10644 return; 10645 llvm::APSInt Left = LHSResult.Val.getInt(); 10646 10647 // If LHS does not have a signed type and non-negative value 10648 // then, the behavior is undefined before C++2a. Warn about it. 10649 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10650 !S.getLangOpts().CPlusPlus20) { 10651 S.DiagRuntimeBehavior(Loc, LHS.get(), 10652 S.PDiag(diag::warn_shift_lhs_negative) 10653 << LHS.get()->getSourceRange()); 10654 return; 10655 } 10656 10657 llvm::APInt ResultBits = 10658 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10659 if (LeftBits.uge(ResultBits)) 10660 return; 10661 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10662 Result = Result.shl(Right); 10663 10664 // Print the bit representation of the signed integer as an unsigned 10665 // hexadecimal number. 10666 SmallString<40> HexResult; 10667 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10668 10669 // If we are only missing a sign bit, this is less likely to result in actual 10670 // bugs -- if the result is cast back to an unsigned type, it will have the 10671 // expected value. Thus we place this behind a different warning that can be 10672 // turned off separately if needed. 10673 if (LeftBits == ResultBits - 1) { 10674 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10675 << HexResult << LHSType 10676 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10677 return; 10678 } 10679 10680 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10681 << HexResult.str() << Result.getMinSignedBits() << LHSType 10682 << Left.getBitWidth() << LHS.get()->getSourceRange() 10683 << RHS.get()->getSourceRange(); 10684 } 10685 10686 /// Return the resulting type when a vector is shifted 10687 /// by a scalar or vector shift amount. 10688 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10689 SourceLocation Loc, bool IsCompAssign) { 10690 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10691 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10692 !LHS.get()->getType()->isVectorType()) { 10693 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10694 << RHS.get()->getType() << LHS.get()->getType() 10695 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10696 return QualType(); 10697 } 10698 10699 if (!IsCompAssign) { 10700 LHS = S.UsualUnaryConversions(LHS.get()); 10701 if (LHS.isInvalid()) return QualType(); 10702 } 10703 10704 RHS = S.UsualUnaryConversions(RHS.get()); 10705 if (RHS.isInvalid()) return QualType(); 10706 10707 QualType LHSType = LHS.get()->getType(); 10708 // Note that LHS might be a scalar because the routine calls not only in 10709 // OpenCL case. 10710 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10711 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10712 10713 // Note that RHS might not be a vector. 10714 QualType RHSType = RHS.get()->getType(); 10715 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10716 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10717 10718 // The operands need to be integers. 10719 if (!LHSEleType->isIntegerType()) { 10720 S.Diag(Loc, diag::err_typecheck_expect_int) 10721 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10722 return QualType(); 10723 } 10724 10725 if (!RHSEleType->isIntegerType()) { 10726 S.Diag(Loc, diag::err_typecheck_expect_int) 10727 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10728 return QualType(); 10729 } 10730 10731 if (!LHSVecTy) { 10732 assert(RHSVecTy); 10733 if (IsCompAssign) 10734 return RHSType; 10735 if (LHSEleType != RHSEleType) { 10736 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10737 LHSEleType = RHSEleType; 10738 } 10739 QualType VecTy = 10740 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10741 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10742 LHSType = VecTy; 10743 } else if (RHSVecTy) { 10744 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10745 // are applied component-wise. So if RHS is a vector, then ensure 10746 // that the number of elements is the same as LHS... 10747 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10748 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10749 << LHS.get()->getType() << RHS.get()->getType() 10750 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10751 return QualType(); 10752 } 10753 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10754 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10755 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10756 if (LHSBT != RHSBT && 10757 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10758 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10759 << LHS.get()->getType() << RHS.get()->getType() 10760 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10761 } 10762 } 10763 } else { 10764 // ...else expand RHS to match the number of elements in LHS. 10765 QualType VecTy = 10766 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10767 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10768 } 10769 10770 return LHSType; 10771 } 10772 10773 // C99 6.5.7 10774 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10775 SourceLocation Loc, BinaryOperatorKind Opc, 10776 bool IsCompAssign) { 10777 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10778 10779 // Vector shifts promote their scalar inputs to vector type. 10780 if (LHS.get()->getType()->isVectorType() || 10781 RHS.get()->getType()->isVectorType()) { 10782 if (LangOpts.ZVector) { 10783 // The shift operators for the z vector extensions work basically 10784 // like general shifts, except that neither the LHS nor the RHS is 10785 // allowed to be a "vector bool". 10786 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10787 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10788 return InvalidOperands(Loc, LHS, RHS); 10789 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10790 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10791 return InvalidOperands(Loc, LHS, RHS); 10792 } 10793 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10794 } 10795 10796 // Shifts don't perform usual arithmetic conversions, they just do integer 10797 // promotions on each operand. C99 6.5.7p3 10798 10799 // For the LHS, do usual unary conversions, but then reset them away 10800 // if this is a compound assignment. 10801 ExprResult OldLHS = LHS; 10802 LHS = UsualUnaryConversions(LHS.get()); 10803 if (LHS.isInvalid()) 10804 return QualType(); 10805 QualType LHSType = LHS.get()->getType(); 10806 if (IsCompAssign) LHS = OldLHS; 10807 10808 // The RHS is simpler. 10809 RHS = UsualUnaryConversions(RHS.get()); 10810 if (RHS.isInvalid()) 10811 return QualType(); 10812 QualType RHSType = RHS.get()->getType(); 10813 10814 // C99 6.5.7p2: Each of the operands shall have integer type. 10815 if (!LHSType->hasIntegerRepresentation() || 10816 !RHSType->hasIntegerRepresentation()) 10817 return InvalidOperands(Loc, LHS, RHS); 10818 10819 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10820 // hasIntegerRepresentation() above instead of this. 10821 if (isScopedEnumerationType(LHSType) || 10822 isScopedEnumerationType(RHSType)) { 10823 return InvalidOperands(Loc, LHS, RHS); 10824 } 10825 // Sanity-check shift operands 10826 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10827 10828 // "The type of the result is that of the promoted left operand." 10829 return LHSType; 10830 } 10831 10832 /// Diagnose bad pointer comparisons. 10833 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10834 ExprResult &LHS, ExprResult &RHS, 10835 bool IsError) { 10836 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10837 : diag::ext_typecheck_comparison_of_distinct_pointers) 10838 << LHS.get()->getType() << RHS.get()->getType() 10839 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10840 } 10841 10842 /// Returns false if the pointers are converted to a composite type, 10843 /// true otherwise. 10844 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10845 ExprResult &LHS, ExprResult &RHS) { 10846 // C++ [expr.rel]p2: 10847 // [...] Pointer conversions (4.10) and qualification 10848 // conversions (4.4) are performed on pointer operands (or on 10849 // a pointer operand and a null pointer constant) to bring 10850 // them to their composite pointer type. [...] 10851 // 10852 // C++ [expr.eq]p1 uses the same notion for (in)equality 10853 // comparisons of pointers. 10854 10855 QualType LHSType = LHS.get()->getType(); 10856 QualType RHSType = RHS.get()->getType(); 10857 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10858 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10859 10860 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10861 if (T.isNull()) { 10862 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10863 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10864 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10865 else 10866 S.InvalidOperands(Loc, LHS, RHS); 10867 return true; 10868 } 10869 10870 return false; 10871 } 10872 10873 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10874 ExprResult &LHS, 10875 ExprResult &RHS, 10876 bool IsError) { 10877 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10878 : diag::ext_typecheck_comparison_of_fptr_to_void) 10879 << LHS.get()->getType() << RHS.get()->getType() 10880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10881 } 10882 10883 static bool isObjCObjectLiteral(ExprResult &E) { 10884 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10885 case Stmt::ObjCArrayLiteralClass: 10886 case Stmt::ObjCDictionaryLiteralClass: 10887 case Stmt::ObjCStringLiteralClass: 10888 case Stmt::ObjCBoxedExprClass: 10889 return true; 10890 default: 10891 // Note that ObjCBoolLiteral is NOT an object literal! 10892 return false; 10893 } 10894 } 10895 10896 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10897 const ObjCObjectPointerType *Type = 10898 LHS->getType()->getAs<ObjCObjectPointerType>(); 10899 10900 // If this is not actually an Objective-C object, bail out. 10901 if (!Type) 10902 return false; 10903 10904 // Get the LHS object's interface type. 10905 QualType InterfaceType = Type->getPointeeType(); 10906 10907 // If the RHS isn't an Objective-C object, bail out. 10908 if (!RHS->getType()->isObjCObjectPointerType()) 10909 return false; 10910 10911 // Try to find the -isEqual: method. 10912 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10913 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10914 InterfaceType, 10915 /*IsInstance=*/true); 10916 if (!Method) { 10917 if (Type->isObjCIdType()) { 10918 // For 'id', just check the global pool. 10919 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10920 /*receiverId=*/true); 10921 } else { 10922 // Check protocols. 10923 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10924 /*IsInstance=*/true); 10925 } 10926 } 10927 10928 if (!Method) 10929 return false; 10930 10931 QualType T = Method->parameters()[0]->getType(); 10932 if (!T->isObjCObjectPointerType()) 10933 return false; 10934 10935 QualType R = Method->getReturnType(); 10936 if (!R->isScalarType()) 10937 return false; 10938 10939 return true; 10940 } 10941 10942 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10943 FromE = FromE->IgnoreParenImpCasts(); 10944 switch (FromE->getStmtClass()) { 10945 default: 10946 break; 10947 case Stmt::ObjCStringLiteralClass: 10948 // "string literal" 10949 return LK_String; 10950 case Stmt::ObjCArrayLiteralClass: 10951 // "array literal" 10952 return LK_Array; 10953 case Stmt::ObjCDictionaryLiteralClass: 10954 // "dictionary literal" 10955 return LK_Dictionary; 10956 case Stmt::BlockExprClass: 10957 return LK_Block; 10958 case Stmt::ObjCBoxedExprClass: { 10959 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10960 switch (Inner->getStmtClass()) { 10961 case Stmt::IntegerLiteralClass: 10962 case Stmt::FloatingLiteralClass: 10963 case Stmt::CharacterLiteralClass: 10964 case Stmt::ObjCBoolLiteralExprClass: 10965 case Stmt::CXXBoolLiteralExprClass: 10966 // "numeric literal" 10967 return LK_Numeric; 10968 case Stmt::ImplicitCastExprClass: { 10969 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10970 // Boolean literals can be represented by implicit casts. 10971 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10972 return LK_Numeric; 10973 break; 10974 } 10975 default: 10976 break; 10977 } 10978 return LK_Boxed; 10979 } 10980 } 10981 return LK_None; 10982 } 10983 10984 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10985 ExprResult &LHS, ExprResult &RHS, 10986 BinaryOperator::Opcode Opc){ 10987 Expr *Literal; 10988 Expr *Other; 10989 if (isObjCObjectLiteral(LHS)) { 10990 Literal = LHS.get(); 10991 Other = RHS.get(); 10992 } else { 10993 Literal = RHS.get(); 10994 Other = LHS.get(); 10995 } 10996 10997 // Don't warn on comparisons against nil. 10998 Other = Other->IgnoreParenCasts(); 10999 if (Other->isNullPointerConstant(S.getASTContext(), 11000 Expr::NPC_ValueDependentIsNotNull)) 11001 return; 11002 11003 // This should be kept in sync with warn_objc_literal_comparison. 11004 // LK_String should always be after the other literals, since it has its own 11005 // warning flag. 11006 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11007 assert(LiteralKind != Sema::LK_Block); 11008 if (LiteralKind == Sema::LK_None) { 11009 llvm_unreachable("Unknown Objective-C object literal kind"); 11010 } 11011 11012 if (LiteralKind == Sema::LK_String) 11013 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11014 << Literal->getSourceRange(); 11015 else 11016 S.Diag(Loc, diag::warn_objc_literal_comparison) 11017 << LiteralKind << Literal->getSourceRange(); 11018 11019 if (BinaryOperator::isEqualityOp(Opc) && 11020 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11021 SourceLocation Start = LHS.get()->getBeginLoc(); 11022 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11023 CharSourceRange OpRange = 11024 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11025 11026 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11027 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11028 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11029 << FixItHint::CreateInsertion(End, "]"); 11030 } 11031 } 11032 11033 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11034 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11035 ExprResult &RHS, SourceLocation Loc, 11036 BinaryOperatorKind Opc) { 11037 // Check that left hand side is !something. 11038 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11039 if (!UO || UO->getOpcode() != UO_LNot) return; 11040 11041 // Only check if the right hand side is non-bool arithmetic type. 11042 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11043 11044 // Make sure that the something in !something is not bool. 11045 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11046 if (SubExpr->isKnownToHaveBooleanValue()) return; 11047 11048 // Emit warning. 11049 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11050 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11051 << Loc << IsBitwiseOp; 11052 11053 // First note suggest !(x < y) 11054 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11055 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11056 FirstClose = S.getLocForEndOfToken(FirstClose); 11057 if (FirstClose.isInvalid()) 11058 FirstOpen = SourceLocation(); 11059 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11060 << IsBitwiseOp 11061 << FixItHint::CreateInsertion(FirstOpen, "(") 11062 << FixItHint::CreateInsertion(FirstClose, ")"); 11063 11064 // Second note suggests (!x) < y 11065 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11066 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11067 SecondClose = S.getLocForEndOfToken(SecondClose); 11068 if (SecondClose.isInvalid()) 11069 SecondOpen = SourceLocation(); 11070 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11071 << FixItHint::CreateInsertion(SecondOpen, "(") 11072 << FixItHint::CreateInsertion(SecondClose, ")"); 11073 } 11074 11075 // Returns true if E refers to a non-weak array. 11076 static bool checkForArray(const Expr *E) { 11077 const ValueDecl *D = nullptr; 11078 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11079 D = DR->getDecl(); 11080 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11081 if (Mem->isImplicitAccess()) 11082 D = Mem->getMemberDecl(); 11083 } 11084 if (!D) 11085 return false; 11086 return D->getType()->isArrayType() && !D->isWeak(); 11087 } 11088 11089 /// Diagnose some forms of syntactically-obvious tautological comparison. 11090 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11091 Expr *LHS, Expr *RHS, 11092 BinaryOperatorKind Opc) { 11093 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11094 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11095 11096 QualType LHSType = LHS->getType(); 11097 QualType RHSType = RHS->getType(); 11098 if (LHSType->hasFloatingRepresentation() || 11099 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11100 S.inTemplateInstantiation()) 11101 return; 11102 11103 // Comparisons between two array types are ill-formed for operator<=>, so 11104 // we shouldn't emit any additional warnings about it. 11105 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11106 return; 11107 11108 // For non-floating point types, check for self-comparisons of the form 11109 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11110 // often indicate logic errors in the program. 11111 // 11112 // NOTE: Don't warn about comparison expressions resulting from macro 11113 // expansion. Also don't warn about comparisons which are only self 11114 // comparisons within a template instantiation. The warnings should catch 11115 // obvious cases in the definition of the template anyways. The idea is to 11116 // warn when the typed comparison operator will always evaluate to the same 11117 // result. 11118 11119 // Used for indexing into %select in warn_comparison_always 11120 enum { 11121 AlwaysConstant, 11122 AlwaysTrue, 11123 AlwaysFalse, 11124 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11125 }; 11126 11127 // C++2a [depr.array.comp]: 11128 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11129 // operands of array type are deprecated. 11130 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11131 RHSStripped->getType()->isArrayType()) { 11132 S.Diag(Loc, diag::warn_depr_array_comparison) 11133 << LHS->getSourceRange() << RHS->getSourceRange() 11134 << LHSStripped->getType() << RHSStripped->getType(); 11135 // Carry on to produce the tautological comparison warning, if this 11136 // expression is potentially-evaluated, we can resolve the array to a 11137 // non-weak declaration, and so on. 11138 } 11139 11140 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11141 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11142 unsigned Result; 11143 switch (Opc) { 11144 case BO_EQ: 11145 case BO_LE: 11146 case BO_GE: 11147 Result = AlwaysTrue; 11148 break; 11149 case BO_NE: 11150 case BO_LT: 11151 case BO_GT: 11152 Result = AlwaysFalse; 11153 break; 11154 case BO_Cmp: 11155 Result = AlwaysEqual; 11156 break; 11157 default: 11158 Result = AlwaysConstant; 11159 break; 11160 } 11161 S.DiagRuntimeBehavior(Loc, nullptr, 11162 S.PDiag(diag::warn_comparison_always) 11163 << 0 /*self-comparison*/ 11164 << Result); 11165 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11166 // What is it always going to evaluate to? 11167 unsigned Result; 11168 switch (Opc) { 11169 case BO_EQ: // e.g. array1 == array2 11170 Result = AlwaysFalse; 11171 break; 11172 case BO_NE: // e.g. array1 != array2 11173 Result = AlwaysTrue; 11174 break; 11175 default: // e.g. array1 <= array2 11176 // The best we can say is 'a constant' 11177 Result = AlwaysConstant; 11178 break; 11179 } 11180 S.DiagRuntimeBehavior(Loc, nullptr, 11181 S.PDiag(diag::warn_comparison_always) 11182 << 1 /*array comparison*/ 11183 << Result); 11184 } 11185 } 11186 11187 if (isa<CastExpr>(LHSStripped)) 11188 LHSStripped = LHSStripped->IgnoreParenCasts(); 11189 if (isa<CastExpr>(RHSStripped)) 11190 RHSStripped = RHSStripped->IgnoreParenCasts(); 11191 11192 // Warn about comparisons against a string constant (unless the other 11193 // operand is null); the user probably wants string comparison function. 11194 Expr *LiteralString = nullptr; 11195 Expr *LiteralStringStripped = nullptr; 11196 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11197 !RHSStripped->isNullPointerConstant(S.Context, 11198 Expr::NPC_ValueDependentIsNull)) { 11199 LiteralString = LHS; 11200 LiteralStringStripped = LHSStripped; 11201 } else if ((isa<StringLiteral>(RHSStripped) || 11202 isa<ObjCEncodeExpr>(RHSStripped)) && 11203 !LHSStripped->isNullPointerConstant(S.Context, 11204 Expr::NPC_ValueDependentIsNull)) { 11205 LiteralString = RHS; 11206 LiteralStringStripped = RHSStripped; 11207 } 11208 11209 if (LiteralString) { 11210 S.DiagRuntimeBehavior(Loc, nullptr, 11211 S.PDiag(diag::warn_stringcompare) 11212 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11213 << LiteralString->getSourceRange()); 11214 } 11215 } 11216 11217 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11218 switch (CK) { 11219 default: { 11220 #ifndef NDEBUG 11221 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11222 << "\n"; 11223 #endif 11224 llvm_unreachable("unhandled cast kind"); 11225 } 11226 case CK_UserDefinedConversion: 11227 return ICK_Identity; 11228 case CK_LValueToRValue: 11229 return ICK_Lvalue_To_Rvalue; 11230 case CK_ArrayToPointerDecay: 11231 return ICK_Array_To_Pointer; 11232 case CK_FunctionToPointerDecay: 11233 return ICK_Function_To_Pointer; 11234 case CK_IntegralCast: 11235 return ICK_Integral_Conversion; 11236 case CK_FloatingCast: 11237 return ICK_Floating_Conversion; 11238 case CK_IntegralToFloating: 11239 case CK_FloatingToIntegral: 11240 return ICK_Floating_Integral; 11241 case CK_IntegralComplexCast: 11242 case CK_FloatingComplexCast: 11243 case CK_FloatingComplexToIntegralComplex: 11244 case CK_IntegralComplexToFloatingComplex: 11245 return ICK_Complex_Conversion; 11246 case CK_FloatingComplexToReal: 11247 case CK_FloatingRealToComplex: 11248 case CK_IntegralComplexToReal: 11249 case CK_IntegralRealToComplex: 11250 return ICK_Complex_Real; 11251 } 11252 } 11253 11254 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11255 QualType FromType, 11256 SourceLocation Loc) { 11257 // Check for a narrowing implicit conversion. 11258 StandardConversionSequence SCS; 11259 SCS.setAsIdentityConversion(); 11260 SCS.setToType(0, FromType); 11261 SCS.setToType(1, ToType); 11262 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11263 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11264 11265 APValue PreNarrowingValue; 11266 QualType PreNarrowingType; 11267 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11268 PreNarrowingType, 11269 /*IgnoreFloatToIntegralConversion*/ true)) { 11270 case NK_Dependent_Narrowing: 11271 // Implicit conversion to a narrower type, but the expression is 11272 // value-dependent so we can't tell whether it's actually narrowing. 11273 case NK_Not_Narrowing: 11274 return false; 11275 11276 case NK_Constant_Narrowing: 11277 // Implicit conversion to a narrower type, and the value is not a constant 11278 // expression. 11279 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11280 << /*Constant*/ 1 11281 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11282 return true; 11283 11284 case NK_Variable_Narrowing: 11285 // Implicit conversion to a narrower type, and the value is not a constant 11286 // expression. 11287 case NK_Type_Narrowing: 11288 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11289 << /*Constant*/ 0 << FromType << ToType; 11290 // TODO: It's not a constant expression, but what if the user intended it 11291 // to be? Can we produce notes to help them figure out why it isn't? 11292 return true; 11293 } 11294 llvm_unreachable("unhandled case in switch"); 11295 } 11296 11297 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11298 ExprResult &LHS, 11299 ExprResult &RHS, 11300 SourceLocation Loc) { 11301 QualType LHSType = LHS.get()->getType(); 11302 QualType RHSType = RHS.get()->getType(); 11303 // Dig out the original argument type and expression before implicit casts 11304 // were applied. These are the types/expressions we need to check the 11305 // [expr.spaceship] requirements against. 11306 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11307 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11308 QualType LHSStrippedType = LHSStripped.get()->getType(); 11309 QualType RHSStrippedType = RHSStripped.get()->getType(); 11310 11311 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11312 // other is not, the program is ill-formed. 11313 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11314 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11315 return QualType(); 11316 } 11317 11318 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11319 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11320 RHSStrippedType->isEnumeralType(); 11321 if (NumEnumArgs == 1) { 11322 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11323 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11324 if (OtherTy->hasFloatingRepresentation()) { 11325 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11326 return QualType(); 11327 } 11328 } 11329 if (NumEnumArgs == 2) { 11330 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11331 // type E, the operator yields the result of converting the operands 11332 // to the underlying type of E and applying <=> to the converted operands. 11333 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11334 S.InvalidOperands(Loc, LHS, RHS); 11335 return QualType(); 11336 } 11337 QualType IntType = 11338 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11339 assert(IntType->isArithmeticType()); 11340 11341 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11342 // promote the boolean type, and all other promotable integer types, to 11343 // avoid this. 11344 if (IntType->isPromotableIntegerType()) 11345 IntType = S.Context.getPromotedIntegerType(IntType); 11346 11347 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11348 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11349 LHSType = RHSType = IntType; 11350 } 11351 11352 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11353 // usual arithmetic conversions are applied to the operands. 11354 QualType Type = 11355 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11356 if (LHS.isInvalid() || RHS.isInvalid()) 11357 return QualType(); 11358 if (Type.isNull()) 11359 return S.InvalidOperands(Loc, LHS, RHS); 11360 11361 Optional<ComparisonCategoryType> CCT = 11362 getComparisonCategoryForBuiltinCmp(Type); 11363 if (!CCT) 11364 return S.InvalidOperands(Loc, LHS, RHS); 11365 11366 bool HasNarrowing = checkThreeWayNarrowingConversion( 11367 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11368 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11369 RHS.get()->getBeginLoc()); 11370 if (HasNarrowing) 11371 return QualType(); 11372 11373 assert(!Type.isNull() && "composite type for <=> has not been set"); 11374 11375 return S.CheckComparisonCategoryType( 11376 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11377 } 11378 11379 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11380 ExprResult &RHS, 11381 SourceLocation Loc, 11382 BinaryOperatorKind Opc) { 11383 if (Opc == BO_Cmp) 11384 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11385 11386 // C99 6.5.8p3 / C99 6.5.9p4 11387 QualType Type = 11388 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11389 if (LHS.isInvalid() || RHS.isInvalid()) 11390 return QualType(); 11391 if (Type.isNull()) 11392 return S.InvalidOperands(Loc, LHS, RHS); 11393 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11394 11395 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11396 return S.InvalidOperands(Loc, LHS, RHS); 11397 11398 // Check for comparisons of floating point operands using != and ==. 11399 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11400 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11401 11402 // The result of comparisons is 'bool' in C++, 'int' in C. 11403 return S.Context.getLogicalOperationType(); 11404 } 11405 11406 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11407 if (!NullE.get()->getType()->isAnyPointerType()) 11408 return; 11409 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11410 if (!E.get()->getType()->isAnyPointerType() && 11411 E.get()->isNullPointerConstant(Context, 11412 Expr::NPC_ValueDependentIsNotNull) == 11413 Expr::NPCK_ZeroExpression) { 11414 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11415 if (CL->getValue() == 0) 11416 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11417 << NullValue 11418 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11419 NullValue ? "NULL" : "(void *)0"); 11420 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11421 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11422 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11423 if (T == Context.CharTy) 11424 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11425 << NullValue 11426 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11427 NullValue ? "NULL" : "(void *)0"); 11428 } 11429 } 11430 } 11431 11432 // C99 6.5.8, C++ [expr.rel] 11433 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11434 SourceLocation Loc, 11435 BinaryOperatorKind Opc) { 11436 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11437 bool IsThreeWay = Opc == BO_Cmp; 11438 bool IsOrdered = IsRelational || IsThreeWay; 11439 auto IsAnyPointerType = [](ExprResult E) { 11440 QualType Ty = E.get()->getType(); 11441 return Ty->isPointerType() || Ty->isMemberPointerType(); 11442 }; 11443 11444 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11445 // type, array-to-pointer, ..., conversions are performed on both operands to 11446 // bring them to their composite type. 11447 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11448 // any type-related checks. 11449 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11450 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11451 if (LHS.isInvalid()) 11452 return QualType(); 11453 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11454 if (RHS.isInvalid()) 11455 return QualType(); 11456 } else { 11457 LHS = DefaultLvalueConversion(LHS.get()); 11458 if (LHS.isInvalid()) 11459 return QualType(); 11460 RHS = DefaultLvalueConversion(RHS.get()); 11461 if (RHS.isInvalid()) 11462 return QualType(); 11463 } 11464 11465 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11466 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11467 CheckPtrComparisonWithNullChar(LHS, RHS); 11468 CheckPtrComparisonWithNullChar(RHS, LHS); 11469 } 11470 11471 // Handle vector comparisons separately. 11472 if (LHS.get()->getType()->isVectorType() || 11473 RHS.get()->getType()->isVectorType()) 11474 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11475 11476 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11477 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11478 11479 QualType LHSType = LHS.get()->getType(); 11480 QualType RHSType = RHS.get()->getType(); 11481 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11482 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11483 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11484 11485 const Expr::NullPointerConstantKind LHSNullKind = 11486 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11487 const Expr::NullPointerConstantKind RHSNullKind = 11488 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11489 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11490 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11491 11492 auto computeResultTy = [&]() { 11493 if (Opc != BO_Cmp) 11494 return Context.getLogicalOperationType(); 11495 assert(getLangOpts().CPlusPlus); 11496 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11497 11498 QualType CompositeTy = LHS.get()->getType(); 11499 assert(!CompositeTy->isReferenceType()); 11500 11501 Optional<ComparisonCategoryType> CCT = 11502 getComparisonCategoryForBuiltinCmp(CompositeTy); 11503 if (!CCT) 11504 return InvalidOperands(Loc, LHS, RHS); 11505 11506 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11507 // P0946R0: Comparisons between a null pointer constant and an object 11508 // pointer result in std::strong_equality, which is ill-formed under 11509 // P1959R0. 11510 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11511 << (LHSIsNull ? LHS.get()->getSourceRange() 11512 : RHS.get()->getSourceRange()); 11513 return QualType(); 11514 } 11515 11516 return CheckComparisonCategoryType( 11517 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11518 }; 11519 11520 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11521 bool IsEquality = Opc == BO_EQ; 11522 if (RHSIsNull) 11523 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11524 RHS.get()->getSourceRange()); 11525 else 11526 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11527 LHS.get()->getSourceRange()); 11528 } 11529 11530 if ((LHSType->isIntegerType() && !LHSIsNull) || 11531 (RHSType->isIntegerType() && !RHSIsNull)) { 11532 // Skip normal pointer conversion checks in this case; we have better 11533 // diagnostics for this below. 11534 } else if (getLangOpts().CPlusPlus) { 11535 // Equality comparison of a function pointer to a void pointer is invalid, 11536 // but we allow it as an extension. 11537 // FIXME: If we really want to allow this, should it be part of composite 11538 // pointer type computation so it works in conditionals too? 11539 if (!IsOrdered && 11540 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11541 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11542 // This is a gcc extension compatibility comparison. 11543 // In a SFINAE context, we treat this as a hard error to maintain 11544 // conformance with the C++ standard. 11545 diagnoseFunctionPointerToVoidComparison( 11546 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11547 11548 if (isSFINAEContext()) 11549 return QualType(); 11550 11551 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11552 return computeResultTy(); 11553 } 11554 11555 // C++ [expr.eq]p2: 11556 // If at least one operand is a pointer [...] bring them to their 11557 // composite pointer type. 11558 // C++ [expr.spaceship]p6 11559 // If at least one of the operands is of pointer type, [...] bring them 11560 // to their composite pointer type. 11561 // C++ [expr.rel]p2: 11562 // If both operands are pointers, [...] bring them to their composite 11563 // pointer type. 11564 // For <=>, the only valid non-pointer types are arrays and functions, and 11565 // we already decayed those, so this is really the same as the relational 11566 // comparison rule. 11567 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11568 (IsOrdered ? 2 : 1) && 11569 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11570 RHSType->isObjCObjectPointerType()))) { 11571 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11572 return QualType(); 11573 return computeResultTy(); 11574 } 11575 } else if (LHSType->isPointerType() && 11576 RHSType->isPointerType()) { // C99 6.5.8p2 11577 // All of the following pointer-related warnings are GCC extensions, except 11578 // when handling null pointer constants. 11579 QualType LCanPointeeTy = 11580 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11581 QualType RCanPointeeTy = 11582 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11583 11584 // C99 6.5.9p2 and C99 6.5.8p2 11585 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11586 RCanPointeeTy.getUnqualifiedType())) { 11587 if (IsRelational) { 11588 // Pointers both need to point to complete or incomplete types 11589 if ((LCanPointeeTy->isIncompleteType() != 11590 RCanPointeeTy->isIncompleteType()) && 11591 !getLangOpts().C11) { 11592 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11593 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11594 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11595 << RCanPointeeTy->isIncompleteType(); 11596 } 11597 if (LCanPointeeTy->isFunctionType()) { 11598 // Valid unless a relational comparison of function pointers 11599 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11600 << LHSType << RHSType << LHS.get()->getSourceRange() 11601 << RHS.get()->getSourceRange(); 11602 } 11603 } 11604 } else if (!IsRelational && 11605 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11606 // Valid unless comparison between non-null pointer and function pointer 11607 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11608 && !LHSIsNull && !RHSIsNull) 11609 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11610 /*isError*/false); 11611 } else { 11612 // Invalid 11613 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11614 } 11615 if (LCanPointeeTy != RCanPointeeTy) { 11616 // Treat NULL constant as a special case in OpenCL. 11617 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11618 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11619 Diag(Loc, 11620 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11621 << LHSType << RHSType << 0 /* comparison */ 11622 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11623 } 11624 } 11625 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11626 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11627 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11628 : CK_BitCast; 11629 if (LHSIsNull && !RHSIsNull) 11630 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11631 else 11632 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11633 } 11634 return computeResultTy(); 11635 } 11636 11637 if (getLangOpts().CPlusPlus) { 11638 // C++ [expr.eq]p4: 11639 // Two operands of type std::nullptr_t or one operand of type 11640 // std::nullptr_t and the other a null pointer constant compare equal. 11641 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11642 if (LHSType->isNullPtrType()) { 11643 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11644 return computeResultTy(); 11645 } 11646 if (RHSType->isNullPtrType()) { 11647 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11648 return computeResultTy(); 11649 } 11650 } 11651 11652 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11653 // These aren't covered by the composite pointer type rules. 11654 if (!IsOrdered && RHSType->isNullPtrType() && 11655 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11656 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11657 return computeResultTy(); 11658 } 11659 if (!IsOrdered && LHSType->isNullPtrType() && 11660 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11661 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11662 return computeResultTy(); 11663 } 11664 11665 if (IsRelational && 11666 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11667 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11668 // HACK: Relational comparison of nullptr_t against a pointer type is 11669 // invalid per DR583, but we allow it within std::less<> and friends, 11670 // since otherwise common uses of it break. 11671 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11672 // friends to have std::nullptr_t overload candidates. 11673 DeclContext *DC = CurContext; 11674 if (isa<FunctionDecl>(DC)) 11675 DC = DC->getParent(); 11676 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11677 if (CTSD->isInStdNamespace() && 11678 llvm::StringSwitch<bool>(CTSD->getName()) 11679 .Cases("less", "less_equal", "greater", "greater_equal", true) 11680 .Default(false)) { 11681 if (RHSType->isNullPtrType()) 11682 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11683 else 11684 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11685 return computeResultTy(); 11686 } 11687 } 11688 } 11689 11690 // C++ [expr.eq]p2: 11691 // If at least one operand is a pointer to member, [...] bring them to 11692 // their composite pointer type. 11693 if (!IsOrdered && 11694 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11695 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11696 return QualType(); 11697 else 11698 return computeResultTy(); 11699 } 11700 } 11701 11702 // Handle block pointer types. 11703 if (!IsOrdered && LHSType->isBlockPointerType() && 11704 RHSType->isBlockPointerType()) { 11705 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11706 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11707 11708 if (!LHSIsNull && !RHSIsNull && 11709 !Context.typesAreCompatible(lpointee, rpointee)) { 11710 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11711 << LHSType << RHSType << LHS.get()->getSourceRange() 11712 << RHS.get()->getSourceRange(); 11713 } 11714 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11715 return computeResultTy(); 11716 } 11717 11718 // Allow block pointers to be compared with null pointer constants. 11719 if (!IsOrdered 11720 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11721 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11722 if (!LHSIsNull && !RHSIsNull) { 11723 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11724 ->getPointeeType()->isVoidType()) 11725 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11726 ->getPointeeType()->isVoidType()))) 11727 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11728 << LHSType << RHSType << LHS.get()->getSourceRange() 11729 << RHS.get()->getSourceRange(); 11730 } 11731 if (LHSIsNull && !RHSIsNull) 11732 LHS = ImpCastExprToType(LHS.get(), RHSType, 11733 RHSType->isPointerType() ? CK_BitCast 11734 : CK_AnyPointerToBlockPointerCast); 11735 else 11736 RHS = ImpCastExprToType(RHS.get(), LHSType, 11737 LHSType->isPointerType() ? CK_BitCast 11738 : CK_AnyPointerToBlockPointerCast); 11739 return computeResultTy(); 11740 } 11741 11742 if (LHSType->isObjCObjectPointerType() || 11743 RHSType->isObjCObjectPointerType()) { 11744 const PointerType *LPT = LHSType->getAs<PointerType>(); 11745 const PointerType *RPT = RHSType->getAs<PointerType>(); 11746 if (LPT || RPT) { 11747 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11748 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11749 11750 if (!LPtrToVoid && !RPtrToVoid && 11751 !Context.typesAreCompatible(LHSType, RHSType)) { 11752 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11753 /*isError*/false); 11754 } 11755 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11756 // the RHS, but we have test coverage for this behavior. 11757 // FIXME: Consider using convertPointersToCompositeType in C++. 11758 if (LHSIsNull && !RHSIsNull) { 11759 Expr *E = LHS.get(); 11760 if (getLangOpts().ObjCAutoRefCount) 11761 CheckObjCConversion(SourceRange(), RHSType, E, 11762 CCK_ImplicitConversion); 11763 LHS = ImpCastExprToType(E, RHSType, 11764 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11765 } 11766 else { 11767 Expr *E = RHS.get(); 11768 if (getLangOpts().ObjCAutoRefCount) 11769 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11770 /*Diagnose=*/true, 11771 /*DiagnoseCFAudited=*/false, Opc); 11772 RHS = ImpCastExprToType(E, LHSType, 11773 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11774 } 11775 return computeResultTy(); 11776 } 11777 if (LHSType->isObjCObjectPointerType() && 11778 RHSType->isObjCObjectPointerType()) { 11779 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11780 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11781 /*isError*/false); 11782 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11783 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11784 11785 if (LHSIsNull && !RHSIsNull) 11786 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11787 else 11788 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11789 return computeResultTy(); 11790 } 11791 11792 if (!IsOrdered && LHSType->isBlockPointerType() && 11793 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11794 LHS = ImpCastExprToType(LHS.get(), RHSType, 11795 CK_BlockPointerToObjCPointerCast); 11796 return computeResultTy(); 11797 } else if (!IsOrdered && 11798 LHSType->isBlockCompatibleObjCPointerType(Context) && 11799 RHSType->isBlockPointerType()) { 11800 RHS = ImpCastExprToType(RHS.get(), LHSType, 11801 CK_BlockPointerToObjCPointerCast); 11802 return computeResultTy(); 11803 } 11804 } 11805 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11806 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11807 unsigned DiagID = 0; 11808 bool isError = false; 11809 if (LangOpts.DebuggerSupport) { 11810 // Under a debugger, allow the comparison of pointers to integers, 11811 // since users tend to want to compare addresses. 11812 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11813 (RHSIsNull && RHSType->isIntegerType())) { 11814 if (IsOrdered) { 11815 isError = getLangOpts().CPlusPlus; 11816 DiagID = 11817 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11818 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11819 } 11820 } else if (getLangOpts().CPlusPlus) { 11821 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11822 isError = true; 11823 } else if (IsOrdered) 11824 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11825 else 11826 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11827 11828 if (DiagID) { 11829 Diag(Loc, DiagID) 11830 << LHSType << RHSType << LHS.get()->getSourceRange() 11831 << RHS.get()->getSourceRange(); 11832 if (isError) 11833 return QualType(); 11834 } 11835 11836 if (LHSType->isIntegerType()) 11837 LHS = ImpCastExprToType(LHS.get(), RHSType, 11838 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11839 else 11840 RHS = ImpCastExprToType(RHS.get(), LHSType, 11841 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11842 return computeResultTy(); 11843 } 11844 11845 // Handle block pointers. 11846 if (!IsOrdered && RHSIsNull 11847 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11848 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11849 return computeResultTy(); 11850 } 11851 if (!IsOrdered && LHSIsNull 11852 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11853 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11854 return computeResultTy(); 11855 } 11856 11857 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11858 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11859 return computeResultTy(); 11860 } 11861 11862 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11863 return computeResultTy(); 11864 } 11865 11866 if (LHSIsNull && RHSType->isQueueT()) { 11867 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11868 return computeResultTy(); 11869 } 11870 11871 if (LHSType->isQueueT() && RHSIsNull) { 11872 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11873 return computeResultTy(); 11874 } 11875 } 11876 11877 return InvalidOperands(Loc, LHS, RHS); 11878 } 11879 11880 // Return a signed ext_vector_type that is of identical size and number of 11881 // elements. For floating point vectors, return an integer type of identical 11882 // size and number of elements. In the non ext_vector_type case, search from 11883 // the largest type to the smallest type to avoid cases where long long == long, 11884 // where long gets picked over long long. 11885 QualType Sema::GetSignedVectorType(QualType V) { 11886 const VectorType *VTy = V->castAs<VectorType>(); 11887 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11888 11889 if (isa<ExtVectorType>(VTy)) { 11890 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11891 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11892 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11893 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11894 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11895 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11896 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11897 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11898 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11899 "Unhandled vector element size in vector compare"); 11900 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11901 } 11902 11903 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11904 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11905 VectorType::GenericVector); 11906 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11907 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11908 VectorType::GenericVector); 11909 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11910 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11911 VectorType::GenericVector); 11912 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11913 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11914 VectorType::GenericVector); 11915 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11916 "Unhandled vector element size in vector compare"); 11917 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11918 VectorType::GenericVector); 11919 } 11920 11921 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11922 /// operates on extended vector types. Instead of producing an IntTy result, 11923 /// like a scalar comparison, a vector comparison produces a vector of integer 11924 /// types. 11925 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11926 SourceLocation Loc, 11927 BinaryOperatorKind Opc) { 11928 if (Opc == BO_Cmp) { 11929 Diag(Loc, diag::err_three_way_vector_comparison); 11930 return QualType(); 11931 } 11932 11933 // Check to make sure we're operating on vectors of the same type and width, 11934 // Allowing one side to be a scalar of element type. 11935 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11936 /*AllowBothBool*/true, 11937 /*AllowBoolConversions*/getLangOpts().ZVector); 11938 if (vType.isNull()) 11939 return vType; 11940 11941 QualType LHSType = LHS.get()->getType(); 11942 11943 // If AltiVec, the comparison results in a numeric type, i.e. 11944 // bool for C++, int for C 11945 if (getLangOpts().AltiVec && 11946 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11947 return Context.getLogicalOperationType(); 11948 11949 // For non-floating point types, check for self-comparisons of the form 11950 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11951 // often indicate logic errors in the program. 11952 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11953 11954 // Check for comparisons of floating point operands using != and ==. 11955 if (BinaryOperator::isEqualityOp(Opc) && 11956 LHSType->hasFloatingRepresentation()) { 11957 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11958 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11959 } 11960 11961 // Return a signed type for the vector. 11962 return GetSignedVectorType(vType); 11963 } 11964 11965 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11966 const ExprResult &XorRHS, 11967 const SourceLocation Loc) { 11968 // Do not diagnose macros. 11969 if (Loc.isMacroID()) 11970 return; 11971 11972 bool Negative = false; 11973 bool ExplicitPlus = false; 11974 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11975 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11976 11977 if (!LHSInt) 11978 return; 11979 if (!RHSInt) { 11980 // Check negative literals. 11981 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11982 UnaryOperatorKind Opc = UO->getOpcode(); 11983 if (Opc != UO_Minus && Opc != UO_Plus) 11984 return; 11985 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11986 if (!RHSInt) 11987 return; 11988 Negative = (Opc == UO_Minus); 11989 ExplicitPlus = !Negative; 11990 } else { 11991 return; 11992 } 11993 } 11994 11995 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11996 llvm::APInt RightSideValue = RHSInt->getValue(); 11997 if (LeftSideValue != 2 && LeftSideValue != 10) 11998 return; 11999 12000 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12001 return; 12002 12003 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12004 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12005 llvm::StringRef ExprStr = 12006 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12007 12008 CharSourceRange XorRange = 12009 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12010 llvm::StringRef XorStr = 12011 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12012 // Do not diagnose if xor keyword/macro is used. 12013 if (XorStr == "xor") 12014 return; 12015 12016 std::string LHSStr = std::string(Lexer::getSourceText( 12017 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12018 S.getSourceManager(), S.getLangOpts())); 12019 std::string RHSStr = std::string(Lexer::getSourceText( 12020 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12021 S.getSourceManager(), S.getLangOpts())); 12022 12023 if (Negative) { 12024 RightSideValue = -RightSideValue; 12025 RHSStr = "-" + RHSStr; 12026 } else if (ExplicitPlus) { 12027 RHSStr = "+" + RHSStr; 12028 } 12029 12030 StringRef LHSStrRef = LHSStr; 12031 StringRef RHSStrRef = RHSStr; 12032 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12033 // literals. 12034 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12035 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12036 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12037 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12038 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12039 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12040 LHSStrRef.find('\'') != StringRef::npos || 12041 RHSStrRef.find('\'') != StringRef::npos) 12042 return; 12043 12044 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12045 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12046 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12047 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12048 std::string SuggestedExpr = "1 << " + RHSStr; 12049 bool Overflow = false; 12050 llvm::APInt One = (LeftSideValue - 1); 12051 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12052 if (Overflow) { 12053 if (RightSideIntValue < 64) 12054 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12055 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12056 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12057 else if (RightSideIntValue == 64) 12058 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12059 else 12060 return; 12061 } else { 12062 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12063 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12064 << PowValue.toString(10, true) 12065 << FixItHint::CreateReplacement( 12066 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12067 } 12068 12069 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12070 } else if (LeftSideValue == 10) { 12071 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12072 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12073 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12074 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12075 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12076 } 12077 } 12078 12079 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12080 SourceLocation Loc) { 12081 // Ensure that either both operands are of the same vector type, or 12082 // one operand is of a vector type and the other is of its element type. 12083 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12084 /*AllowBothBool*/true, 12085 /*AllowBoolConversions*/false); 12086 if (vType.isNull()) 12087 return InvalidOperands(Loc, LHS, RHS); 12088 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12089 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12090 return InvalidOperands(Loc, LHS, RHS); 12091 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12092 // usage of the logical operators && and || with vectors in C. This 12093 // check could be notionally dropped. 12094 if (!getLangOpts().CPlusPlus && 12095 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12096 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12097 12098 return GetSignedVectorType(LHS.get()->getType()); 12099 } 12100 12101 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12102 SourceLocation Loc, 12103 bool IsCompAssign) { 12104 if (!IsCompAssign) { 12105 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12106 if (LHS.isInvalid()) 12107 return QualType(); 12108 } 12109 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12110 if (RHS.isInvalid()) 12111 return QualType(); 12112 12113 // For conversion purposes, we ignore any qualifiers. 12114 // For example, "const float" and "float" are equivalent. 12115 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12116 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12117 12118 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12119 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12120 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12121 12122 if (Context.hasSameType(LHSType, RHSType)) 12123 return LHSType; 12124 12125 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12126 // case we have to return InvalidOperands. 12127 ExprResult OriginalLHS = LHS; 12128 ExprResult OriginalRHS = RHS; 12129 if (LHSMatType && !RHSMatType) { 12130 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12131 if (!RHS.isInvalid()) 12132 return LHSType; 12133 12134 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12135 } 12136 12137 if (!LHSMatType && RHSMatType) { 12138 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12139 if (!LHS.isInvalid()) 12140 return RHSType; 12141 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12142 } 12143 12144 return InvalidOperands(Loc, LHS, RHS); 12145 } 12146 12147 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12148 SourceLocation Loc, 12149 bool IsCompAssign) { 12150 if (!IsCompAssign) { 12151 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12152 if (LHS.isInvalid()) 12153 return QualType(); 12154 } 12155 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12156 if (RHS.isInvalid()) 12157 return QualType(); 12158 12159 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12160 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12161 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12162 12163 if (LHSMatType && RHSMatType) { 12164 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12165 return InvalidOperands(Loc, LHS, RHS); 12166 12167 if (!Context.hasSameType(LHSMatType->getElementType(), 12168 RHSMatType->getElementType())) 12169 return InvalidOperands(Loc, LHS, RHS); 12170 12171 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12172 LHSMatType->getNumRows(), 12173 RHSMatType->getNumColumns()); 12174 } 12175 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12176 } 12177 12178 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12179 SourceLocation Loc, 12180 BinaryOperatorKind Opc) { 12181 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12182 12183 bool IsCompAssign = 12184 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12185 12186 if (LHS.get()->getType()->isVectorType() || 12187 RHS.get()->getType()->isVectorType()) { 12188 if (LHS.get()->getType()->hasIntegerRepresentation() && 12189 RHS.get()->getType()->hasIntegerRepresentation()) 12190 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12191 /*AllowBothBool*/true, 12192 /*AllowBoolConversions*/getLangOpts().ZVector); 12193 return InvalidOperands(Loc, LHS, RHS); 12194 } 12195 12196 if (Opc == BO_And) 12197 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12198 12199 if (LHS.get()->getType()->hasFloatingRepresentation() || 12200 RHS.get()->getType()->hasFloatingRepresentation()) 12201 return InvalidOperands(Loc, LHS, RHS); 12202 12203 ExprResult LHSResult = LHS, RHSResult = RHS; 12204 QualType compType = UsualArithmeticConversions( 12205 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12206 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12207 return QualType(); 12208 LHS = LHSResult.get(); 12209 RHS = RHSResult.get(); 12210 12211 if (Opc == BO_Xor) 12212 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12213 12214 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12215 return compType; 12216 return InvalidOperands(Loc, LHS, RHS); 12217 } 12218 12219 // C99 6.5.[13,14] 12220 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12221 SourceLocation Loc, 12222 BinaryOperatorKind Opc) { 12223 // Check vector operands differently. 12224 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12225 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12226 12227 bool EnumConstantInBoolContext = false; 12228 for (const ExprResult &HS : {LHS, RHS}) { 12229 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12230 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12231 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12232 EnumConstantInBoolContext = true; 12233 } 12234 } 12235 12236 if (EnumConstantInBoolContext) 12237 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12238 12239 // Diagnose cases where the user write a logical and/or but probably meant a 12240 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12241 // is a constant. 12242 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12243 !LHS.get()->getType()->isBooleanType() && 12244 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12245 // Don't warn in macros or template instantiations. 12246 !Loc.isMacroID() && !inTemplateInstantiation()) { 12247 // If the RHS can be constant folded, and if it constant folds to something 12248 // that isn't 0 or 1 (which indicate a potential logical operation that 12249 // happened to fold to true/false) then warn. 12250 // Parens on the RHS are ignored. 12251 Expr::EvalResult EVResult; 12252 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12253 llvm::APSInt Result = EVResult.Val.getInt(); 12254 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12255 !RHS.get()->getExprLoc().isMacroID()) || 12256 (Result != 0 && Result != 1)) { 12257 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12258 << RHS.get()->getSourceRange() 12259 << (Opc == BO_LAnd ? "&&" : "||"); 12260 // Suggest replacing the logical operator with the bitwise version 12261 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12262 << (Opc == BO_LAnd ? "&" : "|") 12263 << FixItHint::CreateReplacement(SourceRange( 12264 Loc, getLocForEndOfToken(Loc)), 12265 Opc == BO_LAnd ? "&" : "|"); 12266 if (Opc == BO_LAnd) 12267 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12268 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12269 << FixItHint::CreateRemoval( 12270 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12271 RHS.get()->getEndLoc())); 12272 } 12273 } 12274 } 12275 12276 if (!Context.getLangOpts().CPlusPlus) { 12277 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12278 // not operate on the built-in scalar and vector float types. 12279 if (Context.getLangOpts().OpenCL && 12280 Context.getLangOpts().OpenCLVersion < 120) { 12281 if (LHS.get()->getType()->isFloatingType() || 12282 RHS.get()->getType()->isFloatingType()) 12283 return InvalidOperands(Loc, LHS, RHS); 12284 } 12285 12286 LHS = UsualUnaryConversions(LHS.get()); 12287 if (LHS.isInvalid()) 12288 return QualType(); 12289 12290 RHS = UsualUnaryConversions(RHS.get()); 12291 if (RHS.isInvalid()) 12292 return QualType(); 12293 12294 if (!LHS.get()->getType()->isScalarType() || 12295 !RHS.get()->getType()->isScalarType()) 12296 return InvalidOperands(Loc, LHS, RHS); 12297 12298 return Context.IntTy; 12299 } 12300 12301 // The following is safe because we only use this method for 12302 // non-overloadable operands. 12303 12304 // C++ [expr.log.and]p1 12305 // C++ [expr.log.or]p1 12306 // The operands are both contextually converted to type bool. 12307 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12308 if (LHSRes.isInvalid()) 12309 return InvalidOperands(Loc, LHS, RHS); 12310 LHS = LHSRes; 12311 12312 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12313 if (RHSRes.isInvalid()) 12314 return InvalidOperands(Loc, LHS, RHS); 12315 RHS = RHSRes; 12316 12317 // C++ [expr.log.and]p2 12318 // C++ [expr.log.or]p2 12319 // The result is a bool. 12320 return Context.BoolTy; 12321 } 12322 12323 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12324 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12325 if (!ME) return false; 12326 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12327 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12328 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12329 if (!Base) return false; 12330 return Base->getMethodDecl() != nullptr; 12331 } 12332 12333 /// Is the given expression (which must be 'const') a reference to a 12334 /// variable which was originally non-const, but which has become 12335 /// 'const' due to being captured within a block? 12336 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12337 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12338 assert(E->isLValue() && E->getType().isConstQualified()); 12339 E = E->IgnoreParens(); 12340 12341 // Must be a reference to a declaration from an enclosing scope. 12342 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12343 if (!DRE) return NCCK_None; 12344 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12345 12346 // The declaration must be a variable which is not declared 'const'. 12347 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12348 if (!var) return NCCK_None; 12349 if (var->getType().isConstQualified()) return NCCK_None; 12350 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12351 12352 // Decide whether the first capture was for a block or a lambda. 12353 DeclContext *DC = S.CurContext, *Prev = nullptr; 12354 // Decide whether the first capture was for a block or a lambda. 12355 while (DC) { 12356 // For init-capture, it is possible that the variable belongs to the 12357 // template pattern of the current context. 12358 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12359 if (var->isInitCapture() && 12360 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12361 break; 12362 if (DC == var->getDeclContext()) 12363 break; 12364 Prev = DC; 12365 DC = DC->getParent(); 12366 } 12367 // Unless we have an init-capture, we've gone one step too far. 12368 if (!var->isInitCapture()) 12369 DC = Prev; 12370 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12371 } 12372 12373 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12374 Ty = Ty.getNonReferenceType(); 12375 if (IsDereference && Ty->isPointerType()) 12376 Ty = Ty->getPointeeType(); 12377 return !Ty.isConstQualified(); 12378 } 12379 12380 // Update err_typecheck_assign_const and note_typecheck_assign_const 12381 // when this enum is changed. 12382 enum { 12383 ConstFunction, 12384 ConstVariable, 12385 ConstMember, 12386 ConstMethod, 12387 NestedConstMember, 12388 ConstUnknown, // Keep as last element 12389 }; 12390 12391 /// Emit the "read-only variable not assignable" error and print notes to give 12392 /// more information about why the variable is not assignable, such as pointing 12393 /// to the declaration of a const variable, showing that a method is const, or 12394 /// that the function is returning a const reference. 12395 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12396 SourceLocation Loc) { 12397 SourceRange ExprRange = E->getSourceRange(); 12398 12399 // Only emit one error on the first const found. All other consts will emit 12400 // a note to the error. 12401 bool DiagnosticEmitted = false; 12402 12403 // Track if the current expression is the result of a dereference, and if the 12404 // next checked expression is the result of a dereference. 12405 bool IsDereference = false; 12406 bool NextIsDereference = false; 12407 12408 // Loop to process MemberExpr chains. 12409 while (true) { 12410 IsDereference = NextIsDereference; 12411 12412 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12413 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12414 NextIsDereference = ME->isArrow(); 12415 const ValueDecl *VD = ME->getMemberDecl(); 12416 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12417 // Mutable fields can be modified even if the class is const. 12418 if (Field->isMutable()) { 12419 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12420 break; 12421 } 12422 12423 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12424 if (!DiagnosticEmitted) { 12425 S.Diag(Loc, diag::err_typecheck_assign_const) 12426 << ExprRange << ConstMember << false /*static*/ << Field 12427 << Field->getType(); 12428 DiagnosticEmitted = true; 12429 } 12430 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12431 << ConstMember << false /*static*/ << Field << Field->getType() 12432 << Field->getSourceRange(); 12433 } 12434 E = ME->getBase(); 12435 continue; 12436 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12437 if (VDecl->getType().isConstQualified()) { 12438 if (!DiagnosticEmitted) { 12439 S.Diag(Loc, diag::err_typecheck_assign_const) 12440 << ExprRange << ConstMember << true /*static*/ << VDecl 12441 << VDecl->getType(); 12442 DiagnosticEmitted = true; 12443 } 12444 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12445 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12446 << VDecl->getSourceRange(); 12447 } 12448 // Static fields do not inherit constness from parents. 12449 break; 12450 } 12451 break; // End MemberExpr 12452 } else if (const ArraySubscriptExpr *ASE = 12453 dyn_cast<ArraySubscriptExpr>(E)) { 12454 E = ASE->getBase()->IgnoreParenImpCasts(); 12455 continue; 12456 } else if (const ExtVectorElementExpr *EVE = 12457 dyn_cast<ExtVectorElementExpr>(E)) { 12458 E = EVE->getBase()->IgnoreParenImpCasts(); 12459 continue; 12460 } 12461 break; 12462 } 12463 12464 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12465 // Function calls 12466 const FunctionDecl *FD = CE->getDirectCallee(); 12467 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12468 if (!DiagnosticEmitted) { 12469 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12470 << ConstFunction << FD; 12471 DiagnosticEmitted = true; 12472 } 12473 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12474 diag::note_typecheck_assign_const) 12475 << ConstFunction << FD << FD->getReturnType() 12476 << FD->getReturnTypeSourceRange(); 12477 } 12478 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12479 // Point to variable declaration. 12480 if (const ValueDecl *VD = DRE->getDecl()) { 12481 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12482 if (!DiagnosticEmitted) { 12483 S.Diag(Loc, diag::err_typecheck_assign_const) 12484 << ExprRange << ConstVariable << VD << VD->getType(); 12485 DiagnosticEmitted = true; 12486 } 12487 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12488 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12489 } 12490 } 12491 } else if (isa<CXXThisExpr>(E)) { 12492 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12493 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12494 if (MD->isConst()) { 12495 if (!DiagnosticEmitted) { 12496 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12497 << ConstMethod << MD; 12498 DiagnosticEmitted = true; 12499 } 12500 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12501 << ConstMethod << MD << MD->getSourceRange(); 12502 } 12503 } 12504 } 12505 } 12506 12507 if (DiagnosticEmitted) 12508 return; 12509 12510 // Can't determine a more specific message, so display the generic error. 12511 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12512 } 12513 12514 enum OriginalExprKind { 12515 OEK_Variable, 12516 OEK_Member, 12517 OEK_LValue 12518 }; 12519 12520 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12521 const RecordType *Ty, 12522 SourceLocation Loc, SourceRange Range, 12523 OriginalExprKind OEK, 12524 bool &DiagnosticEmitted) { 12525 std::vector<const RecordType *> RecordTypeList; 12526 RecordTypeList.push_back(Ty); 12527 unsigned NextToCheckIndex = 0; 12528 // We walk the record hierarchy breadth-first to ensure that we print 12529 // diagnostics in field nesting order. 12530 while (RecordTypeList.size() > NextToCheckIndex) { 12531 bool IsNested = NextToCheckIndex > 0; 12532 for (const FieldDecl *Field : 12533 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12534 // First, check every field for constness. 12535 QualType FieldTy = Field->getType(); 12536 if (FieldTy.isConstQualified()) { 12537 if (!DiagnosticEmitted) { 12538 S.Diag(Loc, diag::err_typecheck_assign_const) 12539 << Range << NestedConstMember << OEK << VD 12540 << IsNested << Field; 12541 DiagnosticEmitted = true; 12542 } 12543 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12544 << NestedConstMember << IsNested << Field 12545 << FieldTy << Field->getSourceRange(); 12546 } 12547 12548 // Then we append it to the list to check next in order. 12549 FieldTy = FieldTy.getCanonicalType(); 12550 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12551 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12552 RecordTypeList.push_back(FieldRecTy); 12553 } 12554 } 12555 ++NextToCheckIndex; 12556 } 12557 } 12558 12559 /// Emit an error for the case where a record we are trying to assign to has a 12560 /// const-qualified field somewhere in its hierarchy. 12561 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12562 SourceLocation Loc) { 12563 QualType Ty = E->getType(); 12564 assert(Ty->isRecordType() && "lvalue was not record?"); 12565 SourceRange Range = E->getSourceRange(); 12566 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12567 bool DiagEmitted = false; 12568 12569 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12570 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12571 Range, OEK_Member, DiagEmitted); 12572 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12573 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12574 Range, OEK_Variable, DiagEmitted); 12575 else 12576 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12577 Range, OEK_LValue, DiagEmitted); 12578 if (!DiagEmitted) 12579 DiagnoseConstAssignment(S, E, Loc); 12580 } 12581 12582 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12583 /// emit an error and return true. If so, return false. 12584 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12585 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12586 12587 S.CheckShadowingDeclModification(E, Loc); 12588 12589 SourceLocation OrigLoc = Loc; 12590 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12591 &Loc); 12592 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12593 IsLV = Expr::MLV_InvalidMessageExpression; 12594 if (IsLV == Expr::MLV_Valid) 12595 return false; 12596 12597 unsigned DiagID = 0; 12598 bool NeedType = false; 12599 switch (IsLV) { // C99 6.5.16p2 12600 case Expr::MLV_ConstQualified: 12601 // Use a specialized diagnostic when we're assigning to an object 12602 // from an enclosing function or block. 12603 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12604 if (NCCK == NCCK_Block) 12605 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12606 else 12607 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12608 break; 12609 } 12610 12611 // In ARC, use some specialized diagnostics for occasions where we 12612 // infer 'const'. These are always pseudo-strong variables. 12613 if (S.getLangOpts().ObjCAutoRefCount) { 12614 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12615 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12616 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12617 12618 // Use the normal diagnostic if it's pseudo-__strong but the 12619 // user actually wrote 'const'. 12620 if (var->isARCPseudoStrong() && 12621 (!var->getTypeSourceInfo() || 12622 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12623 // There are three pseudo-strong cases: 12624 // - self 12625 ObjCMethodDecl *method = S.getCurMethodDecl(); 12626 if (method && var == method->getSelfDecl()) { 12627 DiagID = method->isClassMethod() 12628 ? diag::err_typecheck_arc_assign_self_class_method 12629 : diag::err_typecheck_arc_assign_self; 12630 12631 // - Objective-C externally_retained attribute. 12632 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12633 isa<ParmVarDecl>(var)) { 12634 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12635 12636 // - fast enumeration variables 12637 } else { 12638 DiagID = diag::err_typecheck_arr_assign_enumeration; 12639 } 12640 12641 SourceRange Assign; 12642 if (Loc != OrigLoc) 12643 Assign = SourceRange(OrigLoc, OrigLoc); 12644 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12645 // We need to preserve the AST regardless, so migration tool 12646 // can do its job. 12647 return false; 12648 } 12649 } 12650 } 12651 12652 // If none of the special cases above are triggered, then this is a 12653 // simple const assignment. 12654 if (DiagID == 0) { 12655 DiagnoseConstAssignment(S, E, Loc); 12656 return true; 12657 } 12658 12659 break; 12660 case Expr::MLV_ConstAddrSpace: 12661 DiagnoseConstAssignment(S, E, Loc); 12662 return true; 12663 case Expr::MLV_ConstQualifiedField: 12664 DiagnoseRecursiveConstFields(S, E, Loc); 12665 return true; 12666 case Expr::MLV_ArrayType: 12667 case Expr::MLV_ArrayTemporary: 12668 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12669 NeedType = true; 12670 break; 12671 case Expr::MLV_NotObjectType: 12672 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12673 NeedType = true; 12674 break; 12675 case Expr::MLV_LValueCast: 12676 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12677 break; 12678 case Expr::MLV_Valid: 12679 llvm_unreachable("did not take early return for MLV_Valid"); 12680 case Expr::MLV_InvalidExpression: 12681 case Expr::MLV_MemberFunction: 12682 case Expr::MLV_ClassTemporary: 12683 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12684 break; 12685 case Expr::MLV_IncompleteType: 12686 case Expr::MLV_IncompleteVoidType: 12687 return S.RequireCompleteType(Loc, E->getType(), 12688 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12689 case Expr::MLV_DuplicateVectorComponents: 12690 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12691 break; 12692 case Expr::MLV_NoSetterProperty: 12693 llvm_unreachable("readonly properties should be processed differently"); 12694 case Expr::MLV_InvalidMessageExpression: 12695 DiagID = diag::err_readonly_message_assignment; 12696 break; 12697 case Expr::MLV_SubObjCPropertySetting: 12698 DiagID = diag::err_no_subobject_property_setting; 12699 break; 12700 } 12701 12702 SourceRange Assign; 12703 if (Loc != OrigLoc) 12704 Assign = SourceRange(OrigLoc, OrigLoc); 12705 if (NeedType) 12706 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12707 else 12708 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12709 return true; 12710 } 12711 12712 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12713 SourceLocation Loc, 12714 Sema &Sema) { 12715 if (Sema.inTemplateInstantiation()) 12716 return; 12717 if (Sema.isUnevaluatedContext()) 12718 return; 12719 if (Loc.isInvalid() || Loc.isMacroID()) 12720 return; 12721 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12722 return; 12723 12724 // C / C++ fields 12725 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12726 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12727 if (ML && MR) { 12728 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12729 return; 12730 const ValueDecl *LHSDecl = 12731 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12732 const ValueDecl *RHSDecl = 12733 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12734 if (LHSDecl != RHSDecl) 12735 return; 12736 if (LHSDecl->getType().isVolatileQualified()) 12737 return; 12738 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12739 if (RefTy->getPointeeType().isVolatileQualified()) 12740 return; 12741 12742 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12743 } 12744 12745 // Objective-C instance variables 12746 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12747 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12748 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12749 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12750 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12751 if (RL && RR && RL->getDecl() == RR->getDecl()) 12752 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12753 } 12754 } 12755 12756 // C99 6.5.16.1 12757 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12758 SourceLocation Loc, 12759 QualType CompoundType) { 12760 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12761 12762 // Verify that LHS is a modifiable lvalue, and emit error if not. 12763 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12764 return QualType(); 12765 12766 QualType LHSType = LHSExpr->getType(); 12767 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12768 CompoundType; 12769 // OpenCL v1.2 s6.1.1.1 p2: 12770 // The half data type can only be used to declare a pointer to a buffer that 12771 // contains half values 12772 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12773 LHSType->isHalfType()) { 12774 Diag(Loc, diag::err_opencl_half_load_store) << 1 12775 << LHSType.getUnqualifiedType(); 12776 return QualType(); 12777 } 12778 12779 AssignConvertType ConvTy; 12780 if (CompoundType.isNull()) { 12781 Expr *RHSCheck = RHS.get(); 12782 12783 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12784 12785 QualType LHSTy(LHSType); 12786 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12787 if (RHS.isInvalid()) 12788 return QualType(); 12789 // Special case of NSObject attributes on c-style pointer types. 12790 if (ConvTy == IncompatiblePointer && 12791 ((Context.isObjCNSObjectType(LHSType) && 12792 RHSType->isObjCObjectPointerType()) || 12793 (Context.isObjCNSObjectType(RHSType) && 12794 LHSType->isObjCObjectPointerType()))) 12795 ConvTy = Compatible; 12796 12797 if (ConvTy == Compatible && 12798 LHSType->isObjCObjectType()) 12799 Diag(Loc, diag::err_objc_object_assignment) 12800 << LHSType; 12801 12802 // If the RHS is a unary plus or minus, check to see if they = and + are 12803 // right next to each other. If so, the user may have typo'd "x =+ 4" 12804 // instead of "x += 4". 12805 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12806 RHSCheck = ICE->getSubExpr(); 12807 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12808 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12809 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12810 // Only if the two operators are exactly adjacent. 12811 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12812 // And there is a space or other character before the subexpr of the 12813 // unary +/-. We don't want to warn on "x=-1". 12814 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12815 UO->getSubExpr()->getBeginLoc().isFileID()) { 12816 Diag(Loc, diag::warn_not_compound_assign) 12817 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12818 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12819 } 12820 } 12821 12822 if (ConvTy == Compatible) { 12823 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12824 // Warn about retain cycles where a block captures the LHS, but 12825 // not if the LHS is a simple variable into which the block is 12826 // being stored...unless that variable can be captured by reference! 12827 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12828 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12829 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12830 checkRetainCycles(LHSExpr, RHS.get()); 12831 } 12832 12833 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12834 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12835 // It is safe to assign a weak reference into a strong variable. 12836 // Although this code can still have problems: 12837 // id x = self.weakProp; 12838 // id y = self.weakProp; 12839 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12840 // paths through the function. This should be revisited if 12841 // -Wrepeated-use-of-weak is made flow-sensitive. 12842 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12843 // variable, which will be valid for the current autorelease scope. 12844 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12845 RHS.get()->getBeginLoc())) 12846 getCurFunction()->markSafeWeakUse(RHS.get()); 12847 12848 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12849 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12850 } 12851 } 12852 } else { 12853 // Compound assignment "x += y" 12854 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12855 } 12856 12857 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12858 RHS.get(), AA_Assigning)) 12859 return QualType(); 12860 12861 CheckForNullPointerDereference(*this, LHSExpr); 12862 12863 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12864 if (CompoundType.isNull()) { 12865 // C++2a [expr.ass]p5: 12866 // A simple-assignment whose left operand is of a volatile-qualified 12867 // type is deprecated unless the assignment is either a discarded-value 12868 // expression or an unevaluated operand 12869 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12870 } else { 12871 // C++2a [expr.ass]p6: 12872 // [Compound-assignment] expressions are deprecated if E1 has 12873 // volatile-qualified type 12874 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12875 } 12876 } 12877 12878 // C99 6.5.16p3: The type of an assignment expression is the type of the 12879 // left operand unless the left operand has qualified type, in which case 12880 // it is the unqualified version of the type of the left operand. 12881 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12882 // is converted to the type of the assignment expression (above). 12883 // C++ 5.17p1: the type of the assignment expression is that of its left 12884 // operand. 12885 return (getLangOpts().CPlusPlus 12886 ? LHSType : LHSType.getUnqualifiedType()); 12887 } 12888 12889 // Only ignore explicit casts to void. 12890 static bool IgnoreCommaOperand(const Expr *E) { 12891 E = E->IgnoreParens(); 12892 12893 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12894 if (CE->getCastKind() == CK_ToVoid) { 12895 return true; 12896 } 12897 12898 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12899 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12900 CE->getSubExpr()->getType()->isDependentType()) { 12901 return true; 12902 } 12903 } 12904 12905 return false; 12906 } 12907 12908 // Look for instances where it is likely the comma operator is confused with 12909 // another operator. There is an explicit list of acceptable expressions for 12910 // the left hand side of the comma operator, otherwise emit a warning. 12911 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12912 // No warnings in macros 12913 if (Loc.isMacroID()) 12914 return; 12915 12916 // Don't warn in template instantiations. 12917 if (inTemplateInstantiation()) 12918 return; 12919 12920 // Scope isn't fine-grained enough to explicitly list the specific cases, so 12921 // instead, skip more than needed, then call back into here with the 12922 // CommaVisitor in SemaStmt.cpp. 12923 // The listed locations are the initialization and increment portions 12924 // of a for loop. The additional checks are on the condition of 12925 // if statements, do/while loops, and for loops. 12926 // Differences in scope flags for C89 mode requires the extra logic. 12927 const unsigned ForIncrementFlags = 12928 getLangOpts().C99 || getLangOpts().CPlusPlus 12929 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12930 : Scope::ContinueScope | Scope::BreakScope; 12931 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12932 const unsigned ScopeFlags = getCurScope()->getFlags(); 12933 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12934 (ScopeFlags & ForInitFlags) == ForInitFlags) 12935 return; 12936 12937 // If there are multiple comma operators used together, get the RHS of the 12938 // of the comma operator as the LHS. 12939 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12940 if (BO->getOpcode() != BO_Comma) 12941 break; 12942 LHS = BO->getRHS(); 12943 } 12944 12945 // Only allow some expressions on LHS to not warn. 12946 if (IgnoreCommaOperand(LHS)) 12947 return; 12948 12949 Diag(Loc, diag::warn_comma_operator); 12950 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12951 << LHS->getSourceRange() 12952 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12953 LangOpts.CPlusPlus ? "static_cast<void>(" 12954 : "(void)(") 12955 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12956 ")"); 12957 } 12958 12959 // C99 6.5.17 12960 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12961 SourceLocation Loc) { 12962 LHS = S.CheckPlaceholderExpr(LHS.get()); 12963 RHS = S.CheckPlaceholderExpr(RHS.get()); 12964 if (LHS.isInvalid() || RHS.isInvalid()) 12965 return QualType(); 12966 12967 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12968 // operands, but not unary promotions. 12969 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12970 12971 // So we treat the LHS as a ignored value, and in C++ we allow the 12972 // containing site to determine what should be done with the RHS. 12973 LHS = S.IgnoredValueConversions(LHS.get()); 12974 if (LHS.isInvalid()) 12975 return QualType(); 12976 12977 S.DiagnoseUnusedExprResult(LHS.get()); 12978 12979 if (!S.getLangOpts().CPlusPlus) { 12980 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12981 if (RHS.isInvalid()) 12982 return QualType(); 12983 if (!RHS.get()->getType()->isVoidType()) 12984 S.RequireCompleteType(Loc, RHS.get()->getType(), 12985 diag::err_incomplete_type); 12986 } 12987 12988 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12989 S.DiagnoseCommaOperator(LHS.get(), Loc); 12990 12991 return RHS.get()->getType(); 12992 } 12993 12994 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12995 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12996 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12997 ExprValueKind &VK, 12998 ExprObjectKind &OK, 12999 SourceLocation OpLoc, 13000 bool IsInc, bool IsPrefix) { 13001 if (Op->isTypeDependent()) 13002 return S.Context.DependentTy; 13003 13004 QualType ResType = Op->getType(); 13005 // Atomic types can be used for increment / decrement where the non-atomic 13006 // versions can, so ignore the _Atomic() specifier for the purpose of 13007 // checking. 13008 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13009 ResType = ResAtomicType->getValueType(); 13010 13011 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13012 13013 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13014 // Decrement of bool is not allowed. 13015 if (!IsInc) { 13016 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13017 return QualType(); 13018 } 13019 // Increment of bool sets it to true, but is deprecated. 13020 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13021 : diag::warn_increment_bool) 13022 << Op->getSourceRange(); 13023 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13024 // Error on enum increments and decrements in C++ mode 13025 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13026 return QualType(); 13027 } else if (ResType->isRealType()) { 13028 // OK! 13029 } else if (ResType->isPointerType()) { 13030 // C99 6.5.2.4p2, 6.5.6p2 13031 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13032 return QualType(); 13033 } else if (ResType->isObjCObjectPointerType()) { 13034 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13035 // Otherwise, we just need a complete type. 13036 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13037 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13038 return QualType(); 13039 } else if (ResType->isAnyComplexType()) { 13040 // C99 does not support ++/-- on complex types, we allow as an extension. 13041 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13042 << ResType << Op->getSourceRange(); 13043 } else if (ResType->isPlaceholderType()) { 13044 ExprResult PR = S.CheckPlaceholderExpr(Op); 13045 if (PR.isInvalid()) return QualType(); 13046 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13047 IsInc, IsPrefix); 13048 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13049 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13050 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13051 (ResType->castAs<VectorType>()->getVectorKind() != 13052 VectorType::AltiVecBool)) { 13053 // The z vector extensions allow ++ and -- for non-bool vectors. 13054 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13055 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13056 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13057 } else { 13058 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13059 << ResType << int(IsInc) << Op->getSourceRange(); 13060 return QualType(); 13061 } 13062 // At this point, we know we have a real, complex or pointer type. 13063 // Now make sure the operand is a modifiable lvalue. 13064 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13065 return QualType(); 13066 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13067 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13068 // An operand with volatile-qualified type is deprecated 13069 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13070 << IsInc << ResType; 13071 } 13072 // In C++, a prefix increment is the same type as the operand. Otherwise 13073 // (in C or with postfix), the increment is the unqualified type of the 13074 // operand. 13075 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13076 VK = VK_LValue; 13077 OK = Op->getObjectKind(); 13078 return ResType; 13079 } else { 13080 VK = VK_RValue; 13081 return ResType.getUnqualifiedType(); 13082 } 13083 } 13084 13085 13086 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13087 /// This routine allows us to typecheck complex/recursive expressions 13088 /// where the declaration is needed for type checking. We only need to 13089 /// handle cases when the expression references a function designator 13090 /// or is an lvalue. Here are some examples: 13091 /// - &(x) => x 13092 /// - &*****f => f for f a function designator. 13093 /// - &s.xx => s 13094 /// - &s.zz[1].yy -> s, if zz is an array 13095 /// - *(x + 1) -> x, if x is an array 13096 /// - &"123"[2] -> 0 13097 /// - & __real__ x -> x 13098 /// 13099 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13100 /// members. 13101 static ValueDecl *getPrimaryDecl(Expr *E) { 13102 switch (E->getStmtClass()) { 13103 case Stmt::DeclRefExprClass: 13104 return cast<DeclRefExpr>(E)->getDecl(); 13105 case Stmt::MemberExprClass: 13106 // If this is an arrow operator, the address is an offset from 13107 // the base's value, so the object the base refers to is 13108 // irrelevant. 13109 if (cast<MemberExpr>(E)->isArrow()) 13110 return nullptr; 13111 // Otherwise, the expression refers to a part of the base 13112 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13113 case Stmt::ArraySubscriptExprClass: { 13114 // FIXME: This code shouldn't be necessary! We should catch the implicit 13115 // promotion of register arrays earlier. 13116 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13117 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13118 if (ICE->getSubExpr()->getType()->isArrayType()) 13119 return getPrimaryDecl(ICE->getSubExpr()); 13120 } 13121 return nullptr; 13122 } 13123 case Stmt::UnaryOperatorClass: { 13124 UnaryOperator *UO = cast<UnaryOperator>(E); 13125 13126 switch(UO->getOpcode()) { 13127 case UO_Real: 13128 case UO_Imag: 13129 case UO_Extension: 13130 return getPrimaryDecl(UO->getSubExpr()); 13131 default: 13132 return nullptr; 13133 } 13134 } 13135 case Stmt::ParenExprClass: 13136 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13137 case Stmt::ImplicitCastExprClass: 13138 // If the result of an implicit cast is an l-value, we care about 13139 // the sub-expression; otherwise, the result here doesn't matter. 13140 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13141 case Stmt::CXXUuidofExprClass: 13142 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13143 default: 13144 return nullptr; 13145 } 13146 } 13147 13148 namespace { 13149 enum { 13150 AO_Bit_Field = 0, 13151 AO_Vector_Element = 1, 13152 AO_Property_Expansion = 2, 13153 AO_Register_Variable = 3, 13154 AO_Matrix_Element = 4, 13155 AO_No_Error = 5 13156 }; 13157 } 13158 /// Diagnose invalid operand for address of operations. 13159 /// 13160 /// \param Type The type of operand which cannot have its address taken. 13161 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13162 Expr *E, unsigned Type) { 13163 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13164 } 13165 13166 /// CheckAddressOfOperand - The operand of & must be either a function 13167 /// designator or an lvalue designating an object. If it is an lvalue, the 13168 /// object cannot be declared with storage class register or be a bit field. 13169 /// Note: The usual conversions are *not* applied to the operand of the & 13170 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13171 /// In C++, the operand might be an overloaded function name, in which case 13172 /// we allow the '&' but retain the overloaded-function type. 13173 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13174 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13175 if (PTy->getKind() == BuiltinType::Overload) { 13176 Expr *E = OrigOp.get()->IgnoreParens(); 13177 if (!isa<OverloadExpr>(E)) { 13178 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13179 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13180 << OrigOp.get()->getSourceRange(); 13181 return QualType(); 13182 } 13183 13184 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13185 if (isa<UnresolvedMemberExpr>(Ovl)) 13186 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13187 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13188 << OrigOp.get()->getSourceRange(); 13189 return QualType(); 13190 } 13191 13192 return Context.OverloadTy; 13193 } 13194 13195 if (PTy->getKind() == BuiltinType::UnknownAny) 13196 return Context.UnknownAnyTy; 13197 13198 if (PTy->getKind() == BuiltinType::BoundMember) { 13199 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13200 << OrigOp.get()->getSourceRange(); 13201 return QualType(); 13202 } 13203 13204 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13205 if (OrigOp.isInvalid()) return QualType(); 13206 } 13207 13208 if (OrigOp.get()->isTypeDependent()) 13209 return Context.DependentTy; 13210 13211 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13212 13213 // Make sure to ignore parentheses in subsequent checks 13214 Expr *op = OrigOp.get()->IgnoreParens(); 13215 13216 // In OpenCL captures for blocks called as lambda functions 13217 // are located in the private address space. Blocks used in 13218 // enqueue_kernel can be located in a different address space 13219 // depending on a vendor implementation. Thus preventing 13220 // taking an address of the capture to avoid invalid AS casts. 13221 if (LangOpts.OpenCL) { 13222 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13223 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13224 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13225 return QualType(); 13226 } 13227 } 13228 13229 if (getLangOpts().C99) { 13230 // Implement C99-only parts of addressof rules. 13231 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13232 if (uOp->getOpcode() == UO_Deref) 13233 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13234 // (assuming the deref expression is valid). 13235 return uOp->getSubExpr()->getType(); 13236 } 13237 // Technically, there should be a check for array subscript 13238 // expressions here, but the result of one is always an lvalue anyway. 13239 } 13240 ValueDecl *dcl = getPrimaryDecl(op); 13241 13242 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13243 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13244 op->getBeginLoc())) 13245 return QualType(); 13246 13247 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13248 unsigned AddressOfError = AO_No_Error; 13249 13250 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13251 bool sfinae = (bool)isSFINAEContext(); 13252 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13253 : diag::ext_typecheck_addrof_temporary) 13254 << op->getType() << op->getSourceRange(); 13255 if (sfinae) 13256 return QualType(); 13257 // Materialize the temporary as an lvalue so that we can take its address. 13258 OrigOp = op = 13259 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13260 } else if (isa<ObjCSelectorExpr>(op)) { 13261 return Context.getPointerType(op->getType()); 13262 } else if (lval == Expr::LV_MemberFunction) { 13263 // If it's an instance method, make a member pointer. 13264 // The expression must have exactly the form &A::foo. 13265 13266 // If the underlying expression isn't a decl ref, give up. 13267 if (!isa<DeclRefExpr>(op)) { 13268 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13269 << OrigOp.get()->getSourceRange(); 13270 return QualType(); 13271 } 13272 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13273 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13274 13275 // The id-expression was parenthesized. 13276 if (OrigOp.get() != DRE) { 13277 Diag(OpLoc, diag::err_parens_pointer_member_function) 13278 << OrigOp.get()->getSourceRange(); 13279 13280 // The method was named without a qualifier. 13281 } else if (!DRE->getQualifier()) { 13282 if (MD->getParent()->getName().empty()) 13283 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13284 << op->getSourceRange(); 13285 else { 13286 SmallString<32> Str; 13287 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13288 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13289 << op->getSourceRange() 13290 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13291 } 13292 } 13293 13294 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13295 if (isa<CXXDestructorDecl>(MD)) 13296 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13297 13298 QualType MPTy = Context.getMemberPointerType( 13299 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13300 // Under the MS ABI, lock down the inheritance model now. 13301 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13302 (void)isCompleteType(OpLoc, MPTy); 13303 return MPTy; 13304 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13305 // C99 6.5.3.2p1 13306 // The operand must be either an l-value or a function designator 13307 if (!op->getType()->isFunctionType()) { 13308 // Use a special diagnostic for loads from property references. 13309 if (isa<PseudoObjectExpr>(op)) { 13310 AddressOfError = AO_Property_Expansion; 13311 } else { 13312 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13313 << op->getType() << op->getSourceRange(); 13314 return QualType(); 13315 } 13316 } 13317 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13318 // The operand cannot be a bit-field 13319 AddressOfError = AO_Bit_Field; 13320 } else if (op->getObjectKind() == OK_VectorComponent) { 13321 // The operand cannot be an element of a vector 13322 AddressOfError = AO_Vector_Element; 13323 } else if (op->getObjectKind() == OK_MatrixComponent) { 13324 // The operand cannot be an element of a matrix. 13325 AddressOfError = AO_Matrix_Element; 13326 } else if (dcl) { // C99 6.5.3.2p1 13327 // We have an lvalue with a decl. Make sure the decl is not declared 13328 // with the register storage-class specifier. 13329 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13330 // in C++ it is not error to take address of a register 13331 // variable (c++03 7.1.1P3) 13332 if (vd->getStorageClass() == SC_Register && 13333 !getLangOpts().CPlusPlus) { 13334 AddressOfError = AO_Register_Variable; 13335 } 13336 } else if (isa<MSPropertyDecl>(dcl)) { 13337 AddressOfError = AO_Property_Expansion; 13338 } else if (isa<FunctionTemplateDecl>(dcl)) { 13339 return Context.OverloadTy; 13340 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13341 // Okay: we can take the address of a field. 13342 // Could be a pointer to member, though, if there is an explicit 13343 // scope qualifier for the class. 13344 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13345 DeclContext *Ctx = dcl->getDeclContext(); 13346 if (Ctx && Ctx->isRecord()) { 13347 if (dcl->getType()->isReferenceType()) { 13348 Diag(OpLoc, 13349 diag::err_cannot_form_pointer_to_member_of_reference_type) 13350 << dcl->getDeclName() << dcl->getType(); 13351 return QualType(); 13352 } 13353 13354 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13355 Ctx = Ctx->getParent(); 13356 13357 QualType MPTy = Context.getMemberPointerType( 13358 op->getType(), 13359 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13360 // Under the MS ABI, lock down the inheritance model now. 13361 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13362 (void)isCompleteType(OpLoc, MPTy); 13363 return MPTy; 13364 } 13365 } 13366 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13367 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13368 llvm_unreachable("Unknown/unexpected decl type"); 13369 } 13370 13371 if (AddressOfError != AO_No_Error) { 13372 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13373 return QualType(); 13374 } 13375 13376 if (lval == Expr::LV_IncompleteVoidType) { 13377 // Taking the address of a void variable is technically illegal, but we 13378 // allow it in cases which are otherwise valid. 13379 // Example: "extern void x; void* y = &x;". 13380 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13381 } 13382 13383 // If the operand has type "type", the result has type "pointer to type". 13384 if (op->getType()->isObjCObjectType()) 13385 return Context.getObjCObjectPointerType(op->getType()); 13386 13387 CheckAddressOfPackedMember(op); 13388 13389 return Context.getPointerType(op->getType()); 13390 } 13391 13392 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13393 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13394 if (!DRE) 13395 return; 13396 const Decl *D = DRE->getDecl(); 13397 if (!D) 13398 return; 13399 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13400 if (!Param) 13401 return; 13402 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13403 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13404 return; 13405 if (FunctionScopeInfo *FD = S.getCurFunction()) 13406 if (!FD->ModifiedNonNullParams.count(Param)) 13407 FD->ModifiedNonNullParams.insert(Param); 13408 } 13409 13410 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13411 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13412 SourceLocation OpLoc) { 13413 if (Op->isTypeDependent()) 13414 return S.Context.DependentTy; 13415 13416 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13417 if (ConvResult.isInvalid()) 13418 return QualType(); 13419 Op = ConvResult.get(); 13420 QualType OpTy = Op->getType(); 13421 QualType Result; 13422 13423 if (isa<CXXReinterpretCastExpr>(Op)) { 13424 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13425 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13426 Op->getSourceRange()); 13427 } 13428 13429 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13430 { 13431 Result = PT->getPointeeType(); 13432 } 13433 else if (const ObjCObjectPointerType *OPT = 13434 OpTy->getAs<ObjCObjectPointerType>()) 13435 Result = OPT->getPointeeType(); 13436 else { 13437 ExprResult PR = S.CheckPlaceholderExpr(Op); 13438 if (PR.isInvalid()) return QualType(); 13439 if (PR.get() != Op) 13440 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13441 } 13442 13443 if (Result.isNull()) { 13444 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13445 << OpTy << Op->getSourceRange(); 13446 return QualType(); 13447 } 13448 13449 // Note that per both C89 and C99, indirection is always legal, even if Result 13450 // is an incomplete type or void. It would be possible to warn about 13451 // dereferencing a void pointer, but it's completely well-defined, and such a 13452 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13453 // for pointers to 'void' but is fine for any other pointer type: 13454 // 13455 // C++ [expr.unary.op]p1: 13456 // [...] the expression to which [the unary * operator] is applied shall 13457 // be a pointer to an object type, or a pointer to a function type 13458 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13459 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13460 << OpTy << Op->getSourceRange(); 13461 13462 // Dereferences are usually l-values... 13463 VK = VK_LValue; 13464 13465 // ...except that certain expressions are never l-values in C. 13466 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13467 VK = VK_RValue; 13468 13469 return Result; 13470 } 13471 13472 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13473 BinaryOperatorKind Opc; 13474 switch (Kind) { 13475 default: llvm_unreachable("Unknown binop!"); 13476 case tok::periodstar: Opc = BO_PtrMemD; break; 13477 case tok::arrowstar: Opc = BO_PtrMemI; break; 13478 case tok::star: Opc = BO_Mul; break; 13479 case tok::slash: Opc = BO_Div; break; 13480 case tok::percent: Opc = BO_Rem; break; 13481 case tok::plus: Opc = BO_Add; break; 13482 case tok::minus: Opc = BO_Sub; break; 13483 case tok::lessless: Opc = BO_Shl; break; 13484 case tok::greatergreater: Opc = BO_Shr; break; 13485 case tok::lessequal: Opc = BO_LE; break; 13486 case tok::less: Opc = BO_LT; break; 13487 case tok::greaterequal: Opc = BO_GE; break; 13488 case tok::greater: Opc = BO_GT; break; 13489 case tok::exclaimequal: Opc = BO_NE; break; 13490 case tok::equalequal: Opc = BO_EQ; break; 13491 case tok::spaceship: Opc = BO_Cmp; break; 13492 case tok::amp: Opc = BO_And; break; 13493 case tok::caret: Opc = BO_Xor; break; 13494 case tok::pipe: Opc = BO_Or; break; 13495 case tok::ampamp: Opc = BO_LAnd; break; 13496 case tok::pipepipe: Opc = BO_LOr; break; 13497 case tok::equal: Opc = BO_Assign; break; 13498 case tok::starequal: Opc = BO_MulAssign; break; 13499 case tok::slashequal: Opc = BO_DivAssign; break; 13500 case tok::percentequal: Opc = BO_RemAssign; break; 13501 case tok::plusequal: Opc = BO_AddAssign; break; 13502 case tok::minusequal: Opc = BO_SubAssign; break; 13503 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13504 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13505 case tok::ampequal: Opc = BO_AndAssign; break; 13506 case tok::caretequal: Opc = BO_XorAssign; break; 13507 case tok::pipeequal: Opc = BO_OrAssign; break; 13508 case tok::comma: Opc = BO_Comma; break; 13509 } 13510 return Opc; 13511 } 13512 13513 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13514 tok::TokenKind Kind) { 13515 UnaryOperatorKind Opc; 13516 switch (Kind) { 13517 default: llvm_unreachable("Unknown unary op!"); 13518 case tok::plusplus: Opc = UO_PreInc; break; 13519 case tok::minusminus: Opc = UO_PreDec; break; 13520 case tok::amp: Opc = UO_AddrOf; break; 13521 case tok::star: Opc = UO_Deref; break; 13522 case tok::plus: Opc = UO_Plus; break; 13523 case tok::minus: Opc = UO_Minus; break; 13524 case tok::tilde: Opc = UO_Not; break; 13525 case tok::exclaim: Opc = UO_LNot; break; 13526 case tok::kw___real: Opc = UO_Real; break; 13527 case tok::kw___imag: Opc = UO_Imag; break; 13528 case tok::kw___extension__: Opc = UO_Extension; break; 13529 } 13530 return Opc; 13531 } 13532 13533 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13534 /// This warning suppressed in the event of macro expansions. 13535 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13536 SourceLocation OpLoc, bool IsBuiltin) { 13537 if (S.inTemplateInstantiation()) 13538 return; 13539 if (S.isUnevaluatedContext()) 13540 return; 13541 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13542 return; 13543 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13544 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13545 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13546 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13547 if (!LHSDeclRef || !RHSDeclRef || 13548 LHSDeclRef->getLocation().isMacroID() || 13549 RHSDeclRef->getLocation().isMacroID()) 13550 return; 13551 const ValueDecl *LHSDecl = 13552 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13553 const ValueDecl *RHSDecl = 13554 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13555 if (LHSDecl != RHSDecl) 13556 return; 13557 if (LHSDecl->getType().isVolatileQualified()) 13558 return; 13559 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13560 if (RefTy->getPointeeType().isVolatileQualified()) 13561 return; 13562 13563 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13564 : diag::warn_self_assignment_overloaded) 13565 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13566 << RHSExpr->getSourceRange(); 13567 } 13568 13569 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13570 /// is usually indicative of introspection within the Objective-C pointer. 13571 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13572 SourceLocation OpLoc) { 13573 if (!S.getLangOpts().ObjC) 13574 return; 13575 13576 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13577 const Expr *LHS = L.get(); 13578 const Expr *RHS = R.get(); 13579 13580 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13581 ObjCPointerExpr = LHS; 13582 OtherExpr = RHS; 13583 } 13584 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13585 ObjCPointerExpr = RHS; 13586 OtherExpr = LHS; 13587 } 13588 13589 // This warning is deliberately made very specific to reduce false 13590 // positives with logic that uses '&' for hashing. This logic mainly 13591 // looks for code trying to introspect into tagged pointers, which 13592 // code should generally never do. 13593 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13594 unsigned Diag = diag::warn_objc_pointer_masking; 13595 // Determine if we are introspecting the result of performSelectorXXX. 13596 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13597 // Special case messages to -performSelector and friends, which 13598 // can return non-pointer values boxed in a pointer value. 13599 // Some clients may wish to silence warnings in this subcase. 13600 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13601 Selector S = ME->getSelector(); 13602 StringRef SelArg0 = S.getNameForSlot(0); 13603 if (SelArg0.startswith("performSelector")) 13604 Diag = diag::warn_objc_pointer_masking_performSelector; 13605 } 13606 13607 S.Diag(OpLoc, Diag) 13608 << ObjCPointerExpr->getSourceRange(); 13609 } 13610 } 13611 13612 static NamedDecl *getDeclFromExpr(Expr *E) { 13613 if (!E) 13614 return nullptr; 13615 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13616 return DRE->getDecl(); 13617 if (auto *ME = dyn_cast<MemberExpr>(E)) 13618 return ME->getMemberDecl(); 13619 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13620 return IRE->getDecl(); 13621 return nullptr; 13622 } 13623 13624 // This helper function promotes a binary operator's operands (which are of a 13625 // half vector type) to a vector of floats and then truncates the result to 13626 // a vector of either half or short. 13627 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13628 BinaryOperatorKind Opc, QualType ResultTy, 13629 ExprValueKind VK, ExprObjectKind OK, 13630 bool IsCompAssign, SourceLocation OpLoc, 13631 FPOptions FPFeatures) { 13632 auto &Context = S.getASTContext(); 13633 assert((isVector(ResultTy, Context.HalfTy) || 13634 isVector(ResultTy, Context.ShortTy)) && 13635 "Result must be a vector of half or short"); 13636 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13637 isVector(RHS.get()->getType(), Context.HalfTy) && 13638 "both operands expected to be a half vector"); 13639 13640 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13641 QualType BinOpResTy = RHS.get()->getType(); 13642 13643 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13644 // change BinOpResTy to a vector of ints. 13645 if (isVector(ResultTy, Context.ShortTy)) 13646 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13647 13648 if (IsCompAssign) 13649 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13650 ResultTy, VK, OK, OpLoc, FPFeatures, 13651 BinOpResTy, BinOpResTy); 13652 13653 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13654 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13655 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13656 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13657 } 13658 13659 static std::pair<ExprResult, ExprResult> 13660 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13661 Expr *RHSExpr) { 13662 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13663 if (!S.getLangOpts().CPlusPlus) { 13664 // C cannot handle TypoExpr nodes on either side of a binop because it 13665 // doesn't handle dependent types properly, so make sure any TypoExprs have 13666 // been dealt with before checking the operands. 13667 LHS = S.CorrectDelayedTyposInExpr(LHS); 13668 RHS = S.CorrectDelayedTyposInExpr( 13669 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13670 [Opc, LHS](Expr *E) { 13671 if (Opc != BO_Assign) 13672 return ExprResult(E); 13673 // Avoid correcting the RHS to the same Expr as the LHS. 13674 Decl *D = getDeclFromExpr(E); 13675 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13676 }); 13677 } 13678 return std::make_pair(LHS, RHS); 13679 } 13680 13681 /// Returns true if conversion between vectors of halfs and vectors of floats 13682 /// is needed. 13683 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13684 Expr *E0, Expr *E1 = nullptr) { 13685 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13686 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13687 return false; 13688 13689 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13690 QualType Ty = E->IgnoreImplicit()->getType(); 13691 13692 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13693 // to vectors of floats. Although the element type of the vectors is __fp16, 13694 // the vectors shouldn't be treated as storage-only types. See the 13695 // discussion here: https://reviews.llvm.org/rG825235c140e7 13696 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13697 if (VT->getVectorKind() == VectorType::NeonVector) 13698 return false; 13699 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13700 } 13701 return false; 13702 }; 13703 13704 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13705 } 13706 13707 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13708 /// operator @p Opc at location @c TokLoc. This routine only supports 13709 /// built-in operations; ActOnBinOp handles overloaded operators. 13710 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13711 BinaryOperatorKind Opc, 13712 Expr *LHSExpr, Expr *RHSExpr) { 13713 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13714 // The syntax only allows initializer lists on the RHS of assignment, 13715 // so we don't need to worry about accepting invalid code for 13716 // non-assignment operators. 13717 // C++11 5.17p9: 13718 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13719 // of x = {} is x = T(). 13720 InitializationKind Kind = InitializationKind::CreateDirectList( 13721 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13722 InitializedEntity Entity = 13723 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13724 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13725 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13726 if (Init.isInvalid()) 13727 return Init; 13728 RHSExpr = Init.get(); 13729 } 13730 13731 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13732 QualType ResultTy; // Result type of the binary operator. 13733 // The following two variables are used for compound assignment operators 13734 QualType CompLHSTy; // Type of LHS after promotions for computation 13735 QualType CompResultTy; // Type of computation result 13736 ExprValueKind VK = VK_RValue; 13737 ExprObjectKind OK = OK_Ordinary; 13738 bool ConvertHalfVec = false; 13739 13740 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13741 if (!LHS.isUsable() || !RHS.isUsable()) 13742 return ExprError(); 13743 13744 if (getLangOpts().OpenCL) { 13745 QualType LHSTy = LHSExpr->getType(); 13746 QualType RHSTy = RHSExpr->getType(); 13747 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13748 // the ATOMIC_VAR_INIT macro. 13749 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13750 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13751 if (BO_Assign == Opc) 13752 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13753 else 13754 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13755 return ExprError(); 13756 } 13757 13758 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13759 // only with a builtin functions and therefore should be disallowed here. 13760 if (LHSTy->isImageType() || RHSTy->isImageType() || 13761 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13762 LHSTy->isPipeType() || RHSTy->isPipeType() || 13763 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13764 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13765 return ExprError(); 13766 } 13767 } 13768 13769 switch (Opc) { 13770 case BO_Assign: 13771 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13772 if (getLangOpts().CPlusPlus && 13773 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13774 VK = LHS.get()->getValueKind(); 13775 OK = LHS.get()->getObjectKind(); 13776 } 13777 if (!ResultTy.isNull()) { 13778 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13779 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13780 13781 // Avoid copying a block to the heap if the block is assigned to a local 13782 // auto variable that is declared in the same scope as the block. This 13783 // optimization is unsafe if the local variable is declared in an outer 13784 // scope. For example: 13785 // 13786 // BlockTy b; 13787 // { 13788 // b = ^{...}; 13789 // } 13790 // // It is unsafe to invoke the block here if it wasn't copied to the 13791 // // heap. 13792 // b(); 13793 13794 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13795 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13796 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13797 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13798 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13799 13800 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13801 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13802 NTCUC_Assignment, NTCUK_Copy); 13803 } 13804 RecordModifiableNonNullParam(*this, LHS.get()); 13805 break; 13806 case BO_PtrMemD: 13807 case BO_PtrMemI: 13808 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13809 Opc == BO_PtrMemI); 13810 break; 13811 case BO_Mul: 13812 case BO_Div: 13813 ConvertHalfVec = true; 13814 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13815 Opc == BO_Div); 13816 break; 13817 case BO_Rem: 13818 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13819 break; 13820 case BO_Add: 13821 ConvertHalfVec = true; 13822 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13823 break; 13824 case BO_Sub: 13825 ConvertHalfVec = true; 13826 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13827 break; 13828 case BO_Shl: 13829 case BO_Shr: 13830 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13831 break; 13832 case BO_LE: 13833 case BO_LT: 13834 case BO_GE: 13835 case BO_GT: 13836 ConvertHalfVec = true; 13837 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13838 break; 13839 case BO_EQ: 13840 case BO_NE: 13841 ConvertHalfVec = true; 13842 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13843 break; 13844 case BO_Cmp: 13845 ConvertHalfVec = true; 13846 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13847 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13848 break; 13849 case BO_And: 13850 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13851 LLVM_FALLTHROUGH; 13852 case BO_Xor: 13853 case BO_Or: 13854 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13855 break; 13856 case BO_LAnd: 13857 case BO_LOr: 13858 ConvertHalfVec = true; 13859 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13860 break; 13861 case BO_MulAssign: 13862 case BO_DivAssign: 13863 ConvertHalfVec = true; 13864 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13865 Opc == BO_DivAssign); 13866 CompLHSTy = CompResultTy; 13867 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13868 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13869 break; 13870 case BO_RemAssign: 13871 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13872 CompLHSTy = CompResultTy; 13873 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13874 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13875 break; 13876 case BO_AddAssign: 13877 ConvertHalfVec = true; 13878 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13879 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13880 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13881 break; 13882 case BO_SubAssign: 13883 ConvertHalfVec = true; 13884 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13885 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13886 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13887 break; 13888 case BO_ShlAssign: 13889 case BO_ShrAssign: 13890 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13891 CompLHSTy = CompResultTy; 13892 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13893 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13894 break; 13895 case BO_AndAssign: 13896 case BO_OrAssign: // fallthrough 13897 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13898 LLVM_FALLTHROUGH; 13899 case BO_XorAssign: 13900 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13901 CompLHSTy = CompResultTy; 13902 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13904 break; 13905 case BO_Comma: 13906 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13907 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13908 VK = RHS.get()->getValueKind(); 13909 OK = RHS.get()->getObjectKind(); 13910 } 13911 break; 13912 } 13913 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13914 return ExprError(); 13915 13916 // Some of the binary operations require promoting operands of half vector to 13917 // float vectors and truncating the result back to half vector. For now, we do 13918 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13919 // arm64). 13920 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13921 isVector(LHS.get()->getType(), Context.HalfTy) && 13922 "both sides are half vectors or neither sides are"); 13923 ConvertHalfVec = 13924 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13925 13926 // Check for array bounds violations for both sides of the BinaryOperator 13927 CheckArrayAccess(LHS.get()); 13928 CheckArrayAccess(RHS.get()); 13929 13930 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13931 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13932 &Context.Idents.get("object_setClass"), 13933 SourceLocation(), LookupOrdinaryName); 13934 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13935 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13936 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13937 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13938 "object_setClass(") 13939 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13940 ",") 13941 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13942 } 13943 else 13944 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13945 } 13946 else if (const ObjCIvarRefExpr *OIRE = 13947 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13948 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13949 13950 // Opc is not a compound assignment if CompResultTy is null. 13951 if (CompResultTy.isNull()) { 13952 if (ConvertHalfVec) 13953 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13954 OpLoc, CurFPFeatures); 13955 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13956 VK, OK, OpLoc, CurFPFeatures); 13957 } 13958 13959 // Handle compound assignments. 13960 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13961 OK_ObjCProperty) { 13962 VK = VK_LValue; 13963 OK = LHS.get()->getObjectKind(); 13964 } 13965 13966 // The LHS is not converted to the result type for fixed-point compound 13967 // assignment as the common type is computed on demand. Reset the CompLHSTy 13968 // to the LHS type we would have gotten after unary conversions. 13969 if (CompResultTy->isFixedPointType()) 13970 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13971 13972 if (ConvertHalfVec) 13973 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13974 OpLoc, CurFPFeatures); 13975 13976 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13977 ResultTy, VK, OK, OpLoc, CurFPFeatures, 13978 CompLHSTy, CompResultTy); 13979 } 13980 13981 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13982 /// operators are mixed in a way that suggests that the programmer forgot that 13983 /// comparison operators have higher precedence. The most typical example of 13984 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13985 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13986 SourceLocation OpLoc, Expr *LHSExpr, 13987 Expr *RHSExpr) { 13988 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13989 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13990 13991 // Check that one of the sides is a comparison operator and the other isn't. 13992 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13993 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13994 if (isLeftComp == isRightComp) 13995 return; 13996 13997 // Bitwise operations are sometimes used as eager logical ops. 13998 // Don't diagnose this. 13999 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14000 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14001 if (isLeftBitwise || isRightBitwise) 14002 return; 14003 14004 SourceRange DiagRange = isLeftComp 14005 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14006 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14007 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14008 SourceRange ParensRange = 14009 isLeftComp 14010 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14011 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14012 14013 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14014 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14015 SuggestParentheses(Self, OpLoc, 14016 Self.PDiag(diag::note_precedence_silence) << OpStr, 14017 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14018 SuggestParentheses(Self, OpLoc, 14019 Self.PDiag(diag::note_precedence_bitwise_first) 14020 << BinaryOperator::getOpcodeStr(Opc), 14021 ParensRange); 14022 } 14023 14024 /// It accepts a '&&' expr that is inside a '||' one. 14025 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14026 /// in parentheses. 14027 static void 14028 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14029 BinaryOperator *Bop) { 14030 assert(Bop->getOpcode() == BO_LAnd); 14031 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14032 << Bop->getSourceRange() << OpLoc; 14033 SuggestParentheses(Self, Bop->getOperatorLoc(), 14034 Self.PDiag(diag::note_precedence_silence) 14035 << Bop->getOpcodeStr(), 14036 Bop->getSourceRange()); 14037 } 14038 14039 /// Returns true if the given expression can be evaluated as a constant 14040 /// 'true'. 14041 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14042 bool Res; 14043 return !E->isValueDependent() && 14044 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14045 } 14046 14047 /// Returns true if the given expression can be evaluated as a constant 14048 /// 'false'. 14049 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14050 bool Res; 14051 return !E->isValueDependent() && 14052 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14053 } 14054 14055 /// Look for '&&' in the left hand of a '||' expr. 14056 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14057 Expr *LHSExpr, Expr *RHSExpr) { 14058 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14059 if (Bop->getOpcode() == BO_LAnd) { 14060 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14061 if (EvaluatesAsFalse(S, RHSExpr)) 14062 return; 14063 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14064 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14065 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14066 } else if (Bop->getOpcode() == BO_LOr) { 14067 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14068 // If it's "a || b && 1 || c" we didn't warn earlier for 14069 // "a || b && 1", but warn now. 14070 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14071 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14072 } 14073 } 14074 } 14075 } 14076 14077 /// Look for '&&' in the right hand of a '||' expr. 14078 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14079 Expr *LHSExpr, Expr *RHSExpr) { 14080 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14081 if (Bop->getOpcode() == BO_LAnd) { 14082 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14083 if (EvaluatesAsFalse(S, LHSExpr)) 14084 return; 14085 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14086 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14087 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14088 } 14089 } 14090 } 14091 14092 /// Look for bitwise op in the left or right hand of a bitwise op with 14093 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14094 /// the '&' expression in parentheses. 14095 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14096 SourceLocation OpLoc, Expr *SubExpr) { 14097 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14098 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14099 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14100 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14101 << Bop->getSourceRange() << OpLoc; 14102 SuggestParentheses(S, Bop->getOperatorLoc(), 14103 S.PDiag(diag::note_precedence_silence) 14104 << Bop->getOpcodeStr(), 14105 Bop->getSourceRange()); 14106 } 14107 } 14108 } 14109 14110 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14111 Expr *SubExpr, StringRef Shift) { 14112 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14113 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14114 StringRef Op = Bop->getOpcodeStr(); 14115 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14116 << Bop->getSourceRange() << OpLoc << Shift << Op; 14117 SuggestParentheses(S, Bop->getOperatorLoc(), 14118 S.PDiag(diag::note_precedence_silence) << Op, 14119 Bop->getSourceRange()); 14120 } 14121 } 14122 } 14123 14124 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14125 Expr *LHSExpr, Expr *RHSExpr) { 14126 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14127 if (!OCE) 14128 return; 14129 14130 FunctionDecl *FD = OCE->getDirectCallee(); 14131 if (!FD || !FD->isOverloadedOperator()) 14132 return; 14133 14134 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14135 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14136 return; 14137 14138 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14139 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14140 << (Kind == OO_LessLess); 14141 SuggestParentheses(S, OCE->getOperatorLoc(), 14142 S.PDiag(diag::note_precedence_silence) 14143 << (Kind == OO_LessLess ? "<<" : ">>"), 14144 OCE->getSourceRange()); 14145 SuggestParentheses( 14146 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14147 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14148 } 14149 14150 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14151 /// precedence. 14152 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14153 SourceLocation OpLoc, Expr *LHSExpr, 14154 Expr *RHSExpr){ 14155 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14156 if (BinaryOperator::isBitwiseOp(Opc)) 14157 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14158 14159 // Diagnose "arg1 & arg2 | arg3" 14160 if ((Opc == BO_Or || Opc == BO_Xor) && 14161 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14162 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14163 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14164 } 14165 14166 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14167 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14168 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14169 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14170 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14171 } 14172 14173 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14174 || Opc == BO_Shr) { 14175 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14176 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14177 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14178 } 14179 14180 // Warn on overloaded shift operators and comparisons, such as: 14181 // cout << 5 == 4; 14182 if (BinaryOperator::isComparisonOp(Opc)) 14183 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14184 } 14185 14186 // Binary Operators. 'Tok' is the token for the operator. 14187 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14188 tok::TokenKind Kind, 14189 Expr *LHSExpr, Expr *RHSExpr) { 14190 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14191 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14192 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14193 14194 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14195 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14196 14197 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14198 } 14199 14200 /// Build an overloaded binary operator expression in the given scope. 14201 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14202 BinaryOperatorKind Opc, 14203 Expr *LHS, Expr *RHS) { 14204 switch (Opc) { 14205 case BO_Assign: 14206 case BO_DivAssign: 14207 case BO_RemAssign: 14208 case BO_SubAssign: 14209 case BO_AndAssign: 14210 case BO_OrAssign: 14211 case BO_XorAssign: 14212 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14213 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14214 break; 14215 default: 14216 break; 14217 } 14218 14219 // Find all of the overloaded operators visible from this 14220 // point. We perform both an operator-name lookup from the local 14221 // scope and an argument-dependent lookup based on the types of 14222 // the arguments. 14223 UnresolvedSet<16> Functions; 14224 OverloadedOperatorKind OverOp 14225 = BinaryOperator::getOverloadedOperator(Opc); 14226 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 14227 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 14228 RHS->getType(), Functions); 14229 14230 // In C++20 onwards, we may have a second operator to look up. 14231 if (S.getLangOpts().CPlusPlus20) { 14232 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14233 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 14234 RHS->getType(), Functions); 14235 } 14236 14237 // Build the (potentially-overloaded, potentially-dependent) 14238 // binary operation. 14239 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14240 } 14241 14242 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14243 BinaryOperatorKind Opc, 14244 Expr *LHSExpr, Expr *RHSExpr) { 14245 ExprResult LHS, RHS; 14246 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14247 if (!LHS.isUsable() || !RHS.isUsable()) 14248 return ExprError(); 14249 LHSExpr = LHS.get(); 14250 RHSExpr = RHS.get(); 14251 14252 // We want to end up calling one of checkPseudoObjectAssignment 14253 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14254 // both expressions are overloadable or either is type-dependent), 14255 // or CreateBuiltinBinOp (in any other case). We also want to get 14256 // any placeholder types out of the way. 14257 14258 // Handle pseudo-objects in the LHS. 14259 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14260 // Assignments with a pseudo-object l-value need special analysis. 14261 if (pty->getKind() == BuiltinType::PseudoObject && 14262 BinaryOperator::isAssignmentOp(Opc)) 14263 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14264 14265 // Don't resolve overloads if the other type is overloadable. 14266 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14267 // We can't actually test that if we still have a placeholder, 14268 // though. Fortunately, none of the exceptions we see in that 14269 // code below are valid when the LHS is an overload set. Note 14270 // that an overload set can be dependently-typed, but it never 14271 // instantiates to having an overloadable type. 14272 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14273 if (resolvedRHS.isInvalid()) return ExprError(); 14274 RHSExpr = resolvedRHS.get(); 14275 14276 if (RHSExpr->isTypeDependent() || 14277 RHSExpr->getType()->isOverloadableType()) 14278 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14279 } 14280 14281 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14282 // template, diagnose the missing 'template' keyword instead of diagnosing 14283 // an invalid use of a bound member function. 14284 // 14285 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14286 // to C++1z [over.over]/1.4, but we already checked for that case above. 14287 if (Opc == BO_LT && inTemplateInstantiation() && 14288 (pty->getKind() == BuiltinType::BoundMember || 14289 pty->getKind() == BuiltinType::Overload)) { 14290 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14291 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14292 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14293 return isa<FunctionTemplateDecl>(ND); 14294 })) { 14295 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14296 : OE->getNameLoc(), 14297 diag::err_template_kw_missing) 14298 << OE->getName().getAsString() << ""; 14299 return ExprError(); 14300 } 14301 } 14302 14303 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14304 if (LHS.isInvalid()) return ExprError(); 14305 LHSExpr = LHS.get(); 14306 } 14307 14308 // Handle pseudo-objects in the RHS. 14309 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14310 // An overload in the RHS can potentially be resolved by the type 14311 // being assigned to. 14312 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14313 if (getLangOpts().CPlusPlus && 14314 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14315 LHSExpr->getType()->isOverloadableType())) 14316 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14317 14318 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14319 } 14320 14321 // Don't resolve overloads if the other type is overloadable. 14322 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14323 LHSExpr->getType()->isOverloadableType()) 14324 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14325 14326 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14327 if (!resolvedRHS.isUsable()) return ExprError(); 14328 RHSExpr = resolvedRHS.get(); 14329 } 14330 14331 if (getLangOpts().CPlusPlus) { 14332 // If either expression is type-dependent, always build an 14333 // overloaded op. 14334 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14335 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14336 14337 // Otherwise, build an overloaded op if either expression has an 14338 // overloadable type. 14339 if (LHSExpr->getType()->isOverloadableType() || 14340 RHSExpr->getType()->isOverloadableType()) 14341 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14342 } 14343 14344 // Build a built-in binary operation. 14345 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14346 } 14347 14348 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14349 if (T.isNull() || T->isDependentType()) 14350 return false; 14351 14352 if (!T->isPromotableIntegerType()) 14353 return true; 14354 14355 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14356 } 14357 14358 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14359 UnaryOperatorKind Opc, 14360 Expr *InputExpr) { 14361 ExprResult Input = InputExpr; 14362 ExprValueKind VK = VK_RValue; 14363 ExprObjectKind OK = OK_Ordinary; 14364 QualType resultType; 14365 bool CanOverflow = false; 14366 14367 bool ConvertHalfVec = false; 14368 if (getLangOpts().OpenCL) { 14369 QualType Ty = InputExpr->getType(); 14370 // The only legal unary operation for atomics is '&'. 14371 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14372 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14373 // only with a builtin functions and therefore should be disallowed here. 14374 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14375 || Ty->isBlockPointerType())) { 14376 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14377 << InputExpr->getType() 14378 << Input.get()->getSourceRange()); 14379 } 14380 } 14381 14382 switch (Opc) { 14383 case UO_PreInc: 14384 case UO_PreDec: 14385 case UO_PostInc: 14386 case UO_PostDec: 14387 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14388 OpLoc, 14389 Opc == UO_PreInc || 14390 Opc == UO_PostInc, 14391 Opc == UO_PreInc || 14392 Opc == UO_PreDec); 14393 CanOverflow = isOverflowingIntegerType(Context, resultType); 14394 break; 14395 case UO_AddrOf: 14396 resultType = CheckAddressOfOperand(Input, OpLoc); 14397 CheckAddressOfNoDeref(InputExpr); 14398 RecordModifiableNonNullParam(*this, InputExpr); 14399 break; 14400 case UO_Deref: { 14401 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14402 if (Input.isInvalid()) return ExprError(); 14403 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14404 break; 14405 } 14406 case UO_Plus: 14407 case UO_Minus: 14408 CanOverflow = Opc == UO_Minus && 14409 isOverflowingIntegerType(Context, Input.get()->getType()); 14410 Input = UsualUnaryConversions(Input.get()); 14411 if (Input.isInvalid()) return ExprError(); 14412 // Unary plus and minus require promoting an operand of half vector to a 14413 // float vector and truncating the result back to a half vector. For now, we 14414 // do this only when HalfArgsAndReturns is set (that is, when the target is 14415 // arm or arm64). 14416 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14417 14418 // If the operand is a half vector, promote it to a float vector. 14419 if (ConvertHalfVec) 14420 Input = convertVector(Input.get(), Context.FloatTy, *this); 14421 resultType = Input.get()->getType(); 14422 if (resultType->isDependentType()) 14423 break; 14424 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14425 break; 14426 else if (resultType->isVectorType() && 14427 // The z vector extensions don't allow + or - with bool vectors. 14428 (!Context.getLangOpts().ZVector || 14429 resultType->castAs<VectorType>()->getVectorKind() != 14430 VectorType::AltiVecBool)) 14431 break; 14432 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14433 Opc == UO_Plus && 14434 resultType->isPointerType()) 14435 break; 14436 14437 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14438 << resultType << Input.get()->getSourceRange()); 14439 14440 case UO_Not: // bitwise complement 14441 Input = UsualUnaryConversions(Input.get()); 14442 if (Input.isInvalid()) 14443 return ExprError(); 14444 resultType = Input.get()->getType(); 14445 if (resultType->isDependentType()) 14446 break; 14447 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14448 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14449 // C99 does not support '~' for complex conjugation. 14450 Diag(OpLoc, diag::ext_integer_complement_complex) 14451 << resultType << Input.get()->getSourceRange(); 14452 else if (resultType->hasIntegerRepresentation()) 14453 break; 14454 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14455 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14456 // on vector float types. 14457 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14458 if (!T->isIntegerType()) 14459 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14460 << resultType << Input.get()->getSourceRange()); 14461 } else { 14462 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14463 << resultType << Input.get()->getSourceRange()); 14464 } 14465 break; 14466 14467 case UO_LNot: // logical negation 14468 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14469 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14470 if (Input.isInvalid()) return ExprError(); 14471 resultType = Input.get()->getType(); 14472 14473 // Though we still have to promote half FP to float... 14474 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14475 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14476 resultType = Context.FloatTy; 14477 } 14478 14479 if (resultType->isDependentType()) 14480 break; 14481 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14482 // C99 6.5.3.3p1: ok, fallthrough; 14483 if (Context.getLangOpts().CPlusPlus) { 14484 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14485 // operand contextually converted to bool. 14486 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14487 ScalarTypeToBooleanCastKind(resultType)); 14488 } else if (Context.getLangOpts().OpenCL && 14489 Context.getLangOpts().OpenCLVersion < 120) { 14490 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14491 // operate on scalar float types. 14492 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14493 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14494 << resultType << Input.get()->getSourceRange()); 14495 } 14496 } else if (resultType->isExtVectorType()) { 14497 if (Context.getLangOpts().OpenCL && 14498 Context.getLangOpts().OpenCLVersion < 120 && 14499 !Context.getLangOpts().OpenCLCPlusPlus) { 14500 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14501 // operate on vector float types. 14502 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14503 if (!T->isIntegerType()) 14504 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14505 << resultType << Input.get()->getSourceRange()); 14506 } 14507 // Vector logical not returns the signed variant of the operand type. 14508 resultType = GetSignedVectorType(resultType); 14509 break; 14510 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14511 const VectorType *VTy = resultType->castAs<VectorType>(); 14512 if (VTy->getVectorKind() != VectorType::GenericVector) 14513 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14514 << resultType << Input.get()->getSourceRange()); 14515 14516 // Vector logical not returns the signed variant of the operand type. 14517 resultType = GetSignedVectorType(resultType); 14518 break; 14519 } else { 14520 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14521 << resultType << Input.get()->getSourceRange()); 14522 } 14523 14524 // LNot always has type int. C99 6.5.3.3p5. 14525 // In C++, it's bool. C++ 5.3.1p8 14526 resultType = Context.getLogicalOperationType(); 14527 break; 14528 case UO_Real: 14529 case UO_Imag: 14530 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14531 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14532 // complex l-values to ordinary l-values and all other values to r-values. 14533 if (Input.isInvalid()) return ExprError(); 14534 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14535 if (Input.get()->getValueKind() != VK_RValue && 14536 Input.get()->getObjectKind() == OK_Ordinary) 14537 VK = Input.get()->getValueKind(); 14538 } else if (!getLangOpts().CPlusPlus) { 14539 // In C, a volatile scalar is read by __imag. In C++, it is not. 14540 Input = DefaultLvalueConversion(Input.get()); 14541 } 14542 break; 14543 case UO_Extension: 14544 resultType = Input.get()->getType(); 14545 VK = Input.get()->getValueKind(); 14546 OK = Input.get()->getObjectKind(); 14547 break; 14548 case UO_Coawait: 14549 // It's unnecessary to represent the pass-through operator co_await in the 14550 // AST; just return the input expression instead. 14551 assert(!Input.get()->getType()->isDependentType() && 14552 "the co_await expression must be non-dependant before " 14553 "building operator co_await"); 14554 return Input; 14555 } 14556 if (resultType.isNull() || Input.isInvalid()) 14557 return ExprError(); 14558 14559 // Check for array bounds violations in the operand of the UnaryOperator, 14560 // except for the '*' and '&' operators that have to be handled specially 14561 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14562 // that are explicitly defined as valid by the standard). 14563 if (Opc != UO_AddrOf && Opc != UO_Deref) 14564 CheckArrayAccess(Input.get()); 14565 14566 auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, 14567 OK, OpLoc, CanOverflow, CurFPFeatures); 14568 14569 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14570 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14571 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14572 14573 // Convert the result back to a half vector. 14574 if (ConvertHalfVec) 14575 return convertVector(UO, Context.HalfTy, *this); 14576 return UO; 14577 } 14578 14579 /// Determine whether the given expression is a qualified member 14580 /// access expression, of a form that could be turned into a pointer to member 14581 /// with the address-of operator. 14582 bool Sema::isQualifiedMemberAccess(Expr *E) { 14583 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14584 if (!DRE->getQualifier()) 14585 return false; 14586 14587 ValueDecl *VD = DRE->getDecl(); 14588 if (!VD->isCXXClassMember()) 14589 return false; 14590 14591 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14592 return true; 14593 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14594 return Method->isInstance(); 14595 14596 return false; 14597 } 14598 14599 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14600 if (!ULE->getQualifier()) 14601 return false; 14602 14603 for (NamedDecl *D : ULE->decls()) { 14604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14605 if (Method->isInstance()) 14606 return true; 14607 } else { 14608 // Overload set does not contain methods. 14609 break; 14610 } 14611 } 14612 14613 return false; 14614 } 14615 14616 return false; 14617 } 14618 14619 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14620 UnaryOperatorKind Opc, Expr *Input) { 14621 // First things first: handle placeholders so that the 14622 // overloaded-operator check considers the right type. 14623 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14624 // Increment and decrement of pseudo-object references. 14625 if (pty->getKind() == BuiltinType::PseudoObject && 14626 UnaryOperator::isIncrementDecrementOp(Opc)) 14627 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14628 14629 // extension is always a builtin operator. 14630 if (Opc == UO_Extension) 14631 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14632 14633 // & gets special logic for several kinds of placeholder. 14634 // The builtin code knows what to do. 14635 if (Opc == UO_AddrOf && 14636 (pty->getKind() == BuiltinType::Overload || 14637 pty->getKind() == BuiltinType::UnknownAny || 14638 pty->getKind() == BuiltinType::BoundMember)) 14639 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14640 14641 // Anything else needs to be handled now. 14642 ExprResult Result = CheckPlaceholderExpr(Input); 14643 if (Result.isInvalid()) return ExprError(); 14644 Input = Result.get(); 14645 } 14646 14647 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14648 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14649 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14650 // Find all of the overloaded operators visible from this 14651 // point. We perform both an operator-name lookup from the local 14652 // scope and an argument-dependent lookup based on the types of 14653 // the arguments. 14654 UnresolvedSet<16> Functions; 14655 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14656 if (S && OverOp != OO_None) 14657 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14658 Functions); 14659 14660 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14661 } 14662 14663 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14664 } 14665 14666 // Unary Operators. 'Tok' is the token for the operator. 14667 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14668 tok::TokenKind Op, Expr *Input) { 14669 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14670 } 14671 14672 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14673 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14674 LabelDecl *TheDecl) { 14675 TheDecl->markUsed(Context); 14676 // Create the AST node. The address of a label always has type 'void*'. 14677 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14678 Context.getPointerType(Context.VoidTy)); 14679 } 14680 14681 void Sema::ActOnStartStmtExpr() { 14682 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14683 } 14684 14685 void Sema::ActOnStmtExprError() { 14686 // Note that function is also called by TreeTransform when leaving a 14687 // StmtExpr scope without rebuilding anything. 14688 14689 DiscardCleanupsInEvaluationContext(); 14690 PopExpressionEvaluationContext(); 14691 } 14692 14693 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14694 SourceLocation RPLoc) { 14695 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14696 } 14697 14698 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14699 SourceLocation RPLoc, unsigned TemplateDepth) { 14700 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14701 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14702 14703 if (hasAnyUnrecoverableErrorsInThisFunction()) 14704 DiscardCleanupsInEvaluationContext(); 14705 assert(!Cleanup.exprNeedsCleanups() && 14706 "cleanups within StmtExpr not correctly bound!"); 14707 PopExpressionEvaluationContext(); 14708 14709 // FIXME: there are a variety of strange constraints to enforce here, for 14710 // example, it is not possible to goto into a stmt expression apparently. 14711 // More semantic analysis is needed. 14712 14713 // If there are sub-stmts in the compound stmt, take the type of the last one 14714 // as the type of the stmtexpr. 14715 QualType Ty = Context.VoidTy; 14716 bool StmtExprMayBindToTemp = false; 14717 if (!Compound->body_empty()) { 14718 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14719 if (const auto *LastStmt = 14720 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14721 if (const Expr *Value = LastStmt->getExprStmt()) { 14722 StmtExprMayBindToTemp = true; 14723 Ty = Value->getType(); 14724 } 14725 } 14726 } 14727 14728 // FIXME: Check that expression type is complete/non-abstract; statement 14729 // expressions are not lvalues. 14730 Expr *ResStmtExpr = 14731 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14732 if (StmtExprMayBindToTemp) 14733 return MaybeBindToTemporary(ResStmtExpr); 14734 return ResStmtExpr; 14735 } 14736 14737 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14738 if (ER.isInvalid()) 14739 return ExprError(); 14740 14741 // Do function/array conversion on the last expression, but not 14742 // lvalue-to-rvalue. However, initialize an unqualified type. 14743 ER = DefaultFunctionArrayConversion(ER.get()); 14744 if (ER.isInvalid()) 14745 return ExprError(); 14746 Expr *E = ER.get(); 14747 14748 if (E->isTypeDependent()) 14749 return E; 14750 14751 // In ARC, if the final expression ends in a consume, splice 14752 // the consume out and bind it later. In the alternate case 14753 // (when dealing with a retainable type), the result 14754 // initialization will create a produce. In both cases the 14755 // result will be +1, and we'll need to balance that out with 14756 // a bind. 14757 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14758 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14759 return Cast->getSubExpr(); 14760 14761 // FIXME: Provide a better location for the initialization. 14762 return PerformCopyInitialization( 14763 InitializedEntity::InitializeStmtExprResult( 14764 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14765 SourceLocation(), E); 14766 } 14767 14768 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14769 TypeSourceInfo *TInfo, 14770 ArrayRef<OffsetOfComponent> Components, 14771 SourceLocation RParenLoc) { 14772 QualType ArgTy = TInfo->getType(); 14773 bool Dependent = ArgTy->isDependentType(); 14774 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14775 14776 // We must have at least one component that refers to the type, and the first 14777 // one is known to be a field designator. Verify that the ArgTy represents 14778 // a struct/union/class. 14779 if (!Dependent && !ArgTy->isRecordType()) 14780 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14781 << ArgTy << TypeRange); 14782 14783 // Type must be complete per C99 7.17p3 because a declaring a variable 14784 // with an incomplete type would be ill-formed. 14785 if (!Dependent 14786 && RequireCompleteType(BuiltinLoc, ArgTy, 14787 diag::err_offsetof_incomplete_type, TypeRange)) 14788 return ExprError(); 14789 14790 bool DidWarnAboutNonPOD = false; 14791 QualType CurrentType = ArgTy; 14792 SmallVector<OffsetOfNode, 4> Comps; 14793 SmallVector<Expr*, 4> Exprs; 14794 for (const OffsetOfComponent &OC : Components) { 14795 if (OC.isBrackets) { 14796 // Offset of an array sub-field. TODO: Should we allow vector elements? 14797 if (!CurrentType->isDependentType()) { 14798 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14799 if(!AT) 14800 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14801 << CurrentType); 14802 CurrentType = AT->getElementType(); 14803 } else 14804 CurrentType = Context.DependentTy; 14805 14806 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14807 if (IdxRval.isInvalid()) 14808 return ExprError(); 14809 Expr *Idx = IdxRval.get(); 14810 14811 // The expression must be an integral expression. 14812 // FIXME: An integral constant expression? 14813 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14814 !Idx->getType()->isIntegerType()) 14815 return ExprError( 14816 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14817 << Idx->getSourceRange()); 14818 14819 // Record this array index. 14820 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14821 Exprs.push_back(Idx); 14822 continue; 14823 } 14824 14825 // Offset of a field. 14826 if (CurrentType->isDependentType()) { 14827 // We have the offset of a field, but we can't look into the dependent 14828 // type. Just record the identifier of the field. 14829 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14830 CurrentType = Context.DependentTy; 14831 continue; 14832 } 14833 14834 // We need to have a complete type to look into. 14835 if (RequireCompleteType(OC.LocStart, CurrentType, 14836 diag::err_offsetof_incomplete_type)) 14837 return ExprError(); 14838 14839 // Look for the designated field. 14840 const RecordType *RC = CurrentType->getAs<RecordType>(); 14841 if (!RC) 14842 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14843 << CurrentType); 14844 RecordDecl *RD = RC->getDecl(); 14845 14846 // C++ [lib.support.types]p5: 14847 // The macro offsetof accepts a restricted set of type arguments in this 14848 // International Standard. type shall be a POD structure or a POD union 14849 // (clause 9). 14850 // C++11 [support.types]p4: 14851 // If type is not a standard-layout class (Clause 9), the results are 14852 // undefined. 14853 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14854 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14855 unsigned DiagID = 14856 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14857 : diag::ext_offsetof_non_pod_type; 14858 14859 if (!IsSafe && !DidWarnAboutNonPOD && 14860 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14861 PDiag(DiagID) 14862 << SourceRange(Components[0].LocStart, OC.LocEnd) 14863 << CurrentType)) 14864 DidWarnAboutNonPOD = true; 14865 } 14866 14867 // Look for the field. 14868 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14869 LookupQualifiedName(R, RD); 14870 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14871 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14872 if (!MemberDecl) { 14873 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14874 MemberDecl = IndirectMemberDecl->getAnonField(); 14875 } 14876 14877 if (!MemberDecl) 14878 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14879 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14880 OC.LocEnd)); 14881 14882 // C99 7.17p3: 14883 // (If the specified member is a bit-field, the behavior is undefined.) 14884 // 14885 // We diagnose this as an error. 14886 if (MemberDecl->isBitField()) { 14887 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14888 << MemberDecl->getDeclName() 14889 << SourceRange(BuiltinLoc, RParenLoc); 14890 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14891 return ExprError(); 14892 } 14893 14894 RecordDecl *Parent = MemberDecl->getParent(); 14895 if (IndirectMemberDecl) 14896 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14897 14898 // If the member was found in a base class, introduce OffsetOfNodes for 14899 // the base class indirections. 14900 CXXBasePaths Paths; 14901 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14902 Paths)) { 14903 if (Paths.getDetectedVirtual()) { 14904 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14905 << MemberDecl->getDeclName() 14906 << SourceRange(BuiltinLoc, RParenLoc); 14907 return ExprError(); 14908 } 14909 14910 CXXBasePath &Path = Paths.front(); 14911 for (const CXXBasePathElement &B : Path) 14912 Comps.push_back(OffsetOfNode(B.Base)); 14913 } 14914 14915 if (IndirectMemberDecl) { 14916 for (auto *FI : IndirectMemberDecl->chain()) { 14917 assert(isa<FieldDecl>(FI)); 14918 Comps.push_back(OffsetOfNode(OC.LocStart, 14919 cast<FieldDecl>(FI), OC.LocEnd)); 14920 } 14921 } else 14922 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14923 14924 CurrentType = MemberDecl->getType().getNonReferenceType(); 14925 } 14926 14927 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14928 Comps, Exprs, RParenLoc); 14929 } 14930 14931 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14932 SourceLocation BuiltinLoc, 14933 SourceLocation TypeLoc, 14934 ParsedType ParsedArgTy, 14935 ArrayRef<OffsetOfComponent> Components, 14936 SourceLocation RParenLoc) { 14937 14938 TypeSourceInfo *ArgTInfo; 14939 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14940 if (ArgTy.isNull()) 14941 return ExprError(); 14942 14943 if (!ArgTInfo) 14944 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14945 14946 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14947 } 14948 14949 14950 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14951 Expr *CondExpr, 14952 Expr *LHSExpr, Expr *RHSExpr, 14953 SourceLocation RPLoc) { 14954 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14955 14956 ExprValueKind VK = VK_RValue; 14957 ExprObjectKind OK = OK_Ordinary; 14958 QualType resType; 14959 bool CondIsTrue = false; 14960 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14961 resType = Context.DependentTy; 14962 } else { 14963 // The conditional expression is required to be a constant expression. 14964 llvm::APSInt condEval(32); 14965 ExprResult CondICE 14966 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14967 diag::err_typecheck_choose_expr_requires_constant, false); 14968 if (CondICE.isInvalid()) 14969 return ExprError(); 14970 CondExpr = CondICE.get(); 14971 CondIsTrue = condEval.getZExtValue(); 14972 14973 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14974 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14975 14976 resType = ActiveExpr->getType(); 14977 VK = ActiveExpr->getValueKind(); 14978 OK = ActiveExpr->getObjectKind(); 14979 } 14980 14981 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14982 resType, VK, OK, RPLoc, CondIsTrue); 14983 } 14984 14985 //===----------------------------------------------------------------------===// 14986 // Clang Extensions. 14987 //===----------------------------------------------------------------------===// 14988 14989 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14990 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14991 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14992 14993 if (LangOpts.CPlusPlus) { 14994 MangleNumberingContext *MCtx; 14995 Decl *ManglingContextDecl; 14996 std::tie(MCtx, ManglingContextDecl) = 14997 getCurrentMangleNumberContext(Block->getDeclContext()); 14998 if (MCtx) { 14999 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15000 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15001 } 15002 } 15003 15004 PushBlockScope(CurScope, Block); 15005 CurContext->addDecl(Block); 15006 if (CurScope) 15007 PushDeclContext(CurScope, Block); 15008 else 15009 CurContext = Block; 15010 15011 getCurBlock()->HasImplicitReturnType = true; 15012 15013 // Enter a new evaluation context to insulate the block from any 15014 // cleanups from the enclosing full-expression. 15015 PushExpressionEvaluationContext( 15016 ExpressionEvaluationContext::PotentiallyEvaluated); 15017 } 15018 15019 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15020 Scope *CurScope) { 15021 assert(ParamInfo.getIdentifier() == nullptr && 15022 "block-id should have no identifier!"); 15023 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 15024 BlockScopeInfo *CurBlock = getCurBlock(); 15025 15026 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15027 QualType T = Sig->getType(); 15028 15029 // FIXME: We should allow unexpanded parameter packs here, but that would, 15030 // in turn, make the block expression contain unexpanded parameter packs. 15031 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15032 // Drop the parameters. 15033 FunctionProtoType::ExtProtoInfo EPI; 15034 EPI.HasTrailingReturn = false; 15035 EPI.TypeQuals.addConst(); 15036 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15037 Sig = Context.getTrivialTypeSourceInfo(T); 15038 } 15039 15040 // GetTypeForDeclarator always produces a function type for a block 15041 // literal signature. Furthermore, it is always a FunctionProtoType 15042 // unless the function was written with a typedef. 15043 assert(T->isFunctionType() && 15044 "GetTypeForDeclarator made a non-function block signature"); 15045 15046 // Look for an explicit signature in that function type. 15047 FunctionProtoTypeLoc ExplicitSignature; 15048 15049 if ((ExplicitSignature = Sig->getTypeLoc() 15050 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15051 15052 // Check whether that explicit signature was synthesized by 15053 // GetTypeForDeclarator. If so, don't save that as part of the 15054 // written signature. 15055 if (ExplicitSignature.getLocalRangeBegin() == 15056 ExplicitSignature.getLocalRangeEnd()) { 15057 // This would be much cheaper if we stored TypeLocs instead of 15058 // TypeSourceInfos. 15059 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15060 unsigned Size = Result.getFullDataSize(); 15061 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15062 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15063 15064 ExplicitSignature = FunctionProtoTypeLoc(); 15065 } 15066 } 15067 15068 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15069 CurBlock->FunctionType = T; 15070 15071 const FunctionType *Fn = T->getAs<FunctionType>(); 15072 QualType RetTy = Fn->getReturnType(); 15073 bool isVariadic = 15074 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15075 15076 CurBlock->TheDecl->setIsVariadic(isVariadic); 15077 15078 // Context.DependentTy is used as a placeholder for a missing block 15079 // return type. TODO: what should we do with declarators like: 15080 // ^ * { ... } 15081 // If the answer is "apply template argument deduction".... 15082 if (RetTy != Context.DependentTy) { 15083 CurBlock->ReturnType = RetTy; 15084 CurBlock->TheDecl->setBlockMissingReturnType(false); 15085 CurBlock->HasImplicitReturnType = false; 15086 } 15087 15088 // Push block parameters from the declarator if we had them. 15089 SmallVector<ParmVarDecl*, 8> Params; 15090 if (ExplicitSignature) { 15091 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15092 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15093 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15094 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15095 // Diagnose this as an extension in C17 and earlier. 15096 if (!getLangOpts().C2x) 15097 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15098 } 15099 Params.push_back(Param); 15100 } 15101 15102 // Fake up parameter variables if we have a typedef, like 15103 // ^ fntype { ... } 15104 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15105 for (const auto &I : Fn->param_types()) { 15106 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15107 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15108 Params.push_back(Param); 15109 } 15110 } 15111 15112 // Set the parameters on the block decl. 15113 if (!Params.empty()) { 15114 CurBlock->TheDecl->setParams(Params); 15115 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15116 /*CheckParameterNames=*/false); 15117 } 15118 15119 // Finally we can process decl attributes. 15120 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15121 15122 // Put the parameter variables in scope. 15123 for (auto AI : CurBlock->TheDecl->parameters()) { 15124 AI->setOwningFunction(CurBlock->TheDecl); 15125 15126 // If this has an identifier, add it to the scope stack. 15127 if (AI->getIdentifier()) { 15128 CheckShadow(CurBlock->TheScope, AI); 15129 15130 PushOnScopeChains(AI, CurBlock->TheScope); 15131 } 15132 } 15133 } 15134 15135 /// ActOnBlockError - If there is an error parsing a block, this callback 15136 /// is invoked to pop the information about the block from the action impl. 15137 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15138 // Leave the expression-evaluation context. 15139 DiscardCleanupsInEvaluationContext(); 15140 PopExpressionEvaluationContext(); 15141 15142 // Pop off CurBlock, handle nested blocks. 15143 PopDeclContext(); 15144 PopFunctionScopeInfo(); 15145 } 15146 15147 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15148 /// literal was successfully completed. ^(int x){...} 15149 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15150 Stmt *Body, Scope *CurScope) { 15151 // If blocks are disabled, emit an error. 15152 if (!LangOpts.Blocks) 15153 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15154 15155 // Leave the expression-evaluation context. 15156 if (hasAnyUnrecoverableErrorsInThisFunction()) 15157 DiscardCleanupsInEvaluationContext(); 15158 assert(!Cleanup.exprNeedsCleanups() && 15159 "cleanups within block not correctly bound!"); 15160 PopExpressionEvaluationContext(); 15161 15162 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15163 BlockDecl *BD = BSI->TheDecl; 15164 15165 if (BSI->HasImplicitReturnType) 15166 deduceClosureReturnType(*BSI); 15167 15168 QualType RetTy = Context.VoidTy; 15169 if (!BSI->ReturnType.isNull()) 15170 RetTy = BSI->ReturnType; 15171 15172 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15173 QualType BlockTy; 15174 15175 // If the user wrote a function type in some form, try to use that. 15176 if (!BSI->FunctionType.isNull()) { 15177 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15178 15179 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15180 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15181 15182 // Turn protoless block types into nullary block types. 15183 if (isa<FunctionNoProtoType>(FTy)) { 15184 FunctionProtoType::ExtProtoInfo EPI; 15185 EPI.ExtInfo = Ext; 15186 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15187 15188 // Otherwise, if we don't need to change anything about the function type, 15189 // preserve its sugar structure. 15190 } else if (FTy->getReturnType() == RetTy && 15191 (!NoReturn || FTy->getNoReturnAttr())) { 15192 BlockTy = BSI->FunctionType; 15193 15194 // Otherwise, make the minimal modifications to the function type. 15195 } else { 15196 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15197 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15198 EPI.TypeQuals = Qualifiers(); 15199 EPI.ExtInfo = Ext; 15200 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15201 } 15202 15203 // If we don't have a function type, just build one from nothing. 15204 } else { 15205 FunctionProtoType::ExtProtoInfo EPI; 15206 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15207 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15208 } 15209 15210 DiagnoseUnusedParameters(BD->parameters()); 15211 BlockTy = Context.getBlockPointerType(BlockTy); 15212 15213 // If needed, diagnose invalid gotos and switches in the block. 15214 if (getCurFunction()->NeedsScopeChecking() && 15215 !PP.isCodeCompletionEnabled()) 15216 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15217 15218 BD->setBody(cast<CompoundStmt>(Body)); 15219 15220 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15221 DiagnoseUnguardedAvailabilityViolations(BD); 15222 15223 // Try to apply the named return value optimization. We have to check again 15224 // if we can do this, though, because blocks keep return statements around 15225 // to deduce an implicit return type. 15226 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15227 !BD->isDependentContext()) 15228 computeNRVO(Body, BSI); 15229 15230 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15231 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15232 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15233 NTCUK_Destruct|NTCUK_Copy); 15234 15235 PopDeclContext(); 15236 15237 // Pop the block scope now but keep it alive to the end of this function. 15238 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15239 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15240 15241 // Set the captured variables on the block. 15242 SmallVector<BlockDecl::Capture, 4> Captures; 15243 for (Capture &Cap : BSI->Captures) { 15244 if (Cap.isInvalid() || Cap.isThisCapture()) 15245 continue; 15246 15247 VarDecl *Var = Cap.getVariable(); 15248 Expr *CopyExpr = nullptr; 15249 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15250 if (const RecordType *Record = 15251 Cap.getCaptureType()->getAs<RecordType>()) { 15252 // The capture logic needs the destructor, so make sure we mark it. 15253 // Usually this is unnecessary because most local variables have 15254 // their destructors marked at declaration time, but parameters are 15255 // an exception because it's technically only the call site that 15256 // actually requires the destructor. 15257 if (isa<ParmVarDecl>(Var)) 15258 FinalizeVarWithDestructor(Var, Record); 15259 15260 // Enter a separate potentially-evaluated context while building block 15261 // initializers to isolate their cleanups from those of the block 15262 // itself. 15263 // FIXME: Is this appropriate even when the block itself occurs in an 15264 // unevaluated operand? 15265 EnterExpressionEvaluationContext EvalContext( 15266 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15267 15268 SourceLocation Loc = Cap.getLocation(); 15269 15270 ExprResult Result = BuildDeclarationNameExpr( 15271 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15272 15273 // According to the blocks spec, the capture of a variable from 15274 // the stack requires a const copy constructor. This is not true 15275 // of the copy/move done to move a __block variable to the heap. 15276 if (!Result.isInvalid() && 15277 !Result.get()->getType().isConstQualified()) { 15278 Result = ImpCastExprToType(Result.get(), 15279 Result.get()->getType().withConst(), 15280 CK_NoOp, VK_LValue); 15281 } 15282 15283 if (!Result.isInvalid()) { 15284 Result = PerformCopyInitialization( 15285 InitializedEntity::InitializeBlock(Var->getLocation(), 15286 Cap.getCaptureType(), false), 15287 Loc, Result.get()); 15288 } 15289 15290 // Build a full-expression copy expression if initialization 15291 // succeeded and used a non-trivial constructor. Recover from 15292 // errors by pretending that the copy isn't necessary. 15293 if (!Result.isInvalid() && 15294 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15295 ->isTrivial()) { 15296 Result = MaybeCreateExprWithCleanups(Result); 15297 CopyExpr = Result.get(); 15298 } 15299 } 15300 } 15301 15302 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15303 CopyExpr); 15304 Captures.push_back(NewCap); 15305 } 15306 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15307 15308 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15309 15310 // If the block isn't obviously global, i.e. it captures anything at 15311 // all, then we need to do a few things in the surrounding context: 15312 if (Result->getBlockDecl()->hasCaptures()) { 15313 // First, this expression has a new cleanup object. 15314 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15315 Cleanup.setExprNeedsCleanups(true); 15316 15317 // It also gets a branch-protected scope if any of the captured 15318 // variables needs destruction. 15319 for (const auto &CI : Result->getBlockDecl()->captures()) { 15320 const VarDecl *var = CI.getVariable(); 15321 if (var->getType().isDestructedType() != QualType::DK_none) { 15322 setFunctionHasBranchProtectedScope(); 15323 break; 15324 } 15325 } 15326 } 15327 15328 if (getCurFunction()) 15329 getCurFunction()->addBlock(BD); 15330 15331 return Result; 15332 } 15333 15334 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15335 SourceLocation RPLoc) { 15336 TypeSourceInfo *TInfo; 15337 GetTypeFromParser(Ty, &TInfo); 15338 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15339 } 15340 15341 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15342 Expr *E, TypeSourceInfo *TInfo, 15343 SourceLocation RPLoc) { 15344 Expr *OrigExpr = E; 15345 bool IsMS = false; 15346 15347 // CUDA device code does not support varargs. 15348 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15349 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15350 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15351 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15352 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15353 } 15354 } 15355 15356 // NVPTX does not support va_arg expression. 15357 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15358 Context.getTargetInfo().getTriple().isNVPTX()) 15359 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15360 15361 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15362 // as Microsoft ABI on an actual Microsoft platform, where 15363 // __builtin_ms_va_list and __builtin_va_list are the same.) 15364 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15365 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15366 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15367 if (Context.hasSameType(MSVaListType, E->getType())) { 15368 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15369 return ExprError(); 15370 IsMS = true; 15371 } 15372 } 15373 15374 // Get the va_list type 15375 QualType VaListType = Context.getBuiltinVaListType(); 15376 if (!IsMS) { 15377 if (VaListType->isArrayType()) { 15378 // Deal with implicit array decay; for example, on x86-64, 15379 // va_list is an array, but it's supposed to decay to 15380 // a pointer for va_arg. 15381 VaListType = Context.getArrayDecayedType(VaListType); 15382 // Make sure the input expression also decays appropriately. 15383 ExprResult Result = UsualUnaryConversions(E); 15384 if (Result.isInvalid()) 15385 return ExprError(); 15386 E = Result.get(); 15387 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15388 // If va_list is a record type and we are compiling in C++ mode, 15389 // check the argument using reference binding. 15390 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15391 Context, Context.getLValueReferenceType(VaListType), false); 15392 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15393 if (Init.isInvalid()) 15394 return ExprError(); 15395 E = Init.getAs<Expr>(); 15396 } else { 15397 // Otherwise, the va_list argument must be an l-value because 15398 // it is modified by va_arg. 15399 if (!E->isTypeDependent() && 15400 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15401 return ExprError(); 15402 } 15403 } 15404 15405 if (!IsMS && !E->isTypeDependent() && 15406 !Context.hasSameType(VaListType, E->getType())) 15407 return ExprError( 15408 Diag(E->getBeginLoc(), 15409 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15410 << OrigExpr->getType() << E->getSourceRange()); 15411 15412 if (!TInfo->getType()->isDependentType()) { 15413 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15414 diag::err_second_parameter_to_va_arg_incomplete, 15415 TInfo->getTypeLoc())) 15416 return ExprError(); 15417 15418 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15419 TInfo->getType(), 15420 diag::err_second_parameter_to_va_arg_abstract, 15421 TInfo->getTypeLoc())) 15422 return ExprError(); 15423 15424 if (!TInfo->getType().isPODType(Context)) { 15425 Diag(TInfo->getTypeLoc().getBeginLoc(), 15426 TInfo->getType()->isObjCLifetimeType() 15427 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15428 : diag::warn_second_parameter_to_va_arg_not_pod) 15429 << TInfo->getType() 15430 << TInfo->getTypeLoc().getSourceRange(); 15431 } 15432 15433 // Check for va_arg where arguments of the given type will be promoted 15434 // (i.e. this va_arg is guaranteed to have undefined behavior). 15435 QualType PromoteType; 15436 if (TInfo->getType()->isPromotableIntegerType()) { 15437 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15438 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15439 PromoteType = QualType(); 15440 } 15441 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15442 PromoteType = Context.DoubleTy; 15443 if (!PromoteType.isNull()) 15444 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15445 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15446 << TInfo->getType() 15447 << PromoteType 15448 << TInfo->getTypeLoc().getSourceRange()); 15449 } 15450 15451 QualType T = TInfo->getType().getNonLValueExprType(Context); 15452 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15453 } 15454 15455 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15456 // The type of __null will be int or long, depending on the size of 15457 // pointers on the target. 15458 QualType Ty; 15459 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15460 if (pw == Context.getTargetInfo().getIntWidth()) 15461 Ty = Context.IntTy; 15462 else if (pw == Context.getTargetInfo().getLongWidth()) 15463 Ty = Context.LongTy; 15464 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15465 Ty = Context.LongLongTy; 15466 else { 15467 llvm_unreachable("I don't know size of pointer!"); 15468 } 15469 15470 return new (Context) GNUNullExpr(Ty, TokenLoc); 15471 } 15472 15473 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15474 SourceLocation BuiltinLoc, 15475 SourceLocation RPLoc) { 15476 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15477 } 15478 15479 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15480 SourceLocation BuiltinLoc, 15481 SourceLocation RPLoc, 15482 DeclContext *ParentContext) { 15483 return new (Context) 15484 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15485 } 15486 15487 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15488 bool Diagnose) { 15489 if (!getLangOpts().ObjC) 15490 return false; 15491 15492 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15493 if (!PT) 15494 return false; 15495 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15496 15497 // Ignore any parens, implicit casts (should only be 15498 // array-to-pointer decays), and not-so-opaque values. The last is 15499 // important for making this trigger for property assignments. 15500 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15501 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15502 if (OV->getSourceExpr()) 15503 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15504 15505 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15506 if (!PT->isObjCIdType() && 15507 !(ID && ID->getIdentifier()->isStr("NSString"))) 15508 return false; 15509 if (!SL->isAscii()) 15510 return false; 15511 15512 if (Diagnose) { 15513 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15514 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15515 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15516 } 15517 return true; 15518 } 15519 15520 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15521 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15522 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15523 !SrcExpr->isNullPointerConstant( 15524 getASTContext(), Expr::NPC_NeverValueDependent)) { 15525 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15526 return false; 15527 if (Diagnose) { 15528 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15529 << /*number*/1 15530 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15531 Expr *NumLit = 15532 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15533 if (NumLit) 15534 Exp = NumLit; 15535 } 15536 return true; 15537 } 15538 15539 return false; 15540 } 15541 15542 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15543 const Expr *SrcExpr) { 15544 if (!DstType->isFunctionPointerType() || 15545 !SrcExpr->getType()->isFunctionType()) 15546 return false; 15547 15548 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15549 if (!DRE) 15550 return false; 15551 15552 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15553 if (!FD) 15554 return false; 15555 15556 return !S.checkAddressOfFunctionIsAvailable(FD, 15557 /*Complain=*/true, 15558 SrcExpr->getBeginLoc()); 15559 } 15560 15561 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15562 SourceLocation Loc, 15563 QualType DstType, QualType SrcType, 15564 Expr *SrcExpr, AssignmentAction Action, 15565 bool *Complained) { 15566 if (Complained) 15567 *Complained = false; 15568 15569 // Decode the result (notice that AST's are still created for extensions). 15570 bool CheckInferredResultType = false; 15571 bool isInvalid = false; 15572 unsigned DiagKind = 0; 15573 FixItHint Hint; 15574 ConversionFixItGenerator ConvHints; 15575 bool MayHaveConvFixit = false; 15576 bool MayHaveFunctionDiff = false; 15577 const ObjCInterfaceDecl *IFace = nullptr; 15578 const ObjCProtocolDecl *PDecl = nullptr; 15579 15580 switch (ConvTy) { 15581 case Compatible: 15582 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15583 return false; 15584 15585 case PointerToInt: 15586 if (getLangOpts().CPlusPlus) { 15587 DiagKind = diag::err_typecheck_convert_pointer_int; 15588 isInvalid = true; 15589 } else { 15590 DiagKind = diag::ext_typecheck_convert_pointer_int; 15591 } 15592 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15593 MayHaveConvFixit = true; 15594 break; 15595 case IntToPointer: 15596 if (getLangOpts().CPlusPlus) { 15597 DiagKind = diag::err_typecheck_convert_int_pointer; 15598 isInvalid = true; 15599 } else { 15600 DiagKind = diag::ext_typecheck_convert_int_pointer; 15601 } 15602 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15603 MayHaveConvFixit = true; 15604 break; 15605 case IncompatibleFunctionPointer: 15606 if (getLangOpts().CPlusPlus) { 15607 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15608 isInvalid = true; 15609 } else { 15610 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15611 } 15612 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15613 MayHaveConvFixit = true; 15614 break; 15615 case IncompatiblePointer: 15616 if (Action == AA_Passing_CFAudited) { 15617 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15618 } else if (getLangOpts().CPlusPlus) { 15619 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15620 isInvalid = true; 15621 } else { 15622 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15623 } 15624 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15625 SrcType->isObjCObjectPointerType(); 15626 if (Hint.isNull() && !CheckInferredResultType) { 15627 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15628 } 15629 else if (CheckInferredResultType) { 15630 SrcType = SrcType.getUnqualifiedType(); 15631 DstType = DstType.getUnqualifiedType(); 15632 } 15633 MayHaveConvFixit = true; 15634 break; 15635 case IncompatiblePointerSign: 15636 if (getLangOpts().CPlusPlus) { 15637 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15638 isInvalid = true; 15639 } else { 15640 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15641 } 15642 break; 15643 case FunctionVoidPointer: 15644 if (getLangOpts().CPlusPlus) { 15645 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15646 isInvalid = true; 15647 } else { 15648 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15649 } 15650 break; 15651 case IncompatiblePointerDiscardsQualifiers: { 15652 // Perform array-to-pointer decay if necessary. 15653 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15654 15655 isInvalid = true; 15656 15657 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15658 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15659 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15660 DiagKind = diag::err_typecheck_incompatible_address_space; 15661 break; 15662 15663 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15664 DiagKind = diag::err_typecheck_incompatible_ownership; 15665 break; 15666 } 15667 15668 llvm_unreachable("unknown error case for discarding qualifiers!"); 15669 // fallthrough 15670 } 15671 case CompatiblePointerDiscardsQualifiers: 15672 // If the qualifiers lost were because we were applying the 15673 // (deprecated) C++ conversion from a string literal to a char* 15674 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15675 // Ideally, this check would be performed in 15676 // checkPointerTypesForAssignment. However, that would require a 15677 // bit of refactoring (so that the second argument is an 15678 // expression, rather than a type), which should be done as part 15679 // of a larger effort to fix checkPointerTypesForAssignment for 15680 // C++ semantics. 15681 if (getLangOpts().CPlusPlus && 15682 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15683 return false; 15684 if (getLangOpts().CPlusPlus) { 15685 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15686 isInvalid = true; 15687 } else { 15688 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15689 } 15690 15691 break; 15692 case IncompatibleNestedPointerQualifiers: 15693 if (getLangOpts().CPlusPlus) { 15694 isInvalid = true; 15695 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15696 } else { 15697 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15698 } 15699 break; 15700 case IncompatibleNestedPointerAddressSpaceMismatch: 15701 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15702 isInvalid = true; 15703 break; 15704 case IntToBlockPointer: 15705 DiagKind = diag::err_int_to_block_pointer; 15706 isInvalid = true; 15707 break; 15708 case IncompatibleBlockPointer: 15709 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15710 isInvalid = true; 15711 break; 15712 case IncompatibleObjCQualifiedId: { 15713 if (SrcType->isObjCQualifiedIdType()) { 15714 const ObjCObjectPointerType *srcOPT = 15715 SrcType->castAs<ObjCObjectPointerType>(); 15716 for (auto *srcProto : srcOPT->quals()) { 15717 PDecl = srcProto; 15718 break; 15719 } 15720 if (const ObjCInterfaceType *IFaceT = 15721 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15722 IFace = IFaceT->getDecl(); 15723 } 15724 else if (DstType->isObjCQualifiedIdType()) { 15725 const ObjCObjectPointerType *dstOPT = 15726 DstType->castAs<ObjCObjectPointerType>(); 15727 for (auto *dstProto : dstOPT->quals()) { 15728 PDecl = dstProto; 15729 break; 15730 } 15731 if (const ObjCInterfaceType *IFaceT = 15732 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15733 IFace = IFaceT->getDecl(); 15734 } 15735 if (getLangOpts().CPlusPlus) { 15736 DiagKind = diag::err_incompatible_qualified_id; 15737 isInvalid = true; 15738 } else { 15739 DiagKind = diag::warn_incompatible_qualified_id; 15740 } 15741 break; 15742 } 15743 case IncompatibleVectors: 15744 if (getLangOpts().CPlusPlus) { 15745 DiagKind = diag::err_incompatible_vectors; 15746 isInvalid = true; 15747 } else { 15748 DiagKind = diag::warn_incompatible_vectors; 15749 } 15750 break; 15751 case IncompatibleObjCWeakRef: 15752 DiagKind = diag::err_arc_weak_unavailable_assign; 15753 isInvalid = true; 15754 break; 15755 case Incompatible: 15756 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15757 if (Complained) 15758 *Complained = true; 15759 return true; 15760 } 15761 15762 DiagKind = diag::err_typecheck_convert_incompatible; 15763 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15764 MayHaveConvFixit = true; 15765 isInvalid = true; 15766 MayHaveFunctionDiff = true; 15767 break; 15768 } 15769 15770 QualType FirstType, SecondType; 15771 switch (Action) { 15772 case AA_Assigning: 15773 case AA_Initializing: 15774 // The destination type comes first. 15775 FirstType = DstType; 15776 SecondType = SrcType; 15777 break; 15778 15779 case AA_Returning: 15780 case AA_Passing: 15781 case AA_Passing_CFAudited: 15782 case AA_Converting: 15783 case AA_Sending: 15784 case AA_Casting: 15785 // The source type comes first. 15786 FirstType = SrcType; 15787 SecondType = DstType; 15788 break; 15789 } 15790 15791 PartialDiagnostic FDiag = PDiag(DiagKind); 15792 if (Action == AA_Passing_CFAudited) 15793 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15794 else 15795 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15796 15797 // If we can fix the conversion, suggest the FixIts. 15798 assert(ConvHints.isNull() || Hint.isNull()); 15799 if (!ConvHints.isNull()) { 15800 for (FixItHint &H : ConvHints.Hints) 15801 FDiag << H; 15802 } else { 15803 FDiag << Hint; 15804 } 15805 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15806 15807 if (MayHaveFunctionDiff) 15808 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15809 15810 Diag(Loc, FDiag); 15811 if ((DiagKind == diag::warn_incompatible_qualified_id || 15812 DiagKind == diag::err_incompatible_qualified_id) && 15813 PDecl && IFace && !IFace->hasDefinition()) 15814 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15815 << IFace << PDecl; 15816 15817 if (SecondType == Context.OverloadTy) 15818 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15819 FirstType, /*TakingAddress=*/true); 15820 15821 if (CheckInferredResultType) 15822 EmitRelatedResultTypeNote(SrcExpr); 15823 15824 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15825 EmitRelatedResultTypeNoteForReturn(DstType); 15826 15827 if (Complained) 15828 *Complained = true; 15829 return isInvalid; 15830 } 15831 15832 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15833 llvm::APSInt *Result) { 15834 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15835 public: 15836 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15837 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15838 } 15839 } Diagnoser; 15840 15841 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15842 } 15843 15844 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15845 llvm::APSInt *Result, 15846 unsigned DiagID, 15847 bool AllowFold) { 15848 class IDDiagnoser : public VerifyICEDiagnoser { 15849 unsigned DiagID; 15850 15851 public: 15852 IDDiagnoser(unsigned DiagID) 15853 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15854 15855 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15856 S.Diag(Loc, DiagID) << SR; 15857 } 15858 } Diagnoser(DiagID); 15859 15860 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15861 } 15862 15863 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15864 SourceRange SR) { 15865 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15866 } 15867 15868 ExprResult 15869 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15870 VerifyICEDiagnoser &Diagnoser, 15871 bool AllowFold) { 15872 SourceLocation DiagLoc = E->getBeginLoc(); 15873 15874 if (getLangOpts().CPlusPlus11) { 15875 // C++11 [expr.const]p5: 15876 // If an expression of literal class type is used in a context where an 15877 // integral constant expression is required, then that class type shall 15878 // have a single non-explicit conversion function to an integral or 15879 // unscoped enumeration type 15880 ExprResult Converted; 15881 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15882 public: 15883 CXX11ConvertDiagnoser(bool Silent) 15884 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15885 Silent, true) {} 15886 15887 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15888 QualType T) override { 15889 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15890 } 15891 15892 SemaDiagnosticBuilder diagnoseIncomplete( 15893 Sema &S, SourceLocation Loc, QualType T) override { 15894 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15895 } 15896 15897 SemaDiagnosticBuilder diagnoseExplicitConv( 15898 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15899 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15900 } 15901 15902 SemaDiagnosticBuilder noteExplicitConv( 15903 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15904 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15905 << ConvTy->isEnumeralType() << ConvTy; 15906 } 15907 15908 SemaDiagnosticBuilder diagnoseAmbiguous( 15909 Sema &S, SourceLocation Loc, QualType T) override { 15910 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15911 } 15912 15913 SemaDiagnosticBuilder noteAmbiguous( 15914 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15915 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15916 << ConvTy->isEnumeralType() << ConvTy; 15917 } 15918 15919 SemaDiagnosticBuilder diagnoseConversion( 15920 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15921 llvm_unreachable("conversion functions are permitted"); 15922 } 15923 } ConvertDiagnoser(Diagnoser.Suppress); 15924 15925 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15926 ConvertDiagnoser); 15927 if (Converted.isInvalid()) 15928 return Converted; 15929 E = Converted.get(); 15930 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15931 return ExprError(); 15932 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15933 // An ICE must be of integral or unscoped enumeration type. 15934 if (!Diagnoser.Suppress) 15935 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15936 return ExprError(); 15937 } 15938 15939 ExprResult RValueExpr = DefaultLvalueConversion(E); 15940 if (RValueExpr.isInvalid()) 15941 return ExprError(); 15942 15943 E = RValueExpr.get(); 15944 15945 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15946 // in the non-ICE case. 15947 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15948 if (Result) 15949 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15950 if (!isa<ConstantExpr>(E)) 15951 E = ConstantExpr::Create(Context, E); 15952 return E; 15953 } 15954 15955 Expr::EvalResult EvalResult; 15956 SmallVector<PartialDiagnosticAt, 8> Notes; 15957 EvalResult.Diag = &Notes; 15958 15959 // Try to evaluate the expression, and produce diagnostics explaining why it's 15960 // not a constant expression as a side-effect. 15961 bool Folded = 15962 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15963 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15964 15965 if (!isa<ConstantExpr>(E)) 15966 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15967 15968 // In C++11, we can rely on diagnostics being produced for any expression 15969 // which is not a constant expression. If no diagnostics were produced, then 15970 // this is a constant expression. 15971 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15972 if (Result) 15973 *Result = EvalResult.Val.getInt(); 15974 return E; 15975 } 15976 15977 // If our only note is the usual "invalid subexpression" note, just point 15978 // the caret at its location rather than producing an essentially 15979 // redundant note. 15980 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15981 diag::note_invalid_subexpr_in_const_expr) { 15982 DiagLoc = Notes[0].first; 15983 Notes.clear(); 15984 } 15985 15986 if (!Folded || !AllowFold) { 15987 if (!Diagnoser.Suppress) { 15988 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15989 for (const PartialDiagnosticAt &Note : Notes) 15990 Diag(Note.first, Note.second); 15991 } 15992 15993 return ExprError(); 15994 } 15995 15996 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15997 for (const PartialDiagnosticAt &Note : Notes) 15998 Diag(Note.first, Note.second); 15999 16000 if (Result) 16001 *Result = EvalResult.Val.getInt(); 16002 return E; 16003 } 16004 16005 namespace { 16006 // Handle the case where we conclude a expression which we speculatively 16007 // considered to be unevaluated is actually evaluated. 16008 class TransformToPE : public TreeTransform<TransformToPE> { 16009 typedef TreeTransform<TransformToPE> BaseTransform; 16010 16011 public: 16012 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16013 16014 // Make sure we redo semantic analysis 16015 bool AlwaysRebuild() { return true; } 16016 bool ReplacingOriginal() { return true; } 16017 16018 // We need to special-case DeclRefExprs referring to FieldDecls which 16019 // are not part of a member pointer formation; normal TreeTransforming 16020 // doesn't catch this case because of the way we represent them in the AST. 16021 // FIXME: This is a bit ugly; is it really the best way to handle this 16022 // case? 16023 // 16024 // Error on DeclRefExprs referring to FieldDecls. 16025 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16026 if (isa<FieldDecl>(E->getDecl()) && 16027 !SemaRef.isUnevaluatedContext()) 16028 return SemaRef.Diag(E->getLocation(), 16029 diag::err_invalid_non_static_member_use) 16030 << E->getDecl() << E->getSourceRange(); 16031 16032 return BaseTransform::TransformDeclRefExpr(E); 16033 } 16034 16035 // Exception: filter out member pointer formation 16036 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16037 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16038 return E; 16039 16040 return BaseTransform::TransformUnaryOperator(E); 16041 } 16042 16043 // The body of a lambda-expression is in a separate expression evaluation 16044 // context so never needs to be transformed. 16045 // FIXME: Ideally we wouldn't transform the closure type either, and would 16046 // just recreate the capture expressions and lambda expression. 16047 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16048 return SkipLambdaBody(E, Body); 16049 } 16050 }; 16051 } 16052 16053 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16054 assert(isUnevaluatedContext() && 16055 "Should only transform unevaluated expressions"); 16056 ExprEvalContexts.back().Context = 16057 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16058 if (isUnevaluatedContext()) 16059 return E; 16060 return TransformToPE(*this).TransformExpr(E); 16061 } 16062 16063 void 16064 Sema::PushExpressionEvaluationContext( 16065 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16066 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16067 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16068 LambdaContextDecl, ExprContext); 16069 Cleanup.reset(); 16070 if (!MaybeODRUseExprs.empty()) 16071 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16072 } 16073 16074 void 16075 Sema::PushExpressionEvaluationContext( 16076 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16077 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16078 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16079 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16080 } 16081 16082 namespace { 16083 16084 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16085 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16086 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16087 if (E->getOpcode() == UO_Deref) 16088 return CheckPossibleDeref(S, E->getSubExpr()); 16089 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16090 return CheckPossibleDeref(S, E->getBase()); 16091 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16092 return CheckPossibleDeref(S, E->getBase()); 16093 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16094 QualType Inner; 16095 QualType Ty = E->getType(); 16096 if (const auto *Ptr = Ty->getAs<PointerType>()) 16097 Inner = Ptr->getPointeeType(); 16098 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16099 Inner = Arr->getElementType(); 16100 else 16101 return nullptr; 16102 16103 if (Inner->hasAttr(attr::NoDeref)) 16104 return E; 16105 } 16106 return nullptr; 16107 } 16108 16109 } // namespace 16110 16111 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16112 for (const Expr *E : Rec.PossibleDerefs) { 16113 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16114 if (DeclRef) { 16115 const ValueDecl *Decl = DeclRef->getDecl(); 16116 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16117 << Decl->getName() << E->getSourceRange(); 16118 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16119 } else { 16120 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16121 << E->getSourceRange(); 16122 } 16123 } 16124 Rec.PossibleDerefs.clear(); 16125 } 16126 16127 /// Check whether E, which is either a discarded-value expression or an 16128 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16129 /// and if so, remove it from the list of volatile-qualified assignments that 16130 /// we are going to warn are deprecated. 16131 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16132 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16133 return; 16134 16135 // Note: ignoring parens here is not justified by the standard rules, but 16136 // ignoring parentheses seems like a more reasonable approach, and this only 16137 // drives a deprecation warning so doesn't affect conformance. 16138 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16139 if (BO->getOpcode() == BO_Assign) { 16140 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16141 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16142 LHSs.end()); 16143 } 16144 } 16145 } 16146 16147 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16148 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16149 RebuildingImmediateInvocation) 16150 return E; 16151 16152 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16153 /// It's OK if this fails; we'll also remove this in 16154 /// HandleImmediateInvocations, but catching it here allows us to avoid 16155 /// walking the AST looking for it in simple cases. 16156 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16157 if (auto *DeclRef = 16158 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16159 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16160 16161 E = MaybeCreateExprWithCleanups(E); 16162 16163 ConstantExpr *Res = ConstantExpr::Create( 16164 getASTContext(), E.get(), 16165 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16166 getASTContext()), 16167 /*IsImmediateInvocation*/ true); 16168 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16169 return Res; 16170 } 16171 16172 static void EvaluateAndDiagnoseImmediateInvocation( 16173 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16174 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16175 Expr::EvalResult Eval; 16176 Eval.Diag = &Notes; 16177 ConstantExpr *CE = Candidate.getPointer(); 16178 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 16179 SemaRef.getASTContext(), true); 16180 if (!Result || !Notes.empty()) { 16181 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16182 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16183 InnerExpr = FunctionalCast->getSubExpr(); 16184 FunctionDecl *FD = nullptr; 16185 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16186 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16187 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16188 FD = Call->getConstructor(); 16189 else 16190 llvm_unreachable("unhandled decl kind"); 16191 assert(FD->isConsteval()); 16192 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16193 for (auto &Note : Notes) 16194 SemaRef.Diag(Note.first, Note.second); 16195 return; 16196 } 16197 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16198 } 16199 16200 static void RemoveNestedImmediateInvocation( 16201 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16202 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16203 struct ComplexRemove : TreeTransform<ComplexRemove> { 16204 using Base = TreeTransform<ComplexRemove>; 16205 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16206 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16207 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16208 CurrentII; 16209 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16210 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16211 SmallVector<Sema::ImmediateInvocationCandidate, 16212 4>::reverse_iterator Current) 16213 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16214 void RemoveImmediateInvocation(ConstantExpr* E) { 16215 auto It = std::find_if(CurrentII, IISet.rend(), 16216 [E](Sema::ImmediateInvocationCandidate Elem) { 16217 return Elem.getPointer() == E; 16218 }); 16219 assert(It != IISet.rend() && 16220 "ConstantExpr marked IsImmediateInvocation should " 16221 "be present"); 16222 It->setInt(1); // Mark as deleted 16223 } 16224 ExprResult TransformConstantExpr(ConstantExpr *E) { 16225 if (!E->isImmediateInvocation()) 16226 return Base::TransformConstantExpr(E); 16227 RemoveImmediateInvocation(E); 16228 return Base::TransformExpr(E->getSubExpr()); 16229 } 16230 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16231 /// we need to remove its DeclRefExpr from the DRSet. 16232 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16233 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16234 return Base::TransformCXXOperatorCallExpr(E); 16235 } 16236 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16237 /// here. 16238 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16239 if (!Init) 16240 return Init; 16241 /// ConstantExpr are the first layer of implicit node to be removed so if 16242 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16243 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16244 if (CE->isImmediateInvocation()) 16245 RemoveImmediateInvocation(CE); 16246 return Base::TransformInitializer(Init, NotCopyInit); 16247 } 16248 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16249 DRSet.erase(E); 16250 return E; 16251 } 16252 bool AlwaysRebuild() { return false; } 16253 bool ReplacingOriginal() { return true; } 16254 bool AllowSkippingCXXConstructExpr() { 16255 bool Res = AllowSkippingFirstCXXConstructExpr; 16256 AllowSkippingFirstCXXConstructExpr = true; 16257 return Res; 16258 } 16259 bool AllowSkippingFirstCXXConstructExpr = true; 16260 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16261 Rec.ImmediateInvocationCandidates, It); 16262 16263 /// CXXConstructExpr with a single argument are getting skipped by 16264 /// TreeTransform in some situtation because they could be implicit. This 16265 /// can only occur for the top-level CXXConstructExpr because it is used 16266 /// nowhere in the expression being transformed therefore will not be rebuilt. 16267 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16268 /// skipping the first CXXConstructExpr. 16269 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16270 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16271 16272 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16273 assert(Res.isUsable()); 16274 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16275 It->getPointer()->setSubExpr(Res.get()); 16276 } 16277 16278 static void 16279 HandleImmediateInvocations(Sema &SemaRef, 16280 Sema::ExpressionEvaluationContextRecord &Rec) { 16281 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16282 Rec.ReferenceToConsteval.size() == 0) || 16283 SemaRef.RebuildingImmediateInvocation) 16284 return; 16285 16286 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16287 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16288 /// need to remove ReferenceToConsteval in the immediate invocation. 16289 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16290 16291 /// Prevent sema calls during the tree transform from adding pointers that 16292 /// are already in the sets. 16293 llvm::SaveAndRestore<bool> DisableIITracking( 16294 SemaRef.RebuildingImmediateInvocation, true); 16295 16296 /// Prevent diagnostic during tree transfrom as they are duplicates 16297 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16298 16299 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16300 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16301 if (!It->getInt()) 16302 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16303 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16304 Rec.ReferenceToConsteval.size()) { 16305 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16306 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16307 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16308 bool VisitDeclRefExpr(DeclRefExpr *E) { 16309 DRSet.erase(E); 16310 return DRSet.size(); 16311 } 16312 } Visitor(Rec.ReferenceToConsteval); 16313 Visitor.TraverseStmt( 16314 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16315 } 16316 for (auto CE : Rec.ImmediateInvocationCandidates) 16317 if (!CE.getInt()) 16318 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16319 for (auto DR : Rec.ReferenceToConsteval) { 16320 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16321 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16322 << FD; 16323 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16324 } 16325 } 16326 16327 void Sema::PopExpressionEvaluationContext() { 16328 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16329 unsigned NumTypos = Rec.NumTypos; 16330 16331 if (!Rec.Lambdas.empty()) { 16332 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16333 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16334 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16335 unsigned D; 16336 if (Rec.isUnevaluated()) { 16337 // C++11 [expr.prim.lambda]p2: 16338 // A lambda-expression shall not appear in an unevaluated operand 16339 // (Clause 5). 16340 D = diag::err_lambda_unevaluated_operand; 16341 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16342 // C++1y [expr.const]p2: 16343 // A conditional-expression e is a core constant expression unless the 16344 // evaluation of e, following the rules of the abstract machine, would 16345 // evaluate [...] a lambda-expression. 16346 D = diag::err_lambda_in_constant_expression; 16347 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16348 // C++17 [expr.prim.lamda]p2: 16349 // A lambda-expression shall not appear [...] in a template-argument. 16350 D = diag::err_lambda_in_invalid_context; 16351 } else 16352 llvm_unreachable("Couldn't infer lambda error message."); 16353 16354 for (const auto *L : Rec.Lambdas) 16355 Diag(L->getBeginLoc(), D); 16356 } 16357 } 16358 16359 WarnOnPendingNoDerefs(Rec); 16360 HandleImmediateInvocations(*this, Rec); 16361 16362 // Warn on any volatile-qualified simple-assignments that are not discarded- 16363 // value expressions nor unevaluated operands (those cases get removed from 16364 // this list by CheckUnusedVolatileAssignment). 16365 for (auto *BO : Rec.VolatileAssignmentLHSs) 16366 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16367 << BO->getType(); 16368 16369 // When are coming out of an unevaluated context, clear out any 16370 // temporaries that we may have created as part of the evaluation of 16371 // the expression in that context: they aren't relevant because they 16372 // will never be constructed. 16373 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16374 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16375 ExprCleanupObjects.end()); 16376 Cleanup = Rec.ParentCleanup; 16377 CleanupVarDeclMarking(); 16378 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16379 // Otherwise, merge the contexts together. 16380 } else { 16381 Cleanup.mergeFrom(Rec.ParentCleanup); 16382 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16383 Rec.SavedMaybeODRUseExprs.end()); 16384 } 16385 16386 // Pop the current expression evaluation context off the stack. 16387 ExprEvalContexts.pop_back(); 16388 16389 // The global expression evaluation context record is never popped. 16390 ExprEvalContexts.back().NumTypos += NumTypos; 16391 } 16392 16393 void Sema::DiscardCleanupsInEvaluationContext() { 16394 ExprCleanupObjects.erase( 16395 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16396 ExprCleanupObjects.end()); 16397 Cleanup.reset(); 16398 MaybeODRUseExprs.clear(); 16399 } 16400 16401 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16402 ExprResult Result = CheckPlaceholderExpr(E); 16403 if (Result.isInvalid()) 16404 return ExprError(); 16405 E = Result.get(); 16406 if (!E->getType()->isVariablyModifiedType()) 16407 return E; 16408 return TransformToPotentiallyEvaluated(E); 16409 } 16410 16411 /// Are we in a context that is potentially constant evaluated per C++20 16412 /// [expr.const]p12? 16413 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16414 /// C++2a [expr.const]p12: 16415 // An expression or conversion is potentially constant evaluated if it is 16416 switch (SemaRef.ExprEvalContexts.back().Context) { 16417 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16418 // -- a manifestly constant-evaluated expression, 16419 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16420 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16421 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16422 // -- a potentially-evaluated expression, 16423 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16424 // -- an immediate subexpression of a braced-init-list, 16425 16426 // -- [FIXME] an expression of the form & cast-expression that occurs 16427 // within a templated entity 16428 // -- a subexpression of one of the above that is not a subexpression of 16429 // a nested unevaluated operand. 16430 return true; 16431 16432 case Sema::ExpressionEvaluationContext::Unevaluated: 16433 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16434 // Expressions in this context are never evaluated. 16435 return false; 16436 } 16437 llvm_unreachable("Invalid context"); 16438 } 16439 16440 /// Return true if this function has a calling convention that requires mangling 16441 /// in the size of the parameter pack. 16442 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16443 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16444 // we don't need parameter type sizes. 16445 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16446 if (!TT.isOSWindows() || !TT.isX86()) 16447 return false; 16448 16449 // If this is C++ and this isn't an extern "C" function, parameters do not 16450 // need to be complete. In this case, C++ mangling will apply, which doesn't 16451 // use the size of the parameters. 16452 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16453 return false; 16454 16455 // Stdcall, fastcall, and vectorcall need this special treatment. 16456 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16457 switch (CC) { 16458 case CC_X86StdCall: 16459 case CC_X86FastCall: 16460 case CC_X86VectorCall: 16461 return true; 16462 default: 16463 break; 16464 } 16465 return false; 16466 } 16467 16468 /// Require that all of the parameter types of function be complete. Normally, 16469 /// parameter types are only required to be complete when a function is called 16470 /// or defined, but to mangle functions with certain calling conventions, the 16471 /// mangler needs to know the size of the parameter list. In this situation, 16472 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16473 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16474 /// result in a linker error. Clang doesn't implement this behavior, and instead 16475 /// attempts to error at compile time. 16476 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16477 SourceLocation Loc) { 16478 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16479 FunctionDecl *FD; 16480 ParmVarDecl *Param; 16481 16482 public: 16483 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16484 : FD(FD), Param(Param) {} 16485 16486 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16487 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16488 StringRef CCName; 16489 switch (CC) { 16490 case CC_X86StdCall: 16491 CCName = "stdcall"; 16492 break; 16493 case CC_X86FastCall: 16494 CCName = "fastcall"; 16495 break; 16496 case CC_X86VectorCall: 16497 CCName = "vectorcall"; 16498 break; 16499 default: 16500 llvm_unreachable("CC does not need mangling"); 16501 } 16502 16503 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16504 << Param->getDeclName() << FD->getDeclName() << CCName; 16505 } 16506 }; 16507 16508 for (ParmVarDecl *Param : FD->parameters()) { 16509 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16510 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16511 } 16512 } 16513 16514 namespace { 16515 enum class OdrUseContext { 16516 /// Declarations in this context are not odr-used. 16517 None, 16518 /// Declarations in this context are formally odr-used, but this is a 16519 /// dependent context. 16520 Dependent, 16521 /// Declarations in this context are odr-used but not actually used (yet). 16522 FormallyOdrUsed, 16523 /// Declarations in this context are used. 16524 Used 16525 }; 16526 } 16527 16528 /// Are we within a context in which references to resolved functions or to 16529 /// variables result in odr-use? 16530 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16531 OdrUseContext Result; 16532 16533 switch (SemaRef.ExprEvalContexts.back().Context) { 16534 case Sema::ExpressionEvaluationContext::Unevaluated: 16535 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16536 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16537 return OdrUseContext::None; 16538 16539 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16540 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16541 Result = OdrUseContext::Used; 16542 break; 16543 16544 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16545 Result = OdrUseContext::FormallyOdrUsed; 16546 break; 16547 16548 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16549 // A default argument formally results in odr-use, but doesn't actually 16550 // result in a use in any real sense until it itself is used. 16551 Result = OdrUseContext::FormallyOdrUsed; 16552 break; 16553 } 16554 16555 if (SemaRef.CurContext->isDependentContext()) 16556 return OdrUseContext::Dependent; 16557 16558 return Result; 16559 } 16560 16561 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16562 return Func->isConstexpr() && 16563 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16564 } 16565 16566 /// Mark a function referenced, and check whether it is odr-used 16567 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16568 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16569 bool MightBeOdrUse) { 16570 assert(Func && "No function?"); 16571 16572 Func->setReferenced(); 16573 16574 // Recursive functions aren't really used until they're used from some other 16575 // context. 16576 bool IsRecursiveCall = CurContext == Func; 16577 16578 // C++11 [basic.def.odr]p3: 16579 // A function whose name appears as a potentially-evaluated expression is 16580 // odr-used if it is the unique lookup result or the selected member of a 16581 // set of overloaded functions [...]. 16582 // 16583 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16584 // can just check that here. 16585 OdrUseContext OdrUse = 16586 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16587 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16588 OdrUse = OdrUseContext::FormallyOdrUsed; 16589 16590 // Trivial default constructors and destructors are never actually used. 16591 // FIXME: What about other special members? 16592 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16593 OdrUse == OdrUseContext::Used) { 16594 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16595 if (Constructor->isDefaultConstructor()) 16596 OdrUse = OdrUseContext::FormallyOdrUsed; 16597 if (isa<CXXDestructorDecl>(Func)) 16598 OdrUse = OdrUseContext::FormallyOdrUsed; 16599 } 16600 16601 // C++20 [expr.const]p12: 16602 // A function [...] is needed for constant evaluation if it is [...] a 16603 // constexpr function that is named by an expression that is potentially 16604 // constant evaluated 16605 bool NeededForConstantEvaluation = 16606 isPotentiallyConstantEvaluatedContext(*this) && 16607 isImplicitlyDefinableConstexprFunction(Func); 16608 16609 // Determine whether we require a function definition to exist, per 16610 // C++11 [temp.inst]p3: 16611 // Unless a function template specialization has been explicitly 16612 // instantiated or explicitly specialized, the function template 16613 // specialization is implicitly instantiated when the specialization is 16614 // referenced in a context that requires a function definition to exist. 16615 // C++20 [temp.inst]p7: 16616 // The existence of a definition of a [...] function is considered to 16617 // affect the semantics of the program if the [...] function is needed for 16618 // constant evaluation by an expression 16619 // C++20 [basic.def.odr]p10: 16620 // Every program shall contain exactly one definition of every non-inline 16621 // function or variable that is odr-used in that program outside of a 16622 // discarded statement 16623 // C++20 [special]p1: 16624 // The implementation will implicitly define [defaulted special members] 16625 // if they are odr-used or needed for constant evaluation. 16626 // 16627 // Note that we skip the implicit instantiation of templates that are only 16628 // used in unused default arguments or by recursive calls to themselves. 16629 // This is formally non-conforming, but seems reasonable in practice. 16630 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16631 NeededForConstantEvaluation); 16632 16633 // C++14 [temp.expl.spec]p6: 16634 // If a template [...] is explicitly specialized then that specialization 16635 // shall be declared before the first use of that specialization that would 16636 // cause an implicit instantiation to take place, in every translation unit 16637 // in which such a use occurs 16638 if (NeedDefinition && 16639 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16640 Func->getMemberSpecializationInfo())) 16641 checkSpecializationVisibility(Loc, Func); 16642 16643 if (getLangOpts().CUDA) 16644 CheckCUDACall(Loc, Func); 16645 16646 if (getLangOpts().SYCLIsDevice) 16647 checkSYCLDeviceFunction(Loc, Func); 16648 16649 // If we need a definition, try to create one. 16650 if (NeedDefinition && !Func->getBody()) { 16651 runWithSufficientStackSpace(Loc, [&] { 16652 if (CXXConstructorDecl *Constructor = 16653 dyn_cast<CXXConstructorDecl>(Func)) { 16654 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16655 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16656 if (Constructor->isDefaultConstructor()) { 16657 if (Constructor->isTrivial() && 16658 !Constructor->hasAttr<DLLExportAttr>()) 16659 return; 16660 DefineImplicitDefaultConstructor(Loc, Constructor); 16661 } else if (Constructor->isCopyConstructor()) { 16662 DefineImplicitCopyConstructor(Loc, Constructor); 16663 } else if (Constructor->isMoveConstructor()) { 16664 DefineImplicitMoveConstructor(Loc, Constructor); 16665 } 16666 } else if (Constructor->getInheritedConstructor()) { 16667 DefineInheritingConstructor(Loc, Constructor); 16668 } 16669 } else if (CXXDestructorDecl *Destructor = 16670 dyn_cast<CXXDestructorDecl>(Func)) { 16671 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16672 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16673 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16674 return; 16675 DefineImplicitDestructor(Loc, Destructor); 16676 } 16677 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16678 MarkVTableUsed(Loc, Destructor->getParent()); 16679 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16680 if (MethodDecl->isOverloadedOperator() && 16681 MethodDecl->getOverloadedOperator() == OO_Equal) { 16682 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16683 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16684 if (MethodDecl->isCopyAssignmentOperator()) 16685 DefineImplicitCopyAssignment(Loc, MethodDecl); 16686 else if (MethodDecl->isMoveAssignmentOperator()) 16687 DefineImplicitMoveAssignment(Loc, MethodDecl); 16688 } 16689 } else if (isa<CXXConversionDecl>(MethodDecl) && 16690 MethodDecl->getParent()->isLambda()) { 16691 CXXConversionDecl *Conversion = 16692 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16693 if (Conversion->isLambdaToBlockPointerConversion()) 16694 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16695 else 16696 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16697 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16698 MarkVTableUsed(Loc, MethodDecl->getParent()); 16699 } 16700 16701 if (Func->isDefaulted() && !Func->isDeleted()) { 16702 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16703 if (DCK != DefaultedComparisonKind::None) 16704 DefineDefaultedComparison(Loc, Func, DCK); 16705 } 16706 16707 // Implicit instantiation of function templates and member functions of 16708 // class templates. 16709 if (Func->isImplicitlyInstantiable()) { 16710 TemplateSpecializationKind TSK = 16711 Func->getTemplateSpecializationKindForInstantiation(); 16712 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16713 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16714 if (FirstInstantiation) { 16715 PointOfInstantiation = Loc; 16716 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16717 } else if (TSK != TSK_ImplicitInstantiation) { 16718 // Use the point of use as the point of instantiation, instead of the 16719 // point of explicit instantiation (which we track as the actual point 16720 // of instantiation). This gives better backtraces in diagnostics. 16721 PointOfInstantiation = Loc; 16722 } 16723 16724 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16725 Func->isConstexpr()) { 16726 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16727 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16728 CodeSynthesisContexts.size()) 16729 PendingLocalImplicitInstantiations.push_back( 16730 std::make_pair(Func, PointOfInstantiation)); 16731 else if (Func->isConstexpr()) 16732 // Do not defer instantiations of constexpr functions, to avoid the 16733 // expression evaluator needing to call back into Sema if it sees a 16734 // call to such a function. 16735 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16736 else { 16737 Func->setInstantiationIsPending(true); 16738 PendingInstantiations.push_back( 16739 std::make_pair(Func, PointOfInstantiation)); 16740 // Notify the consumer that a function was implicitly instantiated. 16741 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16742 } 16743 } 16744 } else { 16745 // Walk redefinitions, as some of them may be instantiable. 16746 for (auto i : Func->redecls()) { 16747 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16748 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16749 } 16750 } 16751 }); 16752 } 16753 16754 // C++14 [except.spec]p17: 16755 // An exception-specification is considered to be needed when: 16756 // - the function is odr-used or, if it appears in an unevaluated operand, 16757 // would be odr-used if the expression were potentially-evaluated; 16758 // 16759 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16760 // function is a pure virtual function we're calling, and in that case the 16761 // function was selected by overload resolution and we need to resolve its 16762 // exception specification for a different reason. 16763 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16764 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16765 ResolveExceptionSpec(Loc, FPT); 16766 16767 // If this is the first "real" use, act on that. 16768 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16769 // Keep track of used but undefined functions. 16770 if (!Func->isDefined()) { 16771 if (mightHaveNonExternalLinkage(Func)) 16772 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16773 else if (Func->getMostRecentDecl()->isInlined() && 16774 !LangOpts.GNUInline && 16775 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16776 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16777 else if (isExternalWithNoLinkageType(Func)) 16778 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16779 } 16780 16781 // Some x86 Windows calling conventions mangle the size of the parameter 16782 // pack into the name. Computing the size of the parameters requires the 16783 // parameter types to be complete. Check that now. 16784 if (funcHasParameterSizeMangling(*this, Func)) 16785 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16786 16787 // In the MS C++ ABI, the compiler emits destructor variants where they are 16788 // used. If the destructor is used here but defined elsewhere, mark the 16789 // virtual base destructors referenced. If those virtual base destructors 16790 // are inline, this will ensure they are defined when emitting the complete 16791 // destructor variant. This checking may be redundant if the destructor is 16792 // provided later in this TU. 16793 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16794 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16795 CXXRecordDecl *Parent = Dtor->getParent(); 16796 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16797 CheckCompleteDestructorVariant(Loc, Dtor); 16798 } 16799 } 16800 16801 Func->markUsed(Context); 16802 } 16803 } 16804 16805 /// Directly mark a variable odr-used. Given a choice, prefer to use 16806 /// MarkVariableReferenced since it does additional checks and then 16807 /// calls MarkVarDeclODRUsed. 16808 /// If the variable must be captured: 16809 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16810 /// - else capture it in the DeclContext that maps to the 16811 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16812 static void 16813 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16814 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16815 // Keep track of used but undefined variables. 16816 // FIXME: We shouldn't suppress this warning for static data members. 16817 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16818 (!Var->isExternallyVisible() || Var->isInline() || 16819 SemaRef.isExternalWithNoLinkageType(Var)) && 16820 !(Var->isStaticDataMember() && Var->hasInit())) { 16821 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16822 if (old.isInvalid()) 16823 old = Loc; 16824 } 16825 QualType CaptureType, DeclRefType; 16826 if (SemaRef.LangOpts.OpenMP) 16827 SemaRef.tryCaptureOpenMPLambdas(Var); 16828 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16829 /*EllipsisLoc*/ SourceLocation(), 16830 /*BuildAndDiagnose*/ true, 16831 CaptureType, DeclRefType, 16832 FunctionScopeIndexToStopAt); 16833 16834 Var->markUsed(SemaRef.Context); 16835 } 16836 16837 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16838 SourceLocation Loc, 16839 unsigned CapturingScopeIndex) { 16840 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16841 } 16842 16843 static void 16844 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16845 ValueDecl *var, DeclContext *DC) { 16846 DeclContext *VarDC = var->getDeclContext(); 16847 16848 // If the parameter still belongs to the translation unit, then 16849 // we're actually just using one parameter in the declaration of 16850 // the next. 16851 if (isa<ParmVarDecl>(var) && 16852 isa<TranslationUnitDecl>(VarDC)) 16853 return; 16854 16855 // For C code, don't diagnose about capture if we're not actually in code 16856 // right now; it's impossible to write a non-constant expression outside of 16857 // function context, so we'll get other (more useful) diagnostics later. 16858 // 16859 // For C++, things get a bit more nasty... it would be nice to suppress this 16860 // diagnostic for certain cases like using a local variable in an array bound 16861 // for a member of a local class, but the correct predicate is not obvious. 16862 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16863 return; 16864 16865 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16866 unsigned ContextKind = 3; // unknown 16867 if (isa<CXXMethodDecl>(VarDC) && 16868 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16869 ContextKind = 2; 16870 } else if (isa<FunctionDecl>(VarDC)) { 16871 ContextKind = 0; 16872 } else if (isa<BlockDecl>(VarDC)) { 16873 ContextKind = 1; 16874 } 16875 16876 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16877 << var << ValueKind << ContextKind << VarDC; 16878 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16879 << var; 16880 16881 // FIXME: Add additional diagnostic info about class etc. which prevents 16882 // capture. 16883 } 16884 16885 16886 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16887 bool &SubCapturesAreNested, 16888 QualType &CaptureType, 16889 QualType &DeclRefType) { 16890 // Check whether we've already captured it. 16891 if (CSI->CaptureMap.count(Var)) { 16892 // If we found a capture, any subcaptures are nested. 16893 SubCapturesAreNested = true; 16894 16895 // Retrieve the capture type for this variable. 16896 CaptureType = CSI->getCapture(Var).getCaptureType(); 16897 16898 // Compute the type of an expression that refers to this variable. 16899 DeclRefType = CaptureType.getNonReferenceType(); 16900 16901 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16902 // are mutable in the sense that user can change their value - they are 16903 // private instances of the captured declarations. 16904 const Capture &Cap = CSI->getCapture(Var); 16905 if (Cap.isCopyCapture() && 16906 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16907 !(isa<CapturedRegionScopeInfo>(CSI) && 16908 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16909 DeclRefType.addConst(); 16910 return true; 16911 } 16912 return false; 16913 } 16914 16915 // Only block literals, captured statements, and lambda expressions can 16916 // capture; other scopes don't work. 16917 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16918 SourceLocation Loc, 16919 const bool Diagnose, Sema &S) { 16920 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16921 return getLambdaAwareParentOfDeclContext(DC); 16922 else if (Var->hasLocalStorage()) { 16923 if (Diagnose) 16924 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16925 } 16926 return nullptr; 16927 } 16928 16929 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16930 // certain types of variables (unnamed, variably modified types etc.) 16931 // so check for eligibility. 16932 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16933 SourceLocation Loc, 16934 const bool Diagnose, Sema &S) { 16935 16936 bool IsBlock = isa<BlockScopeInfo>(CSI); 16937 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16938 16939 // Lambdas are not allowed to capture unnamed variables 16940 // (e.g. anonymous unions). 16941 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16942 // assuming that's the intent. 16943 if (IsLambda && !Var->getDeclName()) { 16944 if (Diagnose) { 16945 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16946 S.Diag(Var->getLocation(), diag::note_declared_at); 16947 } 16948 return false; 16949 } 16950 16951 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16952 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16953 if (Diagnose) { 16954 S.Diag(Loc, diag::err_ref_vm_type); 16955 S.Diag(Var->getLocation(), diag::note_previous_decl) 16956 << Var->getDeclName(); 16957 } 16958 return false; 16959 } 16960 // Prohibit structs with flexible array members too. 16961 // We cannot capture what is in the tail end of the struct. 16962 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16963 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16964 if (Diagnose) { 16965 if (IsBlock) 16966 S.Diag(Loc, diag::err_ref_flexarray_type); 16967 else 16968 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16969 << Var->getDeclName(); 16970 S.Diag(Var->getLocation(), diag::note_previous_decl) 16971 << Var->getDeclName(); 16972 } 16973 return false; 16974 } 16975 } 16976 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16977 // Lambdas and captured statements are not allowed to capture __block 16978 // variables; they don't support the expected semantics. 16979 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16980 if (Diagnose) { 16981 S.Diag(Loc, diag::err_capture_block_variable) 16982 << Var->getDeclName() << !IsLambda; 16983 S.Diag(Var->getLocation(), diag::note_previous_decl) 16984 << Var->getDeclName(); 16985 } 16986 return false; 16987 } 16988 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16989 if (S.getLangOpts().OpenCL && IsBlock && 16990 Var->getType()->isBlockPointerType()) { 16991 if (Diagnose) 16992 S.Diag(Loc, diag::err_opencl_block_ref_block); 16993 return false; 16994 } 16995 16996 return true; 16997 } 16998 16999 // Returns true if the capture by block was successful. 17000 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17001 SourceLocation Loc, 17002 const bool BuildAndDiagnose, 17003 QualType &CaptureType, 17004 QualType &DeclRefType, 17005 const bool Nested, 17006 Sema &S, bool Invalid) { 17007 bool ByRef = false; 17008 17009 // Blocks are not allowed to capture arrays, excepting OpenCL. 17010 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17011 // (decayed to pointers). 17012 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17013 if (BuildAndDiagnose) { 17014 S.Diag(Loc, diag::err_ref_array_type); 17015 S.Diag(Var->getLocation(), diag::note_previous_decl) 17016 << Var->getDeclName(); 17017 Invalid = true; 17018 } else { 17019 return false; 17020 } 17021 } 17022 17023 // Forbid the block-capture of autoreleasing variables. 17024 if (!Invalid && 17025 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17026 if (BuildAndDiagnose) { 17027 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17028 << /*block*/ 0; 17029 S.Diag(Var->getLocation(), diag::note_previous_decl) 17030 << Var->getDeclName(); 17031 Invalid = true; 17032 } else { 17033 return false; 17034 } 17035 } 17036 17037 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17038 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17039 QualType PointeeTy = PT->getPointeeType(); 17040 17041 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17042 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17043 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17044 if (BuildAndDiagnose) { 17045 SourceLocation VarLoc = Var->getLocation(); 17046 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17047 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17048 } 17049 } 17050 } 17051 17052 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17053 if (HasBlocksAttr || CaptureType->isReferenceType() || 17054 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17055 // Block capture by reference does not change the capture or 17056 // declaration reference types. 17057 ByRef = true; 17058 } else { 17059 // Block capture by copy introduces 'const'. 17060 CaptureType = CaptureType.getNonReferenceType().withConst(); 17061 DeclRefType = CaptureType; 17062 } 17063 17064 // Actually capture the variable. 17065 if (BuildAndDiagnose) 17066 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17067 CaptureType, Invalid); 17068 17069 return !Invalid; 17070 } 17071 17072 17073 /// Capture the given variable in the captured region. 17074 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17075 VarDecl *Var, 17076 SourceLocation Loc, 17077 const bool BuildAndDiagnose, 17078 QualType &CaptureType, 17079 QualType &DeclRefType, 17080 const bool RefersToCapturedVariable, 17081 Sema &S, bool Invalid) { 17082 // By default, capture variables by reference. 17083 bool ByRef = true; 17084 // Using an LValue reference type is consistent with Lambdas (see below). 17085 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17086 if (S.isOpenMPCapturedDecl(Var)) { 17087 bool HasConst = DeclRefType.isConstQualified(); 17088 DeclRefType = DeclRefType.getUnqualifiedType(); 17089 // Don't lose diagnostics about assignments to const. 17090 if (HasConst) 17091 DeclRefType.addConst(); 17092 } 17093 // Do not capture firstprivates in tasks. 17094 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17095 OMPC_unknown) 17096 return true; 17097 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17098 RSI->OpenMPCaptureLevel); 17099 } 17100 17101 if (ByRef) 17102 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17103 else 17104 CaptureType = DeclRefType; 17105 17106 // Actually capture the variable. 17107 if (BuildAndDiagnose) 17108 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17109 Loc, SourceLocation(), CaptureType, Invalid); 17110 17111 return !Invalid; 17112 } 17113 17114 /// Capture the given variable in the lambda. 17115 static bool captureInLambda(LambdaScopeInfo *LSI, 17116 VarDecl *Var, 17117 SourceLocation Loc, 17118 const bool BuildAndDiagnose, 17119 QualType &CaptureType, 17120 QualType &DeclRefType, 17121 const bool RefersToCapturedVariable, 17122 const Sema::TryCaptureKind Kind, 17123 SourceLocation EllipsisLoc, 17124 const bool IsTopScope, 17125 Sema &S, bool Invalid) { 17126 // Determine whether we are capturing by reference or by value. 17127 bool ByRef = false; 17128 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17129 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17130 } else { 17131 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17132 } 17133 17134 // Compute the type of the field that will capture this variable. 17135 if (ByRef) { 17136 // C++11 [expr.prim.lambda]p15: 17137 // An entity is captured by reference if it is implicitly or 17138 // explicitly captured but not captured by copy. It is 17139 // unspecified whether additional unnamed non-static data 17140 // members are declared in the closure type for entities 17141 // captured by reference. 17142 // 17143 // FIXME: It is not clear whether we want to build an lvalue reference 17144 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17145 // to do the former, while EDG does the latter. Core issue 1249 will 17146 // clarify, but for now we follow GCC because it's a more permissive and 17147 // easily defensible position. 17148 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17149 } else { 17150 // C++11 [expr.prim.lambda]p14: 17151 // For each entity captured by copy, an unnamed non-static 17152 // data member is declared in the closure type. The 17153 // declaration order of these members is unspecified. The type 17154 // of such a data member is the type of the corresponding 17155 // captured entity if the entity is not a reference to an 17156 // object, or the referenced type otherwise. [Note: If the 17157 // captured entity is a reference to a function, the 17158 // corresponding data member is also a reference to a 17159 // function. - end note ] 17160 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17161 if (!RefType->getPointeeType()->isFunctionType()) 17162 CaptureType = RefType->getPointeeType(); 17163 } 17164 17165 // Forbid the lambda copy-capture of autoreleasing variables. 17166 if (!Invalid && 17167 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17168 if (BuildAndDiagnose) { 17169 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17170 S.Diag(Var->getLocation(), diag::note_previous_decl) 17171 << Var->getDeclName(); 17172 Invalid = true; 17173 } else { 17174 return false; 17175 } 17176 } 17177 17178 // Make sure that by-copy captures are of a complete and non-abstract type. 17179 if (!Invalid && BuildAndDiagnose) { 17180 if (!CaptureType->isDependentType() && 17181 S.RequireCompleteSizedType( 17182 Loc, CaptureType, 17183 diag::err_capture_of_incomplete_or_sizeless_type, 17184 Var->getDeclName())) 17185 Invalid = true; 17186 else if (S.RequireNonAbstractType(Loc, CaptureType, 17187 diag::err_capture_of_abstract_type)) 17188 Invalid = true; 17189 } 17190 } 17191 17192 // Compute the type of a reference to this captured variable. 17193 if (ByRef) 17194 DeclRefType = CaptureType.getNonReferenceType(); 17195 else { 17196 // C++ [expr.prim.lambda]p5: 17197 // The closure type for a lambda-expression has a public inline 17198 // function call operator [...]. This function call operator is 17199 // declared const (9.3.1) if and only if the lambda-expression's 17200 // parameter-declaration-clause is not followed by mutable. 17201 DeclRefType = CaptureType.getNonReferenceType(); 17202 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17203 DeclRefType.addConst(); 17204 } 17205 17206 // Add the capture. 17207 if (BuildAndDiagnose) 17208 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17209 Loc, EllipsisLoc, CaptureType, Invalid); 17210 17211 return !Invalid; 17212 } 17213 17214 bool Sema::tryCaptureVariable( 17215 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17216 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17217 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17218 // An init-capture is notionally from the context surrounding its 17219 // declaration, but its parent DC is the lambda class. 17220 DeclContext *VarDC = Var->getDeclContext(); 17221 if (Var->isInitCapture()) 17222 VarDC = VarDC->getParent(); 17223 17224 DeclContext *DC = CurContext; 17225 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17226 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17227 // We need to sync up the Declaration Context with the 17228 // FunctionScopeIndexToStopAt 17229 if (FunctionScopeIndexToStopAt) { 17230 unsigned FSIndex = FunctionScopes.size() - 1; 17231 while (FSIndex != MaxFunctionScopesIndex) { 17232 DC = getLambdaAwareParentOfDeclContext(DC); 17233 --FSIndex; 17234 } 17235 } 17236 17237 17238 // If the variable is declared in the current context, there is no need to 17239 // capture it. 17240 if (VarDC == DC) return true; 17241 17242 // Capture global variables if it is required to use private copy of this 17243 // variable. 17244 bool IsGlobal = !Var->hasLocalStorage(); 17245 if (IsGlobal && 17246 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17247 MaxFunctionScopesIndex))) 17248 return true; 17249 Var = Var->getCanonicalDecl(); 17250 17251 // Walk up the stack to determine whether we can capture the variable, 17252 // performing the "simple" checks that don't depend on type. We stop when 17253 // we've either hit the declared scope of the variable or find an existing 17254 // capture of that variable. We start from the innermost capturing-entity 17255 // (the DC) and ensure that all intervening capturing-entities 17256 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17257 // declcontext can either capture the variable or have already captured 17258 // the variable. 17259 CaptureType = Var->getType(); 17260 DeclRefType = CaptureType.getNonReferenceType(); 17261 bool Nested = false; 17262 bool Explicit = (Kind != TryCapture_Implicit); 17263 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17264 do { 17265 // Only block literals, captured statements, and lambda expressions can 17266 // capture; other scopes don't work. 17267 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17268 ExprLoc, 17269 BuildAndDiagnose, 17270 *this); 17271 // We need to check for the parent *first* because, if we *have* 17272 // private-captured a global variable, we need to recursively capture it in 17273 // intermediate blocks, lambdas, etc. 17274 if (!ParentDC) { 17275 if (IsGlobal) { 17276 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17277 break; 17278 } 17279 return true; 17280 } 17281 17282 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17283 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17284 17285 17286 // Check whether we've already captured it. 17287 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17288 DeclRefType)) { 17289 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17290 break; 17291 } 17292 // If we are instantiating a generic lambda call operator body, 17293 // we do not want to capture new variables. What was captured 17294 // during either a lambdas transformation or initial parsing 17295 // should be used. 17296 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17297 if (BuildAndDiagnose) { 17298 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17299 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17300 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17301 Diag(Var->getLocation(), diag::note_previous_decl) 17302 << Var->getDeclName(); 17303 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17304 } else 17305 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17306 } 17307 return true; 17308 } 17309 17310 // Try to capture variable-length arrays types. 17311 if (Var->getType()->isVariablyModifiedType()) { 17312 // We're going to walk down into the type and look for VLA 17313 // expressions. 17314 QualType QTy = Var->getType(); 17315 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17316 QTy = PVD->getOriginalType(); 17317 captureVariablyModifiedType(Context, QTy, CSI); 17318 } 17319 17320 if (getLangOpts().OpenMP) { 17321 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17322 // OpenMP private variables should not be captured in outer scope, so 17323 // just break here. Similarly, global variables that are captured in a 17324 // target region should not be captured outside the scope of the region. 17325 if (RSI->CapRegionKind == CR_OpenMP) { 17326 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17327 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17328 // If the variable is private (i.e. not captured) and has variably 17329 // modified type, we still need to capture the type for correct 17330 // codegen in all regions, associated with the construct. Currently, 17331 // it is captured in the innermost captured region only. 17332 if (IsOpenMPPrivateDecl != OMPC_unknown && 17333 Var->getType()->isVariablyModifiedType()) { 17334 QualType QTy = Var->getType(); 17335 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17336 QTy = PVD->getOriginalType(); 17337 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17338 I < E; ++I) { 17339 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17340 FunctionScopes[FunctionScopesIndex - I]); 17341 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17342 "Wrong number of captured regions associated with the " 17343 "OpenMP construct."); 17344 captureVariablyModifiedType(Context, QTy, OuterRSI); 17345 } 17346 } 17347 bool IsTargetCap = 17348 IsOpenMPPrivateDecl != OMPC_private && 17349 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17350 RSI->OpenMPCaptureLevel); 17351 // Do not capture global if it is not privatized in outer regions. 17352 bool IsGlobalCap = 17353 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17354 RSI->OpenMPCaptureLevel); 17355 17356 // When we detect target captures we are looking from inside the 17357 // target region, therefore we need to propagate the capture from the 17358 // enclosing region. Therefore, the capture is not initially nested. 17359 if (IsTargetCap) 17360 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17361 17362 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17363 (IsGlobal && !IsGlobalCap)) { 17364 Nested = !IsTargetCap; 17365 DeclRefType = DeclRefType.getUnqualifiedType(); 17366 CaptureType = Context.getLValueReferenceType(DeclRefType); 17367 break; 17368 } 17369 } 17370 } 17371 } 17372 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17373 // No capture-default, and this is not an explicit capture 17374 // so cannot capture this variable. 17375 if (BuildAndDiagnose) { 17376 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17377 Diag(Var->getLocation(), diag::note_previous_decl) 17378 << Var->getDeclName(); 17379 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17380 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17381 diag::note_lambda_decl); 17382 // FIXME: If we error out because an outer lambda can not implicitly 17383 // capture a variable that an inner lambda explicitly captures, we 17384 // should have the inner lambda do the explicit capture - because 17385 // it makes for cleaner diagnostics later. This would purely be done 17386 // so that the diagnostic does not misleadingly claim that a variable 17387 // can not be captured by a lambda implicitly even though it is captured 17388 // explicitly. Suggestion: 17389 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17390 // at the function head 17391 // - cache the StartingDeclContext - this must be a lambda 17392 // - captureInLambda in the innermost lambda the variable. 17393 } 17394 return true; 17395 } 17396 17397 FunctionScopesIndex--; 17398 DC = ParentDC; 17399 Explicit = false; 17400 } while (!VarDC->Equals(DC)); 17401 17402 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17403 // computing the type of the capture at each step, checking type-specific 17404 // requirements, and adding captures if requested. 17405 // If the variable had already been captured previously, we start capturing 17406 // at the lambda nested within that one. 17407 bool Invalid = false; 17408 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17409 ++I) { 17410 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17411 17412 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17413 // certain types of variables (unnamed, variably modified types etc.) 17414 // so check for eligibility. 17415 if (!Invalid) 17416 Invalid = 17417 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17418 17419 // After encountering an error, if we're actually supposed to capture, keep 17420 // capturing in nested contexts to suppress any follow-on diagnostics. 17421 if (Invalid && !BuildAndDiagnose) 17422 return true; 17423 17424 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17425 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17426 DeclRefType, Nested, *this, Invalid); 17427 Nested = true; 17428 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17429 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17430 CaptureType, DeclRefType, Nested, 17431 *this, Invalid); 17432 Nested = true; 17433 } else { 17434 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17435 Invalid = 17436 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17437 DeclRefType, Nested, Kind, EllipsisLoc, 17438 /*IsTopScope*/ I == N - 1, *this, Invalid); 17439 Nested = true; 17440 } 17441 17442 if (Invalid && !BuildAndDiagnose) 17443 return true; 17444 } 17445 return Invalid; 17446 } 17447 17448 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17449 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17450 QualType CaptureType; 17451 QualType DeclRefType; 17452 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17453 /*BuildAndDiagnose=*/true, CaptureType, 17454 DeclRefType, nullptr); 17455 } 17456 17457 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17458 QualType CaptureType; 17459 QualType DeclRefType; 17460 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17461 /*BuildAndDiagnose=*/false, CaptureType, 17462 DeclRefType, nullptr); 17463 } 17464 17465 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17466 QualType CaptureType; 17467 QualType DeclRefType; 17468 17469 // Determine whether we can capture this variable. 17470 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17471 /*BuildAndDiagnose=*/false, CaptureType, 17472 DeclRefType, nullptr)) 17473 return QualType(); 17474 17475 return DeclRefType; 17476 } 17477 17478 namespace { 17479 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17480 // The produced TemplateArgumentListInfo* points to data stored within this 17481 // object, so should only be used in contexts where the pointer will not be 17482 // used after the CopiedTemplateArgs object is destroyed. 17483 class CopiedTemplateArgs { 17484 bool HasArgs; 17485 TemplateArgumentListInfo TemplateArgStorage; 17486 public: 17487 template<typename RefExpr> 17488 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17489 if (HasArgs) 17490 E->copyTemplateArgumentsInto(TemplateArgStorage); 17491 } 17492 operator TemplateArgumentListInfo*() 17493 #ifdef __has_cpp_attribute 17494 #if __has_cpp_attribute(clang::lifetimebound) 17495 [[clang::lifetimebound]] 17496 #endif 17497 #endif 17498 { 17499 return HasArgs ? &TemplateArgStorage : nullptr; 17500 } 17501 }; 17502 } 17503 17504 /// Walk the set of potential results of an expression and mark them all as 17505 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17506 /// 17507 /// \return A new expression if we found any potential results, ExprEmpty() if 17508 /// not, and ExprError() if we diagnosed an error. 17509 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17510 NonOdrUseReason NOUR) { 17511 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17512 // an object that satisfies the requirements for appearing in a 17513 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17514 // is immediately applied." This function handles the lvalue-to-rvalue 17515 // conversion part. 17516 // 17517 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17518 // transform it into the relevant kind of non-odr-use node and rebuild the 17519 // tree of nodes leading to it. 17520 // 17521 // This is a mini-TreeTransform that only transforms a restricted subset of 17522 // nodes (and only certain operands of them). 17523 17524 // Rebuild a subexpression. 17525 auto Rebuild = [&](Expr *Sub) { 17526 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17527 }; 17528 17529 // Check whether a potential result satisfies the requirements of NOUR. 17530 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17531 // Any entity other than a VarDecl is always odr-used whenever it's named 17532 // in a potentially-evaluated expression. 17533 auto *VD = dyn_cast<VarDecl>(D); 17534 if (!VD) 17535 return true; 17536 17537 // C++2a [basic.def.odr]p4: 17538 // A variable x whose name appears as a potentially-evalauted expression 17539 // e is odr-used by e unless 17540 // -- x is a reference that is usable in constant expressions, or 17541 // -- x is a variable of non-reference type that is usable in constant 17542 // expressions and has no mutable subobjects, and e is an element of 17543 // the set of potential results of an expression of 17544 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17545 // conversion is applied, or 17546 // -- x is a variable of non-reference type, and e is an element of the 17547 // set of potential results of a discarded-value expression to which 17548 // the lvalue-to-rvalue conversion is not applied 17549 // 17550 // We check the first bullet and the "potentially-evaluated" condition in 17551 // BuildDeclRefExpr. We check the type requirements in the second bullet 17552 // in CheckLValueToRValueConversionOperand below. 17553 switch (NOUR) { 17554 case NOUR_None: 17555 case NOUR_Unevaluated: 17556 llvm_unreachable("unexpected non-odr-use-reason"); 17557 17558 case NOUR_Constant: 17559 // Constant references were handled when they were built. 17560 if (VD->getType()->isReferenceType()) 17561 return true; 17562 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17563 if (RD->hasMutableFields()) 17564 return true; 17565 if (!VD->isUsableInConstantExpressions(S.Context)) 17566 return true; 17567 break; 17568 17569 case NOUR_Discarded: 17570 if (VD->getType()->isReferenceType()) 17571 return true; 17572 break; 17573 } 17574 return false; 17575 }; 17576 17577 // Mark that this expression does not constitute an odr-use. 17578 auto MarkNotOdrUsed = [&] { 17579 S.MaybeODRUseExprs.remove(E); 17580 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17581 LSI->markVariableExprAsNonODRUsed(E); 17582 }; 17583 17584 // C++2a [basic.def.odr]p2: 17585 // The set of potential results of an expression e is defined as follows: 17586 switch (E->getStmtClass()) { 17587 // -- If e is an id-expression, ... 17588 case Expr::DeclRefExprClass: { 17589 auto *DRE = cast<DeclRefExpr>(E); 17590 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17591 break; 17592 17593 // Rebuild as a non-odr-use DeclRefExpr. 17594 MarkNotOdrUsed(); 17595 return DeclRefExpr::Create( 17596 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17597 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17598 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17599 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17600 } 17601 17602 case Expr::FunctionParmPackExprClass: { 17603 auto *FPPE = cast<FunctionParmPackExpr>(E); 17604 // If any of the declarations in the pack is odr-used, then the expression 17605 // as a whole constitutes an odr-use. 17606 for (VarDecl *D : *FPPE) 17607 if (IsPotentialResultOdrUsed(D)) 17608 return ExprEmpty(); 17609 17610 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17611 // nothing cares about whether we marked this as an odr-use, but it might 17612 // be useful for non-compiler tools. 17613 MarkNotOdrUsed(); 17614 break; 17615 } 17616 17617 // -- If e is a subscripting operation with an array operand... 17618 case Expr::ArraySubscriptExprClass: { 17619 auto *ASE = cast<ArraySubscriptExpr>(E); 17620 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17621 if (!OldBase->getType()->isArrayType()) 17622 break; 17623 ExprResult Base = Rebuild(OldBase); 17624 if (!Base.isUsable()) 17625 return Base; 17626 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17627 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17628 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17629 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17630 ASE->getRBracketLoc()); 17631 } 17632 17633 case Expr::MemberExprClass: { 17634 auto *ME = cast<MemberExpr>(E); 17635 // -- If e is a class member access expression [...] naming a non-static 17636 // data member... 17637 if (isa<FieldDecl>(ME->getMemberDecl())) { 17638 ExprResult Base = Rebuild(ME->getBase()); 17639 if (!Base.isUsable()) 17640 return Base; 17641 return MemberExpr::Create( 17642 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17643 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17644 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17645 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17646 ME->getObjectKind(), ME->isNonOdrUse()); 17647 } 17648 17649 if (ME->getMemberDecl()->isCXXInstanceMember()) 17650 break; 17651 17652 // -- If e is a class member access expression naming a static data member, 17653 // ... 17654 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17655 break; 17656 17657 // Rebuild as a non-odr-use MemberExpr. 17658 MarkNotOdrUsed(); 17659 return MemberExpr::Create( 17660 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17661 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17662 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17663 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17664 return ExprEmpty(); 17665 } 17666 17667 case Expr::BinaryOperatorClass: { 17668 auto *BO = cast<BinaryOperator>(E); 17669 Expr *LHS = BO->getLHS(); 17670 Expr *RHS = BO->getRHS(); 17671 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17672 if (BO->getOpcode() == BO_PtrMemD) { 17673 ExprResult Sub = Rebuild(LHS); 17674 if (!Sub.isUsable()) 17675 return Sub; 17676 LHS = Sub.get(); 17677 // -- If e is a comma expression, ... 17678 } else if (BO->getOpcode() == BO_Comma) { 17679 ExprResult Sub = Rebuild(RHS); 17680 if (!Sub.isUsable()) 17681 return Sub; 17682 RHS = Sub.get(); 17683 } else { 17684 break; 17685 } 17686 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17687 LHS, RHS); 17688 } 17689 17690 // -- If e has the form (e1)... 17691 case Expr::ParenExprClass: { 17692 auto *PE = cast<ParenExpr>(E); 17693 ExprResult Sub = Rebuild(PE->getSubExpr()); 17694 if (!Sub.isUsable()) 17695 return Sub; 17696 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17697 } 17698 17699 // -- If e is a glvalue conditional expression, ... 17700 // We don't apply this to a binary conditional operator. FIXME: Should we? 17701 case Expr::ConditionalOperatorClass: { 17702 auto *CO = cast<ConditionalOperator>(E); 17703 ExprResult LHS = Rebuild(CO->getLHS()); 17704 if (LHS.isInvalid()) 17705 return ExprError(); 17706 ExprResult RHS = Rebuild(CO->getRHS()); 17707 if (RHS.isInvalid()) 17708 return ExprError(); 17709 if (!LHS.isUsable() && !RHS.isUsable()) 17710 return ExprEmpty(); 17711 if (!LHS.isUsable()) 17712 LHS = CO->getLHS(); 17713 if (!RHS.isUsable()) 17714 RHS = CO->getRHS(); 17715 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17716 CO->getCond(), LHS.get(), RHS.get()); 17717 } 17718 17719 // [Clang extension] 17720 // -- If e has the form __extension__ e1... 17721 case Expr::UnaryOperatorClass: { 17722 auto *UO = cast<UnaryOperator>(E); 17723 if (UO->getOpcode() != UO_Extension) 17724 break; 17725 ExprResult Sub = Rebuild(UO->getSubExpr()); 17726 if (!Sub.isUsable()) 17727 return Sub; 17728 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17729 Sub.get()); 17730 } 17731 17732 // [Clang extension] 17733 // -- If e has the form _Generic(...), the set of potential results is the 17734 // union of the sets of potential results of the associated expressions. 17735 case Expr::GenericSelectionExprClass: { 17736 auto *GSE = cast<GenericSelectionExpr>(E); 17737 17738 SmallVector<Expr *, 4> AssocExprs; 17739 bool AnyChanged = false; 17740 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17741 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17742 if (AssocExpr.isInvalid()) 17743 return ExprError(); 17744 if (AssocExpr.isUsable()) { 17745 AssocExprs.push_back(AssocExpr.get()); 17746 AnyChanged = true; 17747 } else { 17748 AssocExprs.push_back(OrigAssocExpr); 17749 } 17750 } 17751 17752 return AnyChanged ? S.CreateGenericSelectionExpr( 17753 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17754 GSE->getRParenLoc(), GSE->getControllingExpr(), 17755 GSE->getAssocTypeSourceInfos(), AssocExprs) 17756 : ExprEmpty(); 17757 } 17758 17759 // [Clang extension] 17760 // -- If e has the form __builtin_choose_expr(...), the set of potential 17761 // results is the union of the sets of potential results of the 17762 // second and third subexpressions. 17763 case Expr::ChooseExprClass: { 17764 auto *CE = cast<ChooseExpr>(E); 17765 17766 ExprResult LHS = Rebuild(CE->getLHS()); 17767 if (LHS.isInvalid()) 17768 return ExprError(); 17769 17770 ExprResult RHS = Rebuild(CE->getLHS()); 17771 if (RHS.isInvalid()) 17772 return ExprError(); 17773 17774 if (!LHS.get() && !RHS.get()) 17775 return ExprEmpty(); 17776 if (!LHS.isUsable()) 17777 LHS = CE->getLHS(); 17778 if (!RHS.isUsable()) 17779 RHS = CE->getRHS(); 17780 17781 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17782 RHS.get(), CE->getRParenLoc()); 17783 } 17784 17785 // Step through non-syntactic nodes. 17786 case Expr::ConstantExprClass: { 17787 auto *CE = cast<ConstantExpr>(E); 17788 ExprResult Sub = Rebuild(CE->getSubExpr()); 17789 if (!Sub.isUsable()) 17790 return Sub; 17791 return ConstantExpr::Create(S.Context, Sub.get()); 17792 } 17793 17794 // We could mostly rely on the recursive rebuilding to rebuild implicit 17795 // casts, but not at the top level, so rebuild them here. 17796 case Expr::ImplicitCastExprClass: { 17797 auto *ICE = cast<ImplicitCastExpr>(E); 17798 // Only step through the narrow set of cast kinds we expect to encounter. 17799 // Anything else suggests we've left the region in which potential results 17800 // can be found. 17801 switch (ICE->getCastKind()) { 17802 case CK_NoOp: 17803 case CK_DerivedToBase: 17804 case CK_UncheckedDerivedToBase: { 17805 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17806 if (!Sub.isUsable()) 17807 return Sub; 17808 CXXCastPath Path(ICE->path()); 17809 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17810 ICE->getValueKind(), &Path); 17811 } 17812 17813 default: 17814 break; 17815 } 17816 break; 17817 } 17818 17819 default: 17820 break; 17821 } 17822 17823 // Can't traverse through this node. Nothing to do. 17824 return ExprEmpty(); 17825 } 17826 17827 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17828 // Check whether the operand is or contains an object of non-trivial C union 17829 // type. 17830 if (E->getType().isVolatileQualified() && 17831 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17832 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17833 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17834 Sema::NTCUC_LValueToRValueVolatile, 17835 NTCUK_Destruct|NTCUK_Copy); 17836 17837 // C++2a [basic.def.odr]p4: 17838 // [...] an expression of non-volatile-qualified non-class type to which 17839 // the lvalue-to-rvalue conversion is applied [...] 17840 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17841 return E; 17842 17843 ExprResult Result = 17844 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17845 if (Result.isInvalid()) 17846 return ExprError(); 17847 return Result.get() ? Result : E; 17848 } 17849 17850 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17851 Res = CorrectDelayedTyposInExpr(Res); 17852 17853 if (!Res.isUsable()) 17854 return Res; 17855 17856 // If a constant-expression is a reference to a variable where we delay 17857 // deciding whether it is an odr-use, just assume we will apply the 17858 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17859 // (a non-type template argument), we have special handling anyway. 17860 return CheckLValueToRValueConversionOperand(Res.get()); 17861 } 17862 17863 void Sema::CleanupVarDeclMarking() { 17864 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17865 // call. 17866 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17867 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17868 17869 for (Expr *E : LocalMaybeODRUseExprs) { 17870 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17871 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17872 DRE->getLocation(), *this); 17873 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17874 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17875 *this); 17876 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17877 for (VarDecl *VD : *FP) 17878 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17879 } else { 17880 llvm_unreachable("Unexpected expression"); 17881 } 17882 } 17883 17884 assert(MaybeODRUseExprs.empty() && 17885 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17886 } 17887 17888 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17889 VarDecl *Var, Expr *E) { 17890 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17891 isa<FunctionParmPackExpr>(E)) && 17892 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17893 Var->setReferenced(); 17894 17895 if (Var->isInvalidDecl()) 17896 return; 17897 17898 auto *MSI = Var->getMemberSpecializationInfo(); 17899 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17900 : Var->getTemplateSpecializationKind(); 17901 17902 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17903 bool UsableInConstantExpr = 17904 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17905 17906 // C++20 [expr.const]p12: 17907 // A variable [...] is needed for constant evaluation if it is [...] a 17908 // variable whose name appears as a potentially constant evaluated 17909 // expression that is either a contexpr variable or is of non-volatile 17910 // const-qualified integral type or of reference type 17911 bool NeededForConstantEvaluation = 17912 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17913 17914 bool NeedDefinition = 17915 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17916 17917 VarTemplateSpecializationDecl *VarSpec = 17918 dyn_cast<VarTemplateSpecializationDecl>(Var); 17919 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17920 "Can't instantiate a partial template specialization."); 17921 17922 // If this might be a member specialization of a static data member, check 17923 // the specialization is visible. We already did the checks for variable 17924 // template specializations when we created them. 17925 if (NeedDefinition && TSK != TSK_Undeclared && 17926 !isa<VarTemplateSpecializationDecl>(Var)) 17927 SemaRef.checkSpecializationVisibility(Loc, Var); 17928 17929 // Perform implicit instantiation of static data members, static data member 17930 // templates of class templates, and variable template specializations. Delay 17931 // instantiations of variable templates, except for those that could be used 17932 // in a constant expression. 17933 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17934 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17935 // instantiation declaration if a variable is usable in a constant 17936 // expression (among other cases). 17937 bool TryInstantiating = 17938 TSK == TSK_ImplicitInstantiation || 17939 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17940 17941 if (TryInstantiating) { 17942 SourceLocation PointOfInstantiation = 17943 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17944 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17945 if (FirstInstantiation) { 17946 PointOfInstantiation = Loc; 17947 if (MSI) 17948 MSI->setPointOfInstantiation(PointOfInstantiation); 17949 else 17950 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17951 } 17952 17953 bool InstantiationDependent = false; 17954 bool IsNonDependent = 17955 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17956 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17957 : true; 17958 17959 // Do not instantiate specializations that are still type-dependent. 17960 if (IsNonDependent) { 17961 if (UsableInConstantExpr) { 17962 // Do not defer instantiations of variables that could be used in a 17963 // constant expression. 17964 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17965 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17966 }); 17967 } else if (FirstInstantiation || 17968 isa<VarTemplateSpecializationDecl>(Var)) { 17969 // FIXME: For a specialization of a variable template, we don't 17970 // distinguish between "declaration and type implicitly instantiated" 17971 // and "implicit instantiation of definition requested", so we have 17972 // no direct way to avoid enqueueing the pending instantiation 17973 // multiple times. 17974 SemaRef.PendingInstantiations 17975 .push_back(std::make_pair(Var, PointOfInstantiation)); 17976 } 17977 } 17978 } 17979 } 17980 17981 // C++2a [basic.def.odr]p4: 17982 // A variable x whose name appears as a potentially-evaluated expression e 17983 // is odr-used by e unless 17984 // -- x is a reference that is usable in constant expressions 17985 // -- x is a variable of non-reference type that is usable in constant 17986 // expressions and has no mutable subobjects [FIXME], and e is an 17987 // element of the set of potential results of an expression of 17988 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17989 // conversion is applied 17990 // -- x is a variable of non-reference type, and e is an element of the set 17991 // of potential results of a discarded-value expression to which the 17992 // lvalue-to-rvalue conversion is not applied [FIXME] 17993 // 17994 // We check the first part of the second bullet here, and 17995 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17996 // FIXME: To get the third bullet right, we need to delay this even for 17997 // variables that are not usable in constant expressions. 17998 17999 // If we already know this isn't an odr-use, there's nothing more to do. 18000 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18001 if (DRE->isNonOdrUse()) 18002 return; 18003 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18004 if (ME->isNonOdrUse()) 18005 return; 18006 18007 switch (OdrUse) { 18008 case OdrUseContext::None: 18009 assert((!E || isa<FunctionParmPackExpr>(E)) && 18010 "missing non-odr-use marking for unevaluated decl ref"); 18011 break; 18012 18013 case OdrUseContext::FormallyOdrUsed: 18014 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18015 // behavior. 18016 break; 18017 18018 case OdrUseContext::Used: 18019 // If we might later find that this expression isn't actually an odr-use, 18020 // delay the marking. 18021 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18022 SemaRef.MaybeODRUseExprs.insert(E); 18023 else 18024 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18025 break; 18026 18027 case OdrUseContext::Dependent: 18028 // If this is a dependent context, we don't need to mark variables as 18029 // odr-used, but we may still need to track them for lambda capture. 18030 // FIXME: Do we also need to do this inside dependent typeid expressions 18031 // (which are modeled as unevaluated at this point)? 18032 const bool RefersToEnclosingScope = 18033 (SemaRef.CurContext != Var->getDeclContext() && 18034 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18035 if (RefersToEnclosingScope) { 18036 LambdaScopeInfo *const LSI = 18037 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18038 if (LSI && (!LSI->CallOperator || 18039 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18040 // If a variable could potentially be odr-used, defer marking it so 18041 // until we finish analyzing the full expression for any 18042 // lvalue-to-rvalue 18043 // or discarded value conversions that would obviate odr-use. 18044 // Add it to the list of potential captures that will be analyzed 18045 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18046 // unless the variable is a reference that was initialized by a constant 18047 // expression (this will never need to be captured or odr-used). 18048 // 18049 // FIXME: We can simplify this a lot after implementing P0588R1. 18050 assert(E && "Capture variable should be used in an expression."); 18051 if (!Var->getType()->isReferenceType() || 18052 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18053 LSI->addPotentialCapture(E->IgnoreParens()); 18054 } 18055 } 18056 break; 18057 } 18058 } 18059 18060 /// Mark a variable referenced, and check whether it is odr-used 18061 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18062 /// used directly for normal expressions referring to VarDecl. 18063 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18064 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18065 } 18066 18067 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18068 Decl *D, Expr *E, bool MightBeOdrUse) { 18069 if (SemaRef.isInOpenMPDeclareTargetContext()) 18070 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18071 18072 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18073 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18074 return; 18075 } 18076 18077 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18078 18079 // If this is a call to a method via a cast, also mark the method in the 18080 // derived class used in case codegen can devirtualize the call. 18081 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18082 if (!ME) 18083 return; 18084 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18085 if (!MD) 18086 return; 18087 // Only attempt to devirtualize if this is truly a virtual call. 18088 bool IsVirtualCall = MD->isVirtual() && 18089 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18090 if (!IsVirtualCall) 18091 return; 18092 18093 // If it's possible to devirtualize the call, mark the called function 18094 // referenced. 18095 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18096 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18097 if (DM) 18098 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18099 } 18100 18101 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18102 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18103 // TODO: update this with DR# once a defect report is filed. 18104 // C++11 defect. The address of a pure member should not be an ODR use, even 18105 // if it's a qualified reference. 18106 bool OdrUse = true; 18107 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18108 if (Method->isVirtual() && 18109 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18110 OdrUse = false; 18111 18112 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18113 if (!isConstantEvaluated() && FD->isConsteval() && 18114 !RebuildingImmediateInvocation) 18115 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18116 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18117 } 18118 18119 /// Perform reference-marking and odr-use handling for a MemberExpr. 18120 void Sema::MarkMemberReferenced(MemberExpr *E) { 18121 // C++11 [basic.def.odr]p2: 18122 // A non-overloaded function whose name appears as a potentially-evaluated 18123 // expression or a member of a set of candidate functions, if selected by 18124 // overload resolution when referred to from a potentially-evaluated 18125 // expression, is odr-used, unless it is a pure virtual function and its 18126 // name is not explicitly qualified. 18127 bool MightBeOdrUse = true; 18128 if (E->performsVirtualDispatch(getLangOpts())) { 18129 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18130 if (Method->isPure()) 18131 MightBeOdrUse = false; 18132 } 18133 SourceLocation Loc = 18134 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18135 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18136 } 18137 18138 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18139 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18140 for (VarDecl *VD : *E) 18141 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18142 } 18143 18144 /// Perform marking for a reference to an arbitrary declaration. It 18145 /// marks the declaration referenced, and performs odr-use checking for 18146 /// functions and variables. This method should not be used when building a 18147 /// normal expression which refers to a variable. 18148 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18149 bool MightBeOdrUse) { 18150 if (MightBeOdrUse) { 18151 if (auto *VD = dyn_cast<VarDecl>(D)) { 18152 MarkVariableReferenced(Loc, VD); 18153 return; 18154 } 18155 } 18156 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18157 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18158 return; 18159 } 18160 D->setReferenced(); 18161 } 18162 18163 namespace { 18164 // Mark all of the declarations used by a type as referenced. 18165 // FIXME: Not fully implemented yet! We need to have a better understanding 18166 // of when we're entering a context we should not recurse into. 18167 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18168 // TreeTransforms rebuilding the type in a new context. Rather than 18169 // duplicating the TreeTransform logic, we should consider reusing it here. 18170 // Currently that causes problems when rebuilding LambdaExprs. 18171 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18172 Sema &S; 18173 SourceLocation Loc; 18174 18175 public: 18176 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18177 18178 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18179 18180 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18181 }; 18182 } 18183 18184 bool MarkReferencedDecls::TraverseTemplateArgument( 18185 const TemplateArgument &Arg) { 18186 { 18187 // A non-type template argument is a constant-evaluated context. 18188 EnterExpressionEvaluationContext Evaluated( 18189 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18190 if (Arg.getKind() == TemplateArgument::Declaration) { 18191 if (Decl *D = Arg.getAsDecl()) 18192 S.MarkAnyDeclReferenced(Loc, D, true); 18193 } else if (Arg.getKind() == TemplateArgument::Expression) { 18194 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18195 } 18196 } 18197 18198 return Inherited::TraverseTemplateArgument(Arg); 18199 } 18200 18201 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18202 MarkReferencedDecls Marker(*this, Loc); 18203 Marker.TraverseType(T); 18204 } 18205 18206 namespace { 18207 /// Helper class that marks all of the declarations referenced by 18208 /// potentially-evaluated subexpressions as "referenced". 18209 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18210 public: 18211 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18212 bool SkipLocalVariables; 18213 18214 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18215 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18216 18217 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18218 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18219 } 18220 18221 void VisitDeclRefExpr(DeclRefExpr *E) { 18222 // If we were asked not to visit local variables, don't. 18223 if (SkipLocalVariables) { 18224 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18225 if (VD->hasLocalStorage()) 18226 return; 18227 } 18228 S.MarkDeclRefReferenced(E); 18229 } 18230 18231 void VisitMemberExpr(MemberExpr *E) { 18232 S.MarkMemberReferenced(E); 18233 Visit(E->getBase()); 18234 } 18235 }; 18236 } // namespace 18237 18238 /// Mark any declarations that appear within this expression or any 18239 /// potentially-evaluated subexpressions as "referenced". 18240 /// 18241 /// \param SkipLocalVariables If true, don't mark local variables as 18242 /// 'referenced'. 18243 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18244 bool SkipLocalVariables) { 18245 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18246 } 18247 18248 /// Emit a diagnostic that describes an effect on the run-time behavior 18249 /// of the program being compiled. 18250 /// 18251 /// This routine emits the given diagnostic when the code currently being 18252 /// type-checked is "potentially evaluated", meaning that there is a 18253 /// possibility that the code will actually be executable. Code in sizeof() 18254 /// expressions, code used only during overload resolution, etc., are not 18255 /// potentially evaluated. This routine will suppress such diagnostics or, 18256 /// in the absolutely nutty case of potentially potentially evaluated 18257 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18258 /// later. 18259 /// 18260 /// This routine should be used for all diagnostics that describe the run-time 18261 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18262 /// Failure to do so will likely result in spurious diagnostics or failures 18263 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18264 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18265 const PartialDiagnostic &PD) { 18266 switch (ExprEvalContexts.back().Context) { 18267 case ExpressionEvaluationContext::Unevaluated: 18268 case ExpressionEvaluationContext::UnevaluatedList: 18269 case ExpressionEvaluationContext::UnevaluatedAbstract: 18270 case ExpressionEvaluationContext::DiscardedStatement: 18271 // The argument will never be evaluated, so don't complain. 18272 break; 18273 18274 case ExpressionEvaluationContext::ConstantEvaluated: 18275 // Relevant diagnostics should be produced by constant evaluation. 18276 break; 18277 18278 case ExpressionEvaluationContext::PotentiallyEvaluated: 18279 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18280 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18281 FunctionScopes.back()->PossiblyUnreachableDiags. 18282 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18283 return true; 18284 } 18285 18286 // The initializer of a constexpr variable or of the first declaration of a 18287 // static data member is not syntactically a constant evaluated constant, 18288 // but nonetheless is always required to be a constant expression, so we 18289 // can skip diagnosing. 18290 // FIXME: Using the mangling context here is a hack. 18291 if (auto *VD = dyn_cast_or_null<VarDecl>( 18292 ExprEvalContexts.back().ManglingContextDecl)) { 18293 if (VD->isConstexpr() || 18294 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18295 break; 18296 // FIXME: For any other kind of variable, we should build a CFG for its 18297 // initializer and check whether the context in question is reachable. 18298 } 18299 18300 Diag(Loc, PD); 18301 return true; 18302 } 18303 18304 return false; 18305 } 18306 18307 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18308 const PartialDiagnostic &PD) { 18309 return DiagRuntimeBehavior( 18310 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18311 } 18312 18313 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18314 CallExpr *CE, FunctionDecl *FD) { 18315 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18316 return false; 18317 18318 // If we're inside a decltype's expression, don't check for a valid return 18319 // type or construct temporaries until we know whether this is the last call. 18320 if (ExprEvalContexts.back().ExprContext == 18321 ExpressionEvaluationContextRecord::EK_Decltype) { 18322 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18323 return false; 18324 } 18325 18326 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18327 FunctionDecl *FD; 18328 CallExpr *CE; 18329 18330 public: 18331 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18332 : FD(FD), CE(CE) { } 18333 18334 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18335 if (!FD) { 18336 S.Diag(Loc, diag::err_call_incomplete_return) 18337 << T << CE->getSourceRange(); 18338 return; 18339 } 18340 18341 S.Diag(Loc, diag::err_call_function_incomplete_return) 18342 << CE->getSourceRange() << FD->getDeclName() << T; 18343 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18344 << FD->getDeclName(); 18345 } 18346 } Diagnoser(FD, CE); 18347 18348 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18349 return true; 18350 18351 return false; 18352 } 18353 18354 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18355 // will prevent this condition from triggering, which is what we want. 18356 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18357 SourceLocation Loc; 18358 18359 unsigned diagnostic = diag::warn_condition_is_assignment; 18360 bool IsOrAssign = false; 18361 18362 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18363 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18364 return; 18365 18366 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18367 18368 // Greylist some idioms by putting them into a warning subcategory. 18369 if (ObjCMessageExpr *ME 18370 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18371 Selector Sel = ME->getSelector(); 18372 18373 // self = [<foo> init...] 18374 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18375 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18376 18377 // <foo> = [<bar> nextObject] 18378 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18379 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18380 } 18381 18382 Loc = Op->getOperatorLoc(); 18383 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18384 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18385 return; 18386 18387 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18388 Loc = Op->getOperatorLoc(); 18389 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18390 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18391 else { 18392 // Not an assignment. 18393 return; 18394 } 18395 18396 Diag(Loc, diagnostic) << E->getSourceRange(); 18397 18398 SourceLocation Open = E->getBeginLoc(); 18399 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18400 Diag(Loc, diag::note_condition_assign_silence) 18401 << FixItHint::CreateInsertion(Open, "(") 18402 << FixItHint::CreateInsertion(Close, ")"); 18403 18404 if (IsOrAssign) 18405 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18406 << FixItHint::CreateReplacement(Loc, "!="); 18407 else 18408 Diag(Loc, diag::note_condition_assign_to_comparison) 18409 << FixItHint::CreateReplacement(Loc, "=="); 18410 } 18411 18412 /// Redundant parentheses over an equality comparison can indicate 18413 /// that the user intended an assignment used as condition. 18414 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18415 // Don't warn if the parens came from a macro. 18416 SourceLocation parenLoc = ParenE->getBeginLoc(); 18417 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18418 return; 18419 // Don't warn for dependent expressions. 18420 if (ParenE->isTypeDependent()) 18421 return; 18422 18423 Expr *E = ParenE->IgnoreParens(); 18424 18425 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18426 if (opE->getOpcode() == BO_EQ && 18427 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18428 == Expr::MLV_Valid) { 18429 SourceLocation Loc = opE->getOperatorLoc(); 18430 18431 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18432 SourceRange ParenERange = ParenE->getSourceRange(); 18433 Diag(Loc, diag::note_equality_comparison_silence) 18434 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18435 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18436 Diag(Loc, diag::note_equality_comparison_to_assign) 18437 << FixItHint::CreateReplacement(Loc, "="); 18438 } 18439 } 18440 18441 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18442 bool IsConstexpr) { 18443 DiagnoseAssignmentAsCondition(E); 18444 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18445 DiagnoseEqualityWithExtraParens(parenE); 18446 18447 ExprResult result = CheckPlaceholderExpr(E); 18448 if (result.isInvalid()) return ExprError(); 18449 E = result.get(); 18450 18451 if (!E->isTypeDependent()) { 18452 if (getLangOpts().CPlusPlus) 18453 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18454 18455 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18456 if (ERes.isInvalid()) 18457 return ExprError(); 18458 E = ERes.get(); 18459 18460 QualType T = E->getType(); 18461 if (!T->isScalarType()) { // C99 6.8.4.1p1 18462 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18463 << T << E->getSourceRange(); 18464 return ExprError(); 18465 } 18466 CheckBoolLikeConversion(E, Loc); 18467 } 18468 18469 return E; 18470 } 18471 18472 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18473 Expr *SubExpr, ConditionKind CK) { 18474 // Empty conditions are valid in for-statements. 18475 if (!SubExpr) 18476 return ConditionResult(); 18477 18478 ExprResult Cond; 18479 switch (CK) { 18480 case ConditionKind::Boolean: 18481 Cond = CheckBooleanCondition(Loc, SubExpr); 18482 break; 18483 18484 case ConditionKind::ConstexprIf: 18485 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18486 break; 18487 18488 case ConditionKind::Switch: 18489 Cond = CheckSwitchCondition(Loc, SubExpr); 18490 break; 18491 } 18492 if (Cond.isInvalid()) 18493 return ConditionError(); 18494 18495 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18496 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18497 if (!FullExpr.get()) 18498 return ConditionError(); 18499 18500 return ConditionResult(*this, nullptr, FullExpr, 18501 CK == ConditionKind::ConstexprIf); 18502 } 18503 18504 namespace { 18505 /// A visitor for rebuilding a call to an __unknown_any expression 18506 /// to have an appropriate type. 18507 struct RebuildUnknownAnyFunction 18508 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18509 18510 Sema &S; 18511 18512 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18513 18514 ExprResult VisitStmt(Stmt *S) { 18515 llvm_unreachable("unexpected statement!"); 18516 } 18517 18518 ExprResult VisitExpr(Expr *E) { 18519 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18520 << E->getSourceRange(); 18521 return ExprError(); 18522 } 18523 18524 /// Rebuild an expression which simply semantically wraps another 18525 /// expression which it shares the type and value kind of. 18526 template <class T> ExprResult rebuildSugarExpr(T *E) { 18527 ExprResult SubResult = Visit(E->getSubExpr()); 18528 if (SubResult.isInvalid()) return ExprError(); 18529 18530 Expr *SubExpr = SubResult.get(); 18531 E->setSubExpr(SubExpr); 18532 E->setType(SubExpr->getType()); 18533 E->setValueKind(SubExpr->getValueKind()); 18534 assert(E->getObjectKind() == OK_Ordinary); 18535 return E; 18536 } 18537 18538 ExprResult VisitParenExpr(ParenExpr *E) { 18539 return rebuildSugarExpr(E); 18540 } 18541 18542 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18543 return rebuildSugarExpr(E); 18544 } 18545 18546 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18547 ExprResult SubResult = Visit(E->getSubExpr()); 18548 if (SubResult.isInvalid()) return ExprError(); 18549 18550 Expr *SubExpr = SubResult.get(); 18551 E->setSubExpr(SubExpr); 18552 E->setType(S.Context.getPointerType(SubExpr->getType())); 18553 assert(E->getValueKind() == VK_RValue); 18554 assert(E->getObjectKind() == OK_Ordinary); 18555 return E; 18556 } 18557 18558 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18559 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18560 18561 E->setType(VD->getType()); 18562 18563 assert(E->getValueKind() == VK_RValue); 18564 if (S.getLangOpts().CPlusPlus && 18565 !(isa<CXXMethodDecl>(VD) && 18566 cast<CXXMethodDecl>(VD)->isInstance())) 18567 E->setValueKind(VK_LValue); 18568 18569 return E; 18570 } 18571 18572 ExprResult VisitMemberExpr(MemberExpr *E) { 18573 return resolveDecl(E, E->getMemberDecl()); 18574 } 18575 18576 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18577 return resolveDecl(E, E->getDecl()); 18578 } 18579 }; 18580 } 18581 18582 /// Given a function expression of unknown-any type, try to rebuild it 18583 /// to have a function type. 18584 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18585 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18586 if (Result.isInvalid()) return ExprError(); 18587 return S.DefaultFunctionArrayConversion(Result.get()); 18588 } 18589 18590 namespace { 18591 /// A visitor for rebuilding an expression of type __unknown_anytype 18592 /// into one which resolves the type directly on the referring 18593 /// expression. Strict preservation of the original source 18594 /// structure is not a goal. 18595 struct RebuildUnknownAnyExpr 18596 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18597 18598 Sema &S; 18599 18600 /// The current destination type. 18601 QualType DestType; 18602 18603 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18604 : S(S), DestType(CastType) {} 18605 18606 ExprResult VisitStmt(Stmt *S) { 18607 llvm_unreachable("unexpected statement!"); 18608 } 18609 18610 ExprResult VisitExpr(Expr *E) { 18611 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18612 << E->getSourceRange(); 18613 return ExprError(); 18614 } 18615 18616 ExprResult VisitCallExpr(CallExpr *E); 18617 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18618 18619 /// Rebuild an expression which simply semantically wraps another 18620 /// expression which it shares the type and value kind of. 18621 template <class T> ExprResult rebuildSugarExpr(T *E) { 18622 ExprResult SubResult = Visit(E->getSubExpr()); 18623 if (SubResult.isInvalid()) return ExprError(); 18624 Expr *SubExpr = SubResult.get(); 18625 E->setSubExpr(SubExpr); 18626 E->setType(SubExpr->getType()); 18627 E->setValueKind(SubExpr->getValueKind()); 18628 assert(E->getObjectKind() == OK_Ordinary); 18629 return E; 18630 } 18631 18632 ExprResult VisitParenExpr(ParenExpr *E) { 18633 return rebuildSugarExpr(E); 18634 } 18635 18636 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18637 return rebuildSugarExpr(E); 18638 } 18639 18640 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18641 const PointerType *Ptr = DestType->getAs<PointerType>(); 18642 if (!Ptr) { 18643 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18644 << E->getSourceRange(); 18645 return ExprError(); 18646 } 18647 18648 if (isa<CallExpr>(E->getSubExpr())) { 18649 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18650 << E->getSourceRange(); 18651 return ExprError(); 18652 } 18653 18654 assert(E->getValueKind() == VK_RValue); 18655 assert(E->getObjectKind() == OK_Ordinary); 18656 E->setType(DestType); 18657 18658 // Build the sub-expression as if it were an object of the pointee type. 18659 DestType = Ptr->getPointeeType(); 18660 ExprResult SubResult = Visit(E->getSubExpr()); 18661 if (SubResult.isInvalid()) return ExprError(); 18662 E->setSubExpr(SubResult.get()); 18663 return E; 18664 } 18665 18666 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18667 18668 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18669 18670 ExprResult VisitMemberExpr(MemberExpr *E) { 18671 return resolveDecl(E, E->getMemberDecl()); 18672 } 18673 18674 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18675 return resolveDecl(E, E->getDecl()); 18676 } 18677 }; 18678 } 18679 18680 /// Rebuilds a call expression which yielded __unknown_anytype. 18681 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18682 Expr *CalleeExpr = E->getCallee(); 18683 18684 enum FnKind { 18685 FK_MemberFunction, 18686 FK_FunctionPointer, 18687 FK_BlockPointer 18688 }; 18689 18690 FnKind Kind; 18691 QualType CalleeType = CalleeExpr->getType(); 18692 if (CalleeType == S.Context.BoundMemberTy) { 18693 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18694 Kind = FK_MemberFunction; 18695 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18696 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18697 CalleeType = Ptr->getPointeeType(); 18698 Kind = FK_FunctionPointer; 18699 } else { 18700 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18701 Kind = FK_BlockPointer; 18702 } 18703 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18704 18705 // Verify that this is a legal result type of a function. 18706 if (DestType->isArrayType() || DestType->isFunctionType()) { 18707 unsigned diagID = diag::err_func_returning_array_function; 18708 if (Kind == FK_BlockPointer) 18709 diagID = diag::err_block_returning_array_function; 18710 18711 S.Diag(E->getExprLoc(), diagID) 18712 << DestType->isFunctionType() << DestType; 18713 return ExprError(); 18714 } 18715 18716 // Otherwise, go ahead and set DestType as the call's result. 18717 E->setType(DestType.getNonLValueExprType(S.Context)); 18718 E->setValueKind(Expr::getValueKindForType(DestType)); 18719 assert(E->getObjectKind() == OK_Ordinary); 18720 18721 // Rebuild the function type, replacing the result type with DestType. 18722 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18723 if (Proto) { 18724 // __unknown_anytype(...) is a special case used by the debugger when 18725 // it has no idea what a function's signature is. 18726 // 18727 // We want to build this call essentially under the K&R 18728 // unprototyped rules, but making a FunctionNoProtoType in C++ 18729 // would foul up all sorts of assumptions. However, we cannot 18730 // simply pass all arguments as variadic arguments, nor can we 18731 // portably just call the function under a non-variadic type; see 18732 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18733 // However, it turns out that in practice it is generally safe to 18734 // call a function declared as "A foo(B,C,D);" under the prototype 18735 // "A foo(B,C,D,...);". The only known exception is with the 18736 // Windows ABI, where any variadic function is implicitly cdecl 18737 // regardless of its normal CC. Therefore we change the parameter 18738 // types to match the types of the arguments. 18739 // 18740 // This is a hack, but it is far superior to moving the 18741 // corresponding target-specific code from IR-gen to Sema/AST. 18742 18743 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18744 SmallVector<QualType, 8> ArgTypes; 18745 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18746 ArgTypes.reserve(E->getNumArgs()); 18747 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18748 Expr *Arg = E->getArg(i); 18749 QualType ArgType = Arg->getType(); 18750 if (E->isLValue()) { 18751 ArgType = S.Context.getLValueReferenceType(ArgType); 18752 } else if (E->isXValue()) { 18753 ArgType = S.Context.getRValueReferenceType(ArgType); 18754 } 18755 ArgTypes.push_back(ArgType); 18756 } 18757 ParamTypes = ArgTypes; 18758 } 18759 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18760 Proto->getExtProtoInfo()); 18761 } else { 18762 DestType = S.Context.getFunctionNoProtoType(DestType, 18763 FnType->getExtInfo()); 18764 } 18765 18766 // Rebuild the appropriate pointer-to-function type. 18767 switch (Kind) { 18768 case FK_MemberFunction: 18769 // Nothing to do. 18770 break; 18771 18772 case FK_FunctionPointer: 18773 DestType = S.Context.getPointerType(DestType); 18774 break; 18775 18776 case FK_BlockPointer: 18777 DestType = S.Context.getBlockPointerType(DestType); 18778 break; 18779 } 18780 18781 // Finally, we can recurse. 18782 ExprResult CalleeResult = Visit(CalleeExpr); 18783 if (!CalleeResult.isUsable()) return ExprError(); 18784 E->setCallee(CalleeResult.get()); 18785 18786 // Bind a temporary if necessary. 18787 return S.MaybeBindToTemporary(E); 18788 } 18789 18790 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18791 // Verify that this is a legal result type of a call. 18792 if (DestType->isArrayType() || DestType->isFunctionType()) { 18793 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18794 << DestType->isFunctionType() << DestType; 18795 return ExprError(); 18796 } 18797 18798 // Rewrite the method result type if available. 18799 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18800 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18801 Method->setReturnType(DestType); 18802 } 18803 18804 // Change the type of the message. 18805 E->setType(DestType.getNonReferenceType()); 18806 E->setValueKind(Expr::getValueKindForType(DestType)); 18807 18808 return S.MaybeBindToTemporary(E); 18809 } 18810 18811 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18812 // The only case we should ever see here is a function-to-pointer decay. 18813 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18814 assert(E->getValueKind() == VK_RValue); 18815 assert(E->getObjectKind() == OK_Ordinary); 18816 18817 E->setType(DestType); 18818 18819 // Rebuild the sub-expression as the pointee (function) type. 18820 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18821 18822 ExprResult Result = Visit(E->getSubExpr()); 18823 if (!Result.isUsable()) return ExprError(); 18824 18825 E->setSubExpr(Result.get()); 18826 return E; 18827 } else if (E->getCastKind() == CK_LValueToRValue) { 18828 assert(E->getValueKind() == VK_RValue); 18829 assert(E->getObjectKind() == OK_Ordinary); 18830 18831 assert(isa<BlockPointerType>(E->getType())); 18832 18833 E->setType(DestType); 18834 18835 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18836 DestType = S.Context.getLValueReferenceType(DestType); 18837 18838 ExprResult Result = Visit(E->getSubExpr()); 18839 if (!Result.isUsable()) return ExprError(); 18840 18841 E->setSubExpr(Result.get()); 18842 return E; 18843 } else { 18844 llvm_unreachable("Unhandled cast type!"); 18845 } 18846 } 18847 18848 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18849 ExprValueKind ValueKind = VK_LValue; 18850 QualType Type = DestType; 18851 18852 // We know how to make this work for certain kinds of decls: 18853 18854 // - functions 18855 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18856 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18857 DestType = Ptr->getPointeeType(); 18858 ExprResult Result = resolveDecl(E, VD); 18859 if (Result.isInvalid()) return ExprError(); 18860 return S.ImpCastExprToType(Result.get(), Type, 18861 CK_FunctionToPointerDecay, VK_RValue); 18862 } 18863 18864 if (!Type->isFunctionType()) { 18865 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18866 << VD << E->getSourceRange(); 18867 return ExprError(); 18868 } 18869 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18870 // We must match the FunctionDecl's type to the hack introduced in 18871 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18872 // type. See the lengthy commentary in that routine. 18873 QualType FDT = FD->getType(); 18874 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18875 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18876 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18877 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18878 SourceLocation Loc = FD->getLocation(); 18879 FunctionDecl *NewFD = FunctionDecl::Create( 18880 S.Context, FD->getDeclContext(), Loc, Loc, 18881 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18882 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18883 /*ConstexprKind*/ CSK_unspecified); 18884 18885 if (FD->getQualifier()) 18886 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18887 18888 SmallVector<ParmVarDecl*, 16> Params; 18889 for (const auto &AI : FT->param_types()) { 18890 ParmVarDecl *Param = 18891 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18892 Param->setScopeInfo(0, Params.size()); 18893 Params.push_back(Param); 18894 } 18895 NewFD->setParams(Params); 18896 DRE->setDecl(NewFD); 18897 VD = DRE->getDecl(); 18898 } 18899 } 18900 18901 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18902 if (MD->isInstance()) { 18903 ValueKind = VK_RValue; 18904 Type = S.Context.BoundMemberTy; 18905 } 18906 18907 // Function references aren't l-values in C. 18908 if (!S.getLangOpts().CPlusPlus) 18909 ValueKind = VK_RValue; 18910 18911 // - variables 18912 } else if (isa<VarDecl>(VD)) { 18913 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18914 Type = RefTy->getPointeeType(); 18915 } else if (Type->isFunctionType()) { 18916 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18917 << VD << E->getSourceRange(); 18918 return ExprError(); 18919 } 18920 18921 // - nothing else 18922 } else { 18923 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18924 << VD << E->getSourceRange(); 18925 return ExprError(); 18926 } 18927 18928 // Modifying the declaration like this is friendly to IR-gen but 18929 // also really dangerous. 18930 VD->setType(DestType); 18931 E->setType(Type); 18932 E->setValueKind(ValueKind); 18933 return E; 18934 } 18935 18936 /// Check a cast of an unknown-any type. We intentionally only 18937 /// trigger this for C-style casts. 18938 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18939 Expr *CastExpr, CastKind &CastKind, 18940 ExprValueKind &VK, CXXCastPath &Path) { 18941 // The type we're casting to must be either void or complete. 18942 if (!CastType->isVoidType() && 18943 RequireCompleteType(TypeRange.getBegin(), CastType, 18944 diag::err_typecheck_cast_to_incomplete)) 18945 return ExprError(); 18946 18947 // Rewrite the casted expression from scratch. 18948 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18949 if (!result.isUsable()) return ExprError(); 18950 18951 CastExpr = result.get(); 18952 VK = CastExpr->getValueKind(); 18953 CastKind = CK_NoOp; 18954 18955 return CastExpr; 18956 } 18957 18958 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18959 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18960 } 18961 18962 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18963 Expr *arg, QualType ¶mType) { 18964 // If the syntactic form of the argument is not an explicit cast of 18965 // any sort, just do default argument promotion. 18966 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18967 if (!castArg) { 18968 ExprResult result = DefaultArgumentPromotion(arg); 18969 if (result.isInvalid()) return ExprError(); 18970 paramType = result.get()->getType(); 18971 return result; 18972 } 18973 18974 // Otherwise, use the type that was written in the explicit cast. 18975 assert(!arg->hasPlaceholderType()); 18976 paramType = castArg->getTypeAsWritten(); 18977 18978 // Copy-initialize a parameter of that type. 18979 InitializedEntity entity = 18980 InitializedEntity::InitializeParameter(Context, paramType, 18981 /*consumed*/ false); 18982 return PerformCopyInitialization(entity, callLoc, arg); 18983 } 18984 18985 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18986 Expr *orig = E; 18987 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18988 while (true) { 18989 E = E->IgnoreParenImpCasts(); 18990 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18991 E = call->getCallee(); 18992 diagID = diag::err_uncasted_call_of_unknown_any; 18993 } else { 18994 break; 18995 } 18996 } 18997 18998 SourceLocation loc; 18999 NamedDecl *d; 19000 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19001 loc = ref->getLocation(); 19002 d = ref->getDecl(); 19003 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19004 loc = mem->getMemberLoc(); 19005 d = mem->getMemberDecl(); 19006 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19007 diagID = diag::err_uncasted_call_of_unknown_any; 19008 loc = msg->getSelectorStartLoc(); 19009 d = msg->getMethodDecl(); 19010 if (!d) { 19011 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19012 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19013 << orig->getSourceRange(); 19014 return ExprError(); 19015 } 19016 } else { 19017 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19018 << E->getSourceRange(); 19019 return ExprError(); 19020 } 19021 19022 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19023 19024 // Never recoverable. 19025 return ExprError(); 19026 } 19027 19028 /// Check for operands with placeholder types and complain if found. 19029 /// Returns ExprError() if there was an error and no recovery was possible. 19030 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19031 if (!getLangOpts().CPlusPlus) { 19032 // C cannot handle TypoExpr nodes on either side of a binop because it 19033 // doesn't handle dependent types properly, so make sure any TypoExprs have 19034 // been dealt with before checking the operands. 19035 ExprResult Result = CorrectDelayedTyposInExpr(E); 19036 if (!Result.isUsable()) return ExprError(); 19037 E = Result.get(); 19038 } 19039 19040 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19041 if (!placeholderType) return E; 19042 19043 switch (placeholderType->getKind()) { 19044 19045 // Overloaded expressions. 19046 case BuiltinType::Overload: { 19047 // Try to resolve a single function template specialization. 19048 // This is obligatory. 19049 ExprResult Result = E; 19050 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19051 return Result; 19052 19053 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19054 // leaves Result unchanged on failure. 19055 Result = E; 19056 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19057 return Result; 19058 19059 // If that failed, try to recover with a call. 19060 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19061 /*complain*/ true); 19062 return Result; 19063 } 19064 19065 // Bound member functions. 19066 case BuiltinType::BoundMember: { 19067 ExprResult result = E; 19068 const Expr *BME = E->IgnoreParens(); 19069 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19070 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19071 if (isa<CXXPseudoDestructorExpr>(BME)) { 19072 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19073 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19074 if (ME->getMemberNameInfo().getName().getNameKind() == 19075 DeclarationName::CXXDestructorName) 19076 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19077 } 19078 tryToRecoverWithCall(result, PD, 19079 /*complain*/ true); 19080 return result; 19081 } 19082 19083 // ARC unbridged casts. 19084 case BuiltinType::ARCUnbridgedCast: { 19085 Expr *realCast = stripARCUnbridgedCast(E); 19086 diagnoseARCUnbridgedCast(realCast); 19087 return realCast; 19088 } 19089 19090 // Expressions of unknown type. 19091 case BuiltinType::UnknownAny: 19092 return diagnoseUnknownAnyExpr(*this, E); 19093 19094 // Pseudo-objects. 19095 case BuiltinType::PseudoObject: 19096 return checkPseudoObjectRValue(E); 19097 19098 case BuiltinType::BuiltinFn: { 19099 // Accept __noop without parens by implicitly converting it to a call expr. 19100 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19101 if (DRE) { 19102 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19103 if (FD->getBuiltinID() == Builtin::BI__noop) { 19104 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19105 CK_BuiltinFnToFnPtr) 19106 .get(); 19107 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19108 VK_RValue, SourceLocation()); 19109 } 19110 } 19111 19112 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19113 return ExprError(); 19114 } 19115 19116 case BuiltinType::IncompleteMatrixIdx: 19117 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19118 ->getRowIdx() 19119 ->getBeginLoc(), 19120 diag::err_matrix_incomplete_index); 19121 return ExprError(); 19122 19123 // Expressions of unknown type. 19124 case BuiltinType::OMPArraySection: 19125 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19126 return ExprError(); 19127 19128 // Expressions of unknown type. 19129 case BuiltinType::OMPArrayShaping: 19130 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19131 19132 case BuiltinType::OMPIterator: 19133 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19134 19135 // Everything else should be impossible. 19136 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19137 case BuiltinType::Id: 19138 #include "clang/Basic/OpenCLImageTypes.def" 19139 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19140 case BuiltinType::Id: 19141 #include "clang/Basic/OpenCLExtensionTypes.def" 19142 #define SVE_TYPE(Name, Id, SingletonId) \ 19143 case BuiltinType::Id: 19144 #include "clang/Basic/AArch64SVEACLETypes.def" 19145 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19146 #define PLACEHOLDER_TYPE(Id, SingletonId) 19147 #include "clang/AST/BuiltinTypes.def" 19148 break; 19149 } 19150 19151 llvm_unreachable("invalid placeholder type!"); 19152 } 19153 19154 bool Sema::CheckCaseExpression(Expr *E) { 19155 if (E->isTypeDependent()) 19156 return true; 19157 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19158 return E->getType()->isIntegralOrEnumerationType(); 19159 return false; 19160 } 19161 19162 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19163 ExprResult 19164 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19165 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19166 "Unknown Objective-C Boolean value!"); 19167 QualType BoolT = Context.ObjCBuiltinBoolTy; 19168 if (!Context.getBOOLDecl()) { 19169 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19170 Sema::LookupOrdinaryName); 19171 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19172 NamedDecl *ND = Result.getFoundDecl(); 19173 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19174 Context.setBOOLDecl(TD); 19175 } 19176 } 19177 if (Context.getBOOLDecl()) 19178 BoolT = Context.getBOOLType(); 19179 return new (Context) 19180 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19181 } 19182 19183 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19184 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19185 SourceLocation RParen) { 19186 19187 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19188 19189 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19190 return Spec.getPlatform() == Platform; 19191 }); 19192 19193 VersionTuple Version; 19194 if (Spec != AvailSpecs.end()) 19195 Version = Spec->getVersion(); 19196 19197 // The use of `@available` in the enclosing function should be analyzed to 19198 // warn when it's used inappropriately (i.e. not if(@available)). 19199 if (getCurFunctionOrMethodDecl()) 19200 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19201 else if (getCurBlock() || getCurLambda()) 19202 getCurFunction()->HasPotentialAvailabilityViolations = true; 19203 19204 return new (Context) 19205 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19206 } 19207 19208 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19209 ArrayRef<Expr *> SubExprs, QualType T) { 19210 // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress 19211 // bogus diagnostics and this trick does not work in C. 19212 // FIXME: use containsErrors() to suppress unwanted diags in C. 19213 if (!Context.getLangOpts().RecoveryAST) 19214 return ExprError(); 19215 19216 if (isSFINAEContext()) 19217 return ExprError(); 19218 19219 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19220 // We don't know the concrete type, fallback to dependent type. 19221 T = Context.DependentTy; 19222 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19223 } 19224