1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 } 70 71 // See if this function is unavailable. 72 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 73 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 74 return false; 75 76 return true; 77 } 78 79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 80 // Warn if this is used but marked unused. 81 if (const auto *A = D->getAttr<UnusedAttr>()) { 82 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 83 // should diagnose them. 84 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 85 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 86 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 87 if (DC && !DC->hasAttr<UnusedAttr>()) 88 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 89 } 90 } 91 } 92 93 /// Emit a note explaining that this function is deleted. 94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 95 assert(Decl->isDeleted()); 96 97 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 98 99 if (Method && Method->isDeleted() && Method->isDefaulted()) { 100 // If the method was explicitly defaulted, point at that declaration. 101 if (!Method->isImplicit()) 102 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 103 104 // Try to diagnose why this special member function was implicitly 105 // deleted. This might fail, if that reason no longer applies. 106 CXXSpecialMember CSM = getSpecialMember(Method); 107 if (CSM != CXXInvalid) 108 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 109 110 return; 111 } 112 113 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 114 if (Ctor && Ctor->isInheritingConstructor()) 115 return NoteDeletedInheritingConstructor(Ctor); 116 117 Diag(Decl->getLocation(), diag::note_availability_specified_here) 118 << Decl << true; 119 } 120 121 /// Determine whether a FunctionDecl was ever declared with an 122 /// explicit storage class. 123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 124 for (auto I : D->redecls()) { 125 if (I->getStorageClass() != SC_None) 126 return true; 127 } 128 return false; 129 } 130 131 /// Check whether we're in an extern inline function and referring to a 132 /// variable or function with internal linkage (C11 6.7.4p3). 133 /// 134 /// This is only a warning because we used to silently accept this code, but 135 /// in many cases it will not behave correctly. This is not enabled in C++ mode 136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 137 /// and so while there may still be user mistakes, most of the time we can't 138 /// prove that there are errors. 139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 140 const NamedDecl *D, 141 SourceLocation Loc) { 142 // This is disabled under C++; there are too many ways for this to fire in 143 // contexts where the warning is a false positive, or where it is technically 144 // correct but benign. 145 if (S.getLangOpts().CPlusPlus) 146 return; 147 148 // Check if this is an inlined function or method. 149 FunctionDecl *Current = S.getCurFunctionDecl(); 150 if (!Current) 151 return; 152 if (!Current->isInlined()) 153 return; 154 if (!Current->isExternallyVisible()) 155 return; 156 157 // Check if the decl has internal linkage. 158 if (D->getFormalLinkage() != InternalLinkage) 159 return; 160 161 // Downgrade from ExtWarn to Extension if 162 // (1) the supposedly external inline function is in the main file, 163 // and probably won't be included anywhere else. 164 // (2) the thing we're referencing is a pure function. 165 // (3) the thing we're referencing is another inline function. 166 // This last can give us false negatives, but it's better than warning on 167 // wrappers for simple C library functions. 168 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 169 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 170 if (!DowngradeWarning && UsedFn) 171 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 172 173 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 174 : diag::ext_internal_in_extern_inline) 175 << /*IsVar=*/!UsedFn << D; 176 177 S.MaybeSuggestAddingStaticToDecl(Current); 178 179 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 180 << D; 181 } 182 183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 184 const FunctionDecl *First = Cur->getFirstDecl(); 185 186 // Suggest "static" on the function, if possible. 187 if (!hasAnyExplicitStorageClass(First)) { 188 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 189 Diag(DeclBegin, diag::note_convert_inline_to_static) 190 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 191 } 192 } 193 194 /// Determine whether the use of this declaration is valid, and 195 /// emit any corresponding diagnostics. 196 /// 197 /// This routine diagnoses various problems with referencing 198 /// declarations that can occur when using a declaration. For example, 199 /// it might warn if a deprecated or unavailable declaration is being 200 /// used, or produce an error (and return true) if a C++0x deleted 201 /// function is being used. 202 /// 203 /// \returns true if there was an error (this declaration cannot be 204 /// referenced), false otherwise. 205 /// 206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 207 const ObjCInterfaceDecl *UnknownObjCClass, 208 bool ObjCPropertyAccess, 209 bool AvoidPartialAvailabilityChecks, 210 ObjCInterfaceDecl *ClassReceiver) { 211 SourceLocation Loc = Locs.front(); 212 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 213 // If there were any diagnostics suppressed by template argument deduction, 214 // emit them now. 215 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 216 if (Pos != SuppressedDiagnostics.end()) { 217 for (const PartialDiagnosticAt &Suppressed : Pos->second) 218 Diag(Suppressed.first, Suppressed.second); 219 220 // Clear out the list of suppressed diagnostics, so that we don't emit 221 // them again for this specialization. However, we don't obsolete this 222 // entry from the table, because we want to avoid ever emitting these 223 // diagnostics again. 224 Pos->second.clear(); 225 } 226 227 // C++ [basic.start.main]p3: 228 // The function 'main' shall not be used within a program. 229 if (cast<FunctionDecl>(D)->isMain()) 230 Diag(Loc, diag::ext_main_used); 231 } 232 233 // See if this is an auto-typed variable whose initializer we are parsing. 234 if (ParsingInitForAutoVars.count(D)) { 235 if (isa<BindingDecl>(D)) { 236 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 237 << D->getDeclName(); 238 } else { 239 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 240 << D->getDeclName() << cast<VarDecl>(D)->getType(); 241 } 242 return true; 243 } 244 245 // See if this is a deleted function. 246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 247 if (FD->isDeleted()) { 248 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 249 if (Ctor && Ctor->isInheritingConstructor()) 250 Diag(Loc, diag::err_deleted_inherited_ctor_use) 251 << Ctor->getParent() 252 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 253 else 254 Diag(Loc, diag::err_deleted_function_use); 255 NoteDeletedFunction(FD); 256 return true; 257 } 258 259 // If the function has a deduced return type, and we can't deduce it, 260 // then we can't use it either. 261 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 262 DeduceReturnType(FD, Loc)) 263 return true; 264 265 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 266 return true; 267 } 268 269 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 270 // Lambdas are only default-constructible or assignable in C++2a onwards. 271 if (MD->getParent()->isLambda() && 272 ((isa<CXXConstructorDecl>(MD) && 273 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 274 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 275 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 276 << !isa<CXXConstructorDecl>(MD); 277 } 278 } 279 280 auto getReferencedObjCProp = [](const NamedDecl *D) -> 281 const ObjCPropertyDecl * { 282 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 283 return MD->findPropertyDecl(); 284 return nullptr; 285 }; 286 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 287 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 288 return true; 289 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 290 return true; 291 } 292 293 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 294 // Only the variables omp_in and omp_out are allowed in the combiner. 295 // Only the variables omp_priv and omp_orig are allowed in the 296 // initializer-clause. 297 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 298 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 299 isa<VarDecl>(D)) { 300 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 301 << getCurFunction()->HasOMPDeclareReductionCombiner; 302 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 303 return true; 304 } 305 306 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 307 AvoidPartialAvailabilityChecks, ClassReceiver); 308 309 DiagnoseUnusedOfDecl(*this, D, Loc); 310 311 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 312 313 return false; 314 } 315 316 /// Retrieve the message suffix that should be added to a 317 /// diagnostic complaining about the given function being deleted or 318 /// unavailable. 319 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 320 std::string Message; 321 if (FD->getAvailability(&Message)) 322 return ": " + Message; 323 324 return std::string(); 325 } 326 327 /// DiagnoseSentinelCalls - This routine checks whether a call or 328 /// message-send is to a declaration with the sentinel attribute, and 329 /// if so, it checks that the requirements of the sentinel are 330 /// satisfied. 331 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 332 ArrayRef<Expr *> Args) { 333 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 334 if (!attr) 335 return; 336 337 // The number of formal parameters of the declaration. 338 unsigned numFormalParams; 339 340 // The kind of declaration. This is also an index into a %select in 341 // the diagnostic. 342 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 343 344 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 345 numFormalParams = MD->param_size(); 346 calleeType = CT_Method; 347 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 348 numFormalParams = FD->param_size(); 349 calleeType = CT_Function; 350 } else if (isa<VarDecl>(D)) { 351 QualType type = cast<ValueDecl>(D)->getType(); 352 const FunctionType *fn = nullptr; 353 if (const PointerType *ptr = type->getAs<PointerType>()) { 354 fn = ptr->getPointeeType()->getAs<FunctionType>(); 355 if (!fn) return; 356 calleeType = CT_Function; 357 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 358 fn = ptr->getPointeeType()->castAs<FunctionType>(); 359 calleeType = CT_Block; 360 } else { 361 return; 362 } 363 364 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 365 numFormalParams = proto->getNumParams(); 366 } else { 367 numFormalParams = 0; 368 } 369 } else { 370 return; 371 } 372 373 // "nullPos" is the number of formal parameters at the end which 374 // effectively count as part of the variadic arguments. This is 375 // useful if you would prefer to not have *any* formal parameters, 376 // but the language forces you to have at least one. 377 unsigned nullPos = attr->getNullPos(); 378 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 379 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 380 381 // The number of arguments which should follow the sentinel. 382 unsigned numArgsAfterSentinel = attr->getSentinel(); 383 384 // If there aren't enough arguments for all the formal parameters, 385 // the sentinel, and the args after the sentinel, complain. 386 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 387 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 388 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 389 return; 390 } 391 392 // Otherwise, find the sentinel expression. 393 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 394 if (!sentinelExpr) return; 395 if (sentinelExpr->isValueDependent()) return; 396 if (Context.isSentinelNullExpr(sentinelExpr)) return; 397 398 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 399 // or 'NULL' if those are actually defined in the context. Only use 400 // 'nil' for ObjC methods, where it's much more likely that the 401 // variadic arguments form a list of object pointers. 402 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 403 std::string NullValue; 404 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 405 NullValue = "nil"; 406 else if (getLangOpts().CPlusPlus11) 407 NullValue = "nullptr"; 408 else if (PP.isMacroDefined("NULL")) 409 NullValue = "NULL"; 410 else 411 NullValue = "(void*) 0"; 412 413 if (MissingNilLoc.isInvalid()) 414 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 415 else 416 Diag(MissingNilLoc, diag::warn_missing_sentinel) 417 << int(calleeType) 418 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 419 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 420 } 421 422 SourceRange Sema::getExprRange(Expr *E) const { 423 return E ? E->getSourceRange() : SourceRange(); 424 } 425 426 //===----------------------------------------------------------------------===// 427 // Standard Promotions and Conversions 428 //===----------------------------------------------------------------------===// 429 430 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 431 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 432 // Handle any placeholder expressions which made it here. 433 if (E->getType()->isPlaceholderType()) { 434 ExprResult result = CheckPlaceholderExpr(E); 435 if (result.isInvalid()) return ExprError(); 436 E = result.get(); 437 } 438 439 QualType Ty = E->getType(); 440 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 441 442 if (Ty->isFunctionType()) { 443 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 444 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 445 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 446 return ExprError(); 447 448 E = ImpCastExprToType(E, Context.getPointerType(Ty), 449 CK_FunctionToPointerDecay).get(); 450 } else if (Ty->isArrayType()) { 451 // In C90 mode, arrays only promote to pointers if the array expression is 452 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 453 // type 'array of type' is converted to an expression that has type 'pointer 454 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 455 // that has type 'array of type' ...". The relevant change is "an lvalue" 456 // (C90) to "an expression" (C99). 457 // 458 // C++ 4.2p1: 459 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 460 // T" can be converted to an rvalue of type "pointer to T". 461 // 462 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 463 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 464 CK_ArrayToPointerDecay).get(); 465 } 466 return E; 467 } 468 469 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 470 // Check to see if we are dereferencing a null pointer. If so, 471 // and if not volatile-qualified, this is undefined behavior that the 472 // optimizer will delete, so warn about it. People sometimes try to use this 473 // to get a deterministic trap and are surprised by clang's behavior. This 474 // only handles the pattern "*null", which is a very syntactic check. 475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 476 if (UO->getOpcode() == UO_Deref && 477 UO->getSubExpr()->IgnoreParenCasts()-> 478 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 479 !UO->getType().isVolatileQualified()) { 480 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 481 S.PDiag(diag::warn_indirection_through_null) 482 << UO->getSubExpr()->getSourceRange()); 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::note_indirection_through_null)); 485 } 486 } 487 488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 489 SourceLocation AssignLoc, 490 const Expr* RHS) { 491 const ObjCIvarDecl *IV = OIRE->getDecl(); 492 if (!IV) 493 return; 494 495 DeclarationName MemberName = IV->getDeclName(); 496 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 497 if (!Member || !Member->isStr("isa")) 498 return; 499 500 const Expr *Base = OIRE->getBase(); 501 QualType BaseType = Base->getType(); 502 if (OIRE->isArrow()) 503 BaseType = BaseType->getPointeeType(); 504 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 505 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 506 ObjCInterfaceDecl *ClassDeclared = nullptr; 507 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 508 if (!ClassDeclared->getSuperClass() 509 && (*ClassDeclared->ivar_begin()) == IV) { 510 if (RHS) { 511 NamedDecl *ObjectSetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_setClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectSetClass) { 516 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 518 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 519 "object_setClass(") 520 << FixItHint::CreateReplacement( 521 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 522 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 523 } 524 else 525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 526 } else { 527 NamedDecl *ObjectGetClass = 528 S.LookupSingleName(S.TUScope, 529 &S.Context.Idents.get("object_getClass"), 530 SourceLocation(), S.LookupOrdinaryName); 531 if (ObjectGetClass) 532 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 533 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 534 "object_getClass(") 535 << FixItHint::CreateReplacement( 536 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 537 else 538 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 539 } 540 S.Diag(IV->getLocation(), diag::note_ivar_decl); 541 } 542 } 543 } 544 545 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 546 // Handle any placeholder expressions which made it here. 547 if (E->getType()->isPlaceholderType()) { 548 ExprResult result = CheckPlaceholderExpr(E); 549 if (result.isInvalid()) return ExprError(); 550 E = result.get(); 551 } 552 553 // C++ [conv.lval]p1: 554 // A glvalue of a non-function, non-array type T can be 555 // converted to a prvalue. 556 if (!E->isGLValue()) return E; 557 558 QualType T = E->getType(); 559 assert(!T.isNull() && "r-value conversion on typeless expression?"); 560 561 // We don't want to throw lvalue-to-rvalue casts on top of 562 // expressions of certain types in C++. 563 if (getLangOpts().CPlusPlus && 564 (E->getType() == Context.OverloadTy || 565 T->isDependentType() || 566 T->isRecordType())) 567 return E; 568 569 // The C standard is actually really unclear on this point, and 570 // DR106 tells us what the result should be but not why. It's 571 // generally best to say that void types just doesn't undergo 572 // lvalue-to-rvalue at all. Note that expressions of unqualified 573 // 'void' type are never l-values, but qualified void can be. 574 if (T->isVoidType()) 575 return E; 576 577 // OpenCL usually rejects direct accesses to values of 'half' type. 578 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 579 T->isHalfType()) { 580 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 581 << 0 << T; 582 return ExprError(); 583 } 584 585 CheckForNullPointerDereference(*this, E); 586 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 587 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 588 &Context.Idents.get("object_getClass"), 589 SourceLocation(), LookupOrdinaryName); 590 if (ObjectGetClass) 591 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 592 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 593 << FixItHint::CreateReplacement( 594 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 595 else 596 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 597 } 598 else if (const ObjCIvarRefExpr *OIRE = 599 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 600 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 601 602 // C++ [conv.lval]p1: 603 // [...] If T is a non-class type, the type of the prvalue is the 604 // cv-unqualified version of T. Otherwise, the type of the 605 // rvalue is T. 606 // 607 // C99 6.3.2.1p2: 608 // If the lvalue has qualified type, the value has the unqualified 609 // version of the type of the lvalue; otherwise, the value has the 610 // type of the lvalue. 611 if (T.hasQualifiers()) 612 T = T.getUnqualifiedType(); 613 614 // Under the MS ABI, lock down the inheritance model now. 615 if (T->isMemberPointerType() && 616 Context.getTargetInfo().getCXXABI().isMicrosoft()) 617 (void)isCompleteType(E->getExprLoc(), T); 618 619 UpdateMarkingForLValueToRValue(E); 620 621 // Loading a __weak object implicitly retains the value, so we need a cleanup to 622 // balance that. 623 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 624 Cleanup.setExprNeedsCleanups(true); 625 626 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 627 nullptr, VK_RValue); 628 629 // C11 6.3.2.1p2: 630 // ... if the lvalue has atomic type, the value has the non-atomic version 631 // of the type of the lvalue ... 632 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 633 T = Atomic->getValueType().getUnqualifiedType(); 634 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 635 nullptr, VK_RValue); 636 } 637 638 return Res; 639 } 640 641 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 642 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 643 if (Res.isInvalid()) 644 return ExprError(); 645 Res = DefaultLvalueConversion(Res.get()); 646 if (Res.isInvalid()) 647 return ExprError(); 648 return Res; 649 } 650 651 /// CallExprUnaryConversions - a special case of an unary conversion 652 /// performed on a function designator of a call expression. 653 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 654 QualType Ty = E->getType(); 655 ExprResult Res = E; 656 // Only do implicit cast for a function type, but not for a pointer 657 // to function type. 658 if (Ty->isFunctionType()) { 659 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 660 CK_FunctionToPointerDecay).get(); 661 if (Res.isInvalid()) 662 return ExprError(); 663 } 664 Res = DefaultLvalueConversion(Res.get()); 665 if (Res.isInvalid()) 666 return ExprError(); 667 return Res.get(); 668 } 669 670 /// UsualUnaryConversions - Performs various conversions that are common to most 671 /// operators (C99 6.3). The conversions of array and function types are 672 /// sometimes suppressed. For example, the array->pointer conversion doesn't 673 /// apply if the array is an argument to the sizeof or address (&) operators. 674 /// In these instances, this routine should *not* be called. 675 ExprResult Sema::UsualUnaryConversions(Expr *E) { 676 // First, convert to an r-value. 677 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 678 if (Res.isInvalid()) 679 return ExprError(); 680 E = Res.get(); 681 682 QualType Ty = E->getType(); 683 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 684 685 // Half FP have to be promoted to float unless it is natively supported 686 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 687 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 688 689 // Try to perform integral promotions if the object has a theoretically 690 // promotable type. 691 if (Ty->isIntegralOrUnscopedEnumerationType()) { 692 // C99 6.3.1.1p2: 693 // 694 // The following may be used in an expression wherever an int or 695 // unsigned int may be used: 696 // - an object or expression with an integer type whose integer 697 // conversion rank is less than or equal to the rank of int 698 // and unsigned int. 699 // - A bit-field of type _Bool, int, signed int, or unsigned int. 700 // 701 // If an int can represent all values of the original type, the 702 // value is converted to an int; otherwise, it is converted to an 703 // unsigned int. These are called the integer promotions. All 704 // other types are unchanged by the integer promotions. 705 706 QualType PTy = Context.isPromotableBitField(E); 707 if (!PTy.isNull()) { 708 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 709 return E; 710 } 711 if (Ty->isPromotableIntegerType()) { 712 QualType PT = Context.getPromotedIntegerType(Ty); 713 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 714 return E; 715 } 716 } 717 return E; 718 } 719 720 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 721 /// do not have a prototype. Arguments that have type float or __fp16 722 /// are promoted to double. All other argument types are converted by 723 /// UsualUnaryConversions(). 724 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 725 QualType Ty = E->getType(); 726 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 727 728 ExprResult Res = UsualUnaryConversions(E); 729 if (Res.isInvalid()) 730 return ExprError(); 731 E = Res.get(); 732 733 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 734 // promote to double. 735 // Note that default argument promotion applies only to float (and 736 // half/fp16); it does not apply to _Float16. 737 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 738 if (BTy && (BTy->getKind() == BuiltinType::Half || 739 BTy->getKind() == BuiltinType::Float)) { 740 if (getLangOpts().OpenCL && 741 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 742 if (BTy->getKind() == BuiltinType::Half) { 743 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 744 } 745 } else { 746 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 747 } 748 } 749 750 // C++ performs lvalue-to-rvalue conversion as a default argument 751 // promotion, even on class types, but note: 752 // C++11 [conv.lval]p2: 753 // When an lvalue-to-rvalue conversion occurs in an unevaluated 754 // operand or a subexpression thereof the value contained in the 755 // referenced object is not accessed. Otherwise, if the glvalue 756 // has a class type, the conversion copy-initializes a temporary 757 // of type T from the glvalue and the result of the conversion 758 // is a prvalue for the temporary. 759 // FIXME: add some way to gate this entire thing for correctness in 760 // potentially potentially evaluated contexts. 761 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 762 ExprResult Temp = PerformCopyInitialization( 763 InitializedEntity::InitializeTemporary(E->getType()), 764 E->getExprLoc(), E); 765 if (Temp.isInvalid()) 766 return ExprError(); 767 E = Temp.get(); 768 } 769 770 return E; 771 } 772 773 /// Determine the degree of POD-ness for an expression. 774 /// Incomplete types are considered POD, since this check can be performed 775 /// when we're in an unevaluated context. 776 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 777 if (Ty->isIncompleteType()) { 778 // C++11 [expr.call]p7: 779 // After these conversions, if the argument does not have arithmetic, 780 // enumeration, pointer, pointer to member, or class type, the program 781 // is ill-formed. 782 // 783 // Since we've already performed array-to-pointer and function-to-pointer 784 // decay, the only such type in C++ is cv void. This also handles 785 // initializer lists as variadic arguments. 786 if (Ty->isVoidType()) 787 return VAK_Invalid; 788 789 if (Ty->isObjCObjectType()) 790 return VAK_Invalid; 791 return VAK_Valid; 792 } 793 794 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 795 return VAK_Invalid; 796 797 if (Ty.isCXX98PODType(Context)) 798 return VAK_Valid; 799 800 // C++11 [expr.call]p7: 801 // Passing a potentially-evaluated argument of class type (Clause 9) 802 // having a non-trivial copy constructor, a non-trivial move constructor, 803 // or a non-trivial destructor, with no corresponding parameter, 804 // is conditionally-supported with implementation-defined semantics. 805 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 806 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 807 if (!Record->hasNonTrivialCopyConstructor() && 808 !Record->hasNonTrivialMoveConstructor() && 809 !Record->hasNonTrivialDestructor()) 810 return VAK_ValidInCXX11; 811 812 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 813 return VAK_Valid; 814 815 if (Ty->isObjCObjectType()) 816 return VAK_Invalid; 817 818 if (getLangOpts().MSVCCompat) 819 return VAK_MSVCUndefined; 820 821 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 822 // permitted to reject them. We should consider doing so. 823 return VAK_Undefined; 824 } 825 826 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 827 // Don't allow one to pass an Objective-C interface to a vararg. 828 const QualType &Ty = E->getType(); 829 VarArgKind VAK = isValidVarArgType(Ty); 830 831 // Complain about passing non-POD types through varargs. 832 switch (VAK) { 833 case VAK_ValidInCXX11: 834 DiagRuntimeBehavior( 835 E->getBeginLoc(), nullptr, 836 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 837 LLVM_FALLTHROUGH; 838 case VAK_Valid: 839 if (Ty->isRecordType()) { 840 // This is unlikely to be what the user intended. If the class has a 841 // 'c_str' member function, the user probably meant to call that. 842 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 843 PDiag(diag::warn_pass_class_arg_to_vararg) 844 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 845 } 846 break; 847 848 case VAK_Undefined: 849 case VAK_MSVCUndefined: 850 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 851 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 852 << getLangOpts().CPlusPlus11 << Ty << CT); 853 break; 854 855 case VAK_Invalid: 856 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 857 Diag(E->getBeginLoc(), 858 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 859 << Ty << CT; 860 else if (Ty->isObjCObjectType()) 861 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 862 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 863 << Ty << CT); 864 else 865 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 866 << isa<InitListExpr>(E) << Ty << CT; 867 break; 868 } 869 } 870 871 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 872 /// will create a trap if the resulting type is not a POD type. 873 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 874 FunctionDecl *FDecl) { 875 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 876 // Strip the unbridged-cast placeholder expression off, if applicable. 877 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 878 (CT == VariadicMethod || 879 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 880 E = stripARCUnbridgedCast(E); 881 882 // Otherwise, do normal placeholder checking. 883 } else { 884 ExprResult ExprRes = CheckPlaceholderExpr(E); 885 if (ExprRes.isInvalid()) 886 return ExprError(); 887 E = ExprRes.get(); 888 } 889 } 890 891 ExprResult ExprRes = DefaultArgumentPromotion(E); 892 if (ExprRes.isInvalid()) 893 return ExprError(); 894 E = ExprRes.get(); 895 896 // Diagnostics regarding non-POD argument types are 897 // emitted along with format string checking in Sema::CheckFunctionCall(). 898 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 899 // Turn this into a trap. 900 CXXScopeSpec SS; 901 SourceLocation TemplateKWLoc; 902 UnqualifiedId Name; 903 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 904 E->getBeginLoc()); 905 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 906 Name, true, false); 907 if (TrapFn.isInvalid()) 908 return ExprError(); 909 910 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 911 None, E->getEndLoc()); 912 if (Call.isInvalid()) 913 return ExprError(); 914 915 ExprResult Comma = 916 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 917 if (Comma.isInvalid()) 918 return ExprError(); 919 return Comma.get(); 920 } 921 922 if (!getLangOpts().CPlusPlus && 923 RequireCompleteType(E->getExprLoc(), E->getType(), 924 diag::err_call_incomplete_argument)) 925 return ExprError(); 926 927 return E; 928 } 929 930 /// Converts an integer to complex float type. Helper function of 931 /// UsualArithmeticConversions() 932 /// 933 /// \return false if the integer expression is an integer type and is 934 /// successfully converted to the complex type. 935 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 936 ExprResult &ComplexExpr, 937 QualType IntTy, 938 QualType ComplexTy, 939 bool SkipCast) { 940 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 941 if (SkipCast) return false; 942 if (IntTy->isIntegerType()) { 943 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 944 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 945 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 946 CK_FloatingRealToComplex); 947 } else { 948 assert(IntTy->isComplexIntegerType()); 949 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 950 CK_IntegralComplexToFloatingComplex); 951 } 952 return false; 953 } 954 955 /// Handle arithmetic conversion with complex types. Helper function of 956 /// UsualArithmeticConversions() 957 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 958 ExprResult &RHS, QualType LHSType, 959 QualType RHSType, 960 bool IsCompAssign) { 961 // if we have an integer operand, the result is the complex type. 962 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 963 /*skipCast*/false)) 964 return LHSType; 965 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 966 /*skipCast*/IsCompAssign)) 967 return RHSType; 968 969 // This handles complex/complex, complex/float, or float/complex. 970 // When both operands are complex, the shorter operand is converted to the 971 // type of the longer, and that is the type of the result. This corresponds 972 // to what is done when combining two real floating-point operands. 973 // The fun begins when size promotion occur across type domains. 974 // From H&S 6.3.4: When one operand is complex and the other is a real 975 // floating-point type, the less precise type is converted, within it's 976 // real or complex domain, to the precision of the other type. For example, 977 // when combining a "long double" with a "double _Complex", the 978 // "double _Complex" is promoted to "long double _Complex". 979 980 // Compute the rank of the two types, regardless of whether they are complex. 981 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 982 983 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 984 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 985 QualType LHSElementType = 986 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 987 QualType RHSElementType = 988 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 989 990 QualType ResultType = S.Context.getComplexType(LHSElementType); 991 if (Order < 0) { 992 // Promote the precision of the LHS if not an assignment. 993 ResultType = S.Context.getComplexType(RHSElementType); 994 if (!IsCompAssign) { 995 if (LHSComplexType) 996 LHS = 997 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 998 else 999 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1000 } 1001 } else if (Order > 0) { 1002 // Promote the precision of the RHS. 1003 if (RHSComplexType) 1004 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1005 else 1006 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1007 } 1008 return ResultType; 1009 } 1010 1011 /// Handle arithmetic conversion from integer to float. Helper function 1012 /// of UsualArithmeticConversions() 1013 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1014 ExprResult &IntExpr, 1015 QualType FloatTy, QualType IntTy, 1016 bool ConvertFloat, bool ConvertInt) { 1017 if (IntTy->isIntegerType()) { 1018 if (ConvertInt) 1019 // Convert intExpr to the lhs floating point type. 1020 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1021 CK_IntegralToFloating); 1022 return FloatTy; 1023 } 1024 1025 // Convert both sides to the appropriate complex float. 1026 assert(IntTy->isComplexIntegerType()); 1027 QualType result = S.Context.getComplexType(FloatTy); 1028 1029 // _Complex int -> _Complex float 1030 if (ConvertInt) 1031 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1032 CK_IntegralComplexToFloatingComplex); 1033 1034 // float -> _Complex float 1035 if (ConvertFloat) 1036 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1037 CK_FloatingRealToComplex); 1038 1039 return result; 1040 } 1041 1042 /// Handle arithmethic conversion with floating point types. Helper 1043 /// function of UsualArithmeticConversions() 1044 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1045 ExprResult &RHS, QualType LHSType, 1046 QualType RHSType, bool IsCompAssign) { 1047 bool LHSFloat = LHSType->isRealFloatingType(); 1048 bool RHSFloat = RHSType->isRealFloatingType(); 1049 1050 // If we have two real floating types, convert the smaller operand 1051 // to the bigger result. 1052 if (LHSFloat && RHSFloat) { 1053 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1054 if (order > 0) { 1055 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1056 return LHSType; 1057 } 1058 1059 assert(order < 0 && "illegal float comparison"); 1060 if (!IsCompAssign) 1061 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1062 return RHSType; 1063 } 1064 1065 if (LHSFloat) { 1066 // Half FP has to be promoted to float unless it is natively supported 1067 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1068 LHSType = S.Context.FloatTy; 1069 1070 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1071 /*convertFloat=*/!IsCompAssign, 1072 /*convertInt=*/ true); 1073 } 1074 assert(RHSFloat); 1075 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1076 /*convertInt=*/ true, 1077 /*convertFloat=*/!IsCompAssign); 1078 } 1079 1080 /// Diagnose attempts to convert between __float128 and long double if 1081 /// there is no support for such conversion. Helper function of 1082 /// UsualArithmeticConversions(). 1083 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1084 QualType RHSType) { 1085 /* No issue converting if at least one of the types is not a floating point 1086 type or the two types have the same rank. 1087 */ 1088 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1089 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1090 return false; 1091 1092 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1093 "The remaining types must be floating point types."); 1094 1095 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1096 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1097 1098 QualType LHSElemType = LHSComplex ? 1099 LHSComplex->getElementType() : LHSType; 1100 QualType RHSElemType = RHSComplex ? 1101 RHSComplex->getElementType() : RHSType; 1102 1103 // No issue if the two types have the same representation 1104 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1105 &S.Context.getFloatTypeSemantics(RHSElemType)) 1106 return false; 1107 1108 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1109 RHSElemType == S.Context.LongDoubleTy); 1110 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1111 RHSElemType == S.Context.Float128Ty); 1112 1113 // We've handled the situation where __float128 and long double have the same 1114 // representation. We allow all conversions for all possible long double types 1115 // except PPC's double double. 1116 return Float128AndLongDouble && 1117 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1118 &llvm::APFloat::PPCDoubleDouble()); 1119 } 1120 1121 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1122 1123 namespace { 1124 /// These helper callbacks are placed in an anonymous namespace to 1125 /// permit their use as function template parameters. 1126 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1127 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1128 } 1129 1130 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1131 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1132 CK_IntegralComplexCast); 1133 } 1134 } 1135 1136 /// Handle integer arithmetic conversions. Helper function of 1137 /// UsualArithmeticConversions() 1138 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1139 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1140 ExprResult &RHS, QualType LHSType, 1141 QualType RHSType, bool IsCompAssign) { 1142 // The rules for this case are in C99 6.3.1.8 1143 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1144 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1145 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1146 if (LHSSigned == RHSSigned) { 1147 // Same signedness; use the higher-ranked type 1148 if (order >= 0) { 1149 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1150 return LHSType; 1151 } else if (!IsCompAssign) 1152 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1153 return RHSType; 1154 } else if (order != (LHSSigned ? 1 : -1)) { 1155 // The unsigned type has greater than or equal rank to the 1156 // signed type, so use the unsigned type 1157 if (RHSSigned) { 1158 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1159 return LHSType; 1160 } else if (!IsCompAssign) 1161 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1162 return RHSType; 1163 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1164 // The two types are different widths; if we are here, that 1165 // means the signed type is larger than the unsigned type, so 1166 // use the signed type. 1167 if (LHSSigned) { 1168 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1169 return LHSType; 1170 } else if (!IsCompAssign) 1171 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1172 return RHSType; 1173 } else { 1174 // The signed type is higher-ranked than the unsigned type, 1175 // but isn't actually any bigger (like unsigned int and long 1176 // on most 32-bit systems). Use the unsigned type corresponding 1177 // to the signed type. 1178 QualType result = 1179 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1180 RHS = (*doRHSCast)(S, RHS.get(), result); 1181 if (!IsCompAssign) 1182 LHS = (*doLHSCast)(S, LHS.get(), result); 1183 return result; 1184 } 1185 } 1186 1187 /// Handle conversions with GCC complex int extension. Helper function 1188 /// of UsualArithmeticConversions() 1189 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1190 ExprResult &RHS, QualType LHSType, 1191 QualType RHSType, 1192 bool IsCompAssign) { 1193 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1194 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1195 1196 if (LHSComplexInt && RHSComplexInt) { 1197 QualType LHSEltType = LHSComplexInt->getElementType(); 1198 QualType RHSEltType = RHSComplexInt->getElementType(); 1199 QualType ScalarType = 1200 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1201 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1202 1203 return S.Context.getComplexType(ScalarType); 1204 } 1205 1206 if (LHSComplexInt) { 1207 QualType LHSEltType = LHSComplexInt->getElementType(); 1208 QualType ScalarType = 1209 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1210 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1211 QualType ComplexType = S.Context.getComplexType(ScalarType); 1212 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1213 CK_IntegralRealToComplex); 1214 1215 return ComplexType; 1216 } 1217 1218 assert(RHSComplexInt); 1219 1220 QualType RHSEltType = RHSComplexInt->getElementType(); 1221 QualType ScalarType = 1222 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1223 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1224 QualType ComplexType = S.Context.getComplexType(ScalarType); 1225 1226 if (!IsCompAssign) 1227 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1228 CK_IntegralRealToComplex); 1229 return ComplexType; 1230 } 1231 1232 /// UsualArithmeticConversions - Performs various conversions that are common to 1233 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1234 /// routine returns the first non-arithmetic type found. The client is 1235 /// responsible for emitting appropriate error diagnostics. 1236 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1237 bool IsCompAssign) { 1238 if (!IsCompAssign) { 1239 LHS = UsualUnaryConversions(LHS.get()); 1240 if (LHS.isInvalid()) 1241 return QualType(); 1242 } 1243 1244 RHS = UsualUnaryConversions(RHS.get()); 1245 if (RHS.isInvalid()) 1246 return QualType(); 1247 1248 // For conversion purposes, we ignore any qualifiers. 1249 // For example, "const float" and "float" are equivalent. 1250 QualType LHSType = 1251 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1252 QualType RHSType = 1253 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1254 1255 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1256 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1257 LHSType = AtomicLHS->getValueType(); 1258 1259 // If both types are identical, no conversion is needed. 1260 if (LHSType == RHSType) 1261 return LHSType; 1262 1263 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1264 // The caller can deal with this (e.g. pointer + int). 1265 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1266 return QualType(); 1267 1268 // Apply unary and bitfield promotions to the LHS's type. 1269 QualType LHSUnpromotedType = LHSType; 1270 if (LHSType->isPromotableIntegerType()) 1271 LHSType = Context.getPromotedIntegerType(LHSType); 1272 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1273 if (!LHSBitfieldPromoteTy.isNull()) 1274 LHSType = LHSBitfieldPromoteTy; 1275 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1276 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1277 1278 // If both types are identical, no conversion is needed. 1279 if (LHSType == RHSType) 1280 return LHSType; 1281 1282 // At this point, we have two different arithmetic types. 1283 1284 // Diagnose attempts to convert between __float128 and long double where 1285 // such conversions currently can't be handled. 1286 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1287 return QualType(); 1288 1289 // Handle complex types first (C99 6.3.1.8p1). 1290 if (LHSType->isComplexType() || RHSType->isComplexType()) 1291 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1292 IsCompAssign); 1293 1294 // Now handle "real" floating types (i.e. float, double, long double). 1295 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1296 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1297 IsCompAssign); 1298 1299 // Handle GCC complex int extension. 1300 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1301 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1302 IsCompAssign); 1303 1304 // Finally, we have two differing integer types. 1305 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1306 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1307 } 1308 1309 1310 //===----------------------------------------------------------------------===// 1311 // Semantic Analysis for various Expression Types 1312 //===----------------------------------------------------------------------===// 1313 1314 1315 ExprResult 1316 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1317 SourceLocation DefaultLoc, 1318 SourceLocation RParenLoc, 1319 Expr *ControllingExpr, 1320 ArrayRef<ParsedType> ArgTypes, 1321 ArrayRef<Expr *> ArgExprs) { 1322 unsigned NumAssocs = ArgTypes.size(); 1323 assert(NumAssocs == ArgExprs.size()); 1324 1325 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1326 for (unsigned i = 0; i < NumAssocs; ++i) { 1327 if (ArgTypes[i]) 1328 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1329 else 1330 Types[i] = nullptr; 1331 } 1332 1333 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1334 ControllingExpr, 1335 llvm::makeArrayRef(Types, NumAssocs), 1336 ArgExprs); 1337 delete [] Types; 1338 return ER; 1339 } 1340 1341 ExprResult 1342 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1343 SourceLocation DefaultLoc, 1344 SourceLocation RParenLoc, 1345 Expr *ControllingExpr, 1346 ArrayRef<TypeSourceInfo *> Types, 1347 ArrayRef<Expr *> Exprs) { 1348 unsigned NumAssocs = Types.size(); 1349 assert(NumAssocs == Exprs.size()); 1350 1351 // Decay and strip qualifiers for the controlling expression type, and handle 1352 // placeholder type replacement. See committee discussion from WG14 DR423. 1353 { 1354 EnterExpressionEvaluationContext Unevaluated( 1355 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1356 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1357 if (R.isInvalid()) 1358 return ExprError(); 1359 ControllingExpr = R.get(); 1360 } 1361 1362 // The controlling expression is an unevaluated operand, so side effects are 1363 // likely unintended. 1364 if (!inTemplateInstantiation() && 1365 ControllingExpr->HasSideEffects(Context, false)) 1366 Diag(ControllingExpr->getExprLoc(), 1367 diag::warn_side_effects_unevaluated_context); 1368 1369 bool TypeErrorFound = false, 1370 IsResultDependent = ControllingExpr->isTypeDependent(), 1371 ContainsUnexpandedParameterPack 1372 = ControllingExpr->containsUnexpandedParameterPack(); 1373 1374 for (unsigned i = 0; i < NumAssocs; ++i) { 1375 if (Exprs[i]->containsUnexpandedParameterPack()) 1376 ContainsUnexpandedParameterPack = true; 1377 1378 if (Types[i]) { 1379 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1380 ContainsUnexpandedParameterPack = true; 1381 1382 if (Types[i]->getType()->isDependentType()) { 1383 IsResultDependent = true; 1384 } else { 1385 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1386 // complete object type other than a variably modified type." 1387 unsigned D = 0; 1388 if (Types[i]->getType()->isIncompleteType()) 1389 D = diag::err_assoc_type_incomplete; 1390 else if (!Types[i]->getType()->isObjectType()) 1391 D = diag::err_assoc_type_nonobject; 1392 else if (Types[i]->getType()->isVariablyModifiedType()) 1393 D = diag::err_assoc_type_variably_modified; 1394 1395 if (D != 0) { 1396 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1397 << Types[i]->getTypeLoc().getSourceRange() 1398 << Types[i]->getType(); 1399 TypeErrorFound = true; 1400 } 1401 1402 // C11 6.5.1.1p2 "No two generic associations in the same generic 1403 // selection shall specify compatible types." 1404 for (unsigned j = i+1; j < NumAssocs; ++j) 1405 if (Types[j] && !Types[j]->getType()->isDependentType() && 1406 Context.typesAreCompatible(Types[i]->getType(), 1407 Types[j]->getType())) { 1408 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1409 diag::err_assoc_compatible_types) 1410 << Types[j]->getTypeLoc().getSourceRange() 1411 << Types[j]->getType() 1412 << Types[i]->getType(); 1413 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1414 diag::note_compat_assoc) 1415 << Types[i]->getTypeLoc().getSourceRange() 1416 << Types[i]->getType(); 1417 TypeErrorFound = true; 1418 } 1419 } 1420 } 1421 } 1422 if (TypeErrorFound) 1423 return ExprError(); 1424 1425 // If we determined that the generic selection is result-dependent, don't 1426 // try to compute the result expression. 1427 if (IsResultDependent) 1428 return new (Context) GenericSelectionExpr( 1429 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1430 ContainsUnexpandedParameterPack); 1431 1432 SmallVector<unsigned, 1> CompatIndices; 1433 unsigned DefaultIndex = -1U; 1434 for (unsigned i = 0; i < NumAssocs; ++i) { 1435 if (!Types[i]) 1436 DefaultIndex = i; 1437 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1438 Types[i]->getType())) 1439 CompatIndices.push_back(i); 1440 } 1441 1442 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1443 // type compatible with at most one of the types named in its generic 1444 // association list." 1445 if (CompatIndices.size() > 1) { 1446 // We strip parens here because the controlling expression is typically 1447 // parenthesized in macro definitions. 1448 ControllingExpr = ControllingExpr->IgnoreParens(); 1449 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1450 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1451 << (unsigned)CompatIndices.size(); 1452 for (unsigned I : CompatIndices) { 1453 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1454 diag::note_compat_assoc) 1455 << Types[I]->getTypeLoc().getSourceRange() 1456 << Types[I]->getType(); 1457 } 1458 return ExprError(); 1459 } 1460 1461 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1462 // its controlling expression shall have type compatible with exactly one of 1463 // the types named in its generic association list." 1464 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1465 // We strip parens here because the controlling expression is typically 1466 // parenthesized in macro definitions. 1467 ControllingExpr = ControllingExpr->IgnoreParens(); 1468 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1469 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1470 return ExprError(); 1471 } 1472 1473 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1474 // type name that is compatible with the type of the controlling expression, 1475 // then the result expression of the generic selection is the expression 1476 // in that generic association. Otherwise, the result expression of the 1477 // generic selection is the expression in the default generic association." 1478 unsigned ResultIndex = 1479 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1480 1481 return new (Context) GenericSelectionExpr( 1482 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1483 ContainsUnexpandedParameterPack, ResultIndex); 1484 } 1485 1486 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1487 /// location of the token and the offset of the ud-suffix within it. 1488 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1489 unsigned Offset) { 1490 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1491 S.getLangOpts()); 1492 } 1493 1494 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1495 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1496 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1497 IdentifierInfo *UDSuffix, 1498 SourceLocation UDSuffixLoc, 1499 ArrayRef<Expr*> Args, 1500 SourceLocation LitEndLoc) { 1501 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1502 1503 QualType ArgTy[2]; 1504 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1505 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1506 if (ArgTy[ArgIdx]->isArrayType()) 1507 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1508 } 1509 1510 DeclarationName OpName = 1511 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1512 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1513 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1514 1515 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1516 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1517 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1518 /*AllowStringTemplate*/ false, 1519 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1520 return ExprError(); 1521 1522 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1523 } 1524 1525 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1526 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1527 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1528 /// multiple tokens. However, the common case is that StringToks points to one 1529 /// string. 1530 /// 1531 ExprResult 1532 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1533 assert(!StringToks.empty() && "Must have at least one string!"); 1534 1535 StringLiteralParser Literal(StringToks, PP); 1536 if (Literal.hadError) 1537 return ExprError(); 1538 1539 SmallVector<SourceLocation, 4> StringTokLocs; 1540 for (const Token &Tok : StringToks) 1541 StringTokLocs.push_back(Tok.getLocation()); 1542 1543 QualType CharTy = Context.CharTy; 1544 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1545 if (Literal.isWide()) { 1546 CharTy = Context.getWideCharType(); 1547 Kind = StringLiteral::Wide; 1548 } else if (Literal.isUTF8()) { 1549 if (getLangOpts().Char8) 1550 CharTy = Context.Char8Ty; 1551 Kind = StringLiteral::UTF8; 1552 } else if (Literal.isUTF16()) { 1553 CharTy = Context.Char16Ty; 1554 Kind = StringLiteral::UTF16; 1555 } else if (Literal.isUTF32()) { 1556 CharTy = Context.Char32Ty; 1557 Kind = StringLiteral::UTF32; 1558 } else if (Literal.isPascal()) { 1559 CharTy = Context.UnsignedCharTy; 1560 } 1561 1562 QualType CharTyConst = CharTy; 1563 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1564 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1565 CharTyConst.addConst(); 1566 1567 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1568 1569 // Get an array type for the string, according to C99 6.4.5. This includes 1570 // the nul terminator character as well as the string length for pascal 1571 // strings. 1572 QualType StrTy = Context.getConstantArrayType( 1573 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1574 ArrayType::Normal, 0); 1575 1576 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1577 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1578 Kind, Literal.Pascal, StrTy, 1579 &StringTokLocs[0], 1580 StringTokLocs.size()); 1581 if (Literal.getUDSuffix().empty()) 1582 return Lit; 1583 1584 // We're building a user-defined literal. 1585 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1586 SourceLocation UDSuffixLoc = 1587 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1588 Literal.getUDSuffixOffset()); 1589 1590 // Make sure we're allowed user-defined literals here. 1591 if (!UDLScope) 1592 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1593 1594 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1595 // operator "" X (str, len) 1596 QualType SizeType = Context.getSizeType(); 1597 1598 DeclarationName OpName = 1599 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1600 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1601 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1602 1603 QualType ArgTy[] = { 1604 Context.getArrayDecayedType(StrTy), SizeType 1605 }; 1606 1607 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1608 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1609 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1610 /*AllowStringTemplate*/ true, 1611 /*DiagnoseMissing*/ true)) { 1612 1613 case LOLR_Cooked: { 1614 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1615 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1616 StringTokLocs[0]); 1617 Expr *Args[] = { Lit, LenArg }; 1618 1619 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1620 } 1621 1622 case LOLR_StringTemplate: { 1623 TemplateArgumentListInfo ExplicitArgs; 1624 1625 unsigned CharBits = Context.getIntWidth(CharTy); 1626 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1627 llvm::APSInt Value(CharBits, CharIsUnsigned); 1628 1629 TemplateArgument TypeArg(CharTy); 1630 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1631 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1632 1633 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1634 Value = Lit->getCodeUnit(I); 1635 TemplateArgument Arg(Context, Value, CharTy); 1636 TemplateArgumentLocInfo ArgInfo; 1637 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1638 } 1639 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1640 &ExplicitArgs); 1641 } 1642 case LOLR_Raw: 1643 case LOLR_Template: 1644 case LOLR_ErrorNoDiagnostic: 1645 llvm_unreachable("unexpected literal operator lookup result"); 1646 case LOLR_Error: 1647 return ExprError(); 1648 } 1649 llvm_unreachable("unexpected literal operator lookup result"); 1650 } 1651 1652 ExprResult 1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1654 SourceLocation Loc, 1655 const CXXScopeSpec *SS) { 1656 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1657 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1658 } 1659 1660 /// BuildDeclRefExpr - Build an expression that references a 1661 /// declaration that does not require a closure capture. 1662 ExprResult 1663 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1664 const DeclarationNameInfo &NameInfo, 1665 const CXXScopeSpec *SS, NamedDecl *FoundD, 1666 const TemplateArgumentListInfo *TemplateArgs) { 1667 bool RefersToCapturedVariable = 1668 isa<VarDecl>(D) && 1669 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1670 1671 DeclRefExpr *E; 1672 if (isa<VarTemplateSpecializationDecl>(D)) { 1673 VarTemplateSpecializationDecl *VarSpec = 1674 cast<VarTemplateSpecializationDecl>(D); 1675 1676 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1677 : NestedNameSpecifierLoc(), 1678 VarSpec->getTemplateKeywordLoc(), D, 1679 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1680 FoundD, TemplateArgs); 1681 } else { 1682 assert(!TemplateArgs && "No template arguments for non-variable" 1683 " template specialization references"); 1684 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1685 : NestedNameSpecifierLoc(), 1686 SourceLocation(), D, RefersToCapturedVariable, 1687 NameInfo, Ty, VK, FoundD); 1688 } 1689 1690 MarkDeclRefReferenced(E); 1691 1692 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1693 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1694 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1695 getCurFunction()->recordUseOfWeak(E); 1696 1697 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1698 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1699 FD = IFD->getAnonField(); 1700 if (FD) { 1701 UnusedPrivateFields.remove(FD); 1702 // Just in case we're building an illegal pointer-to-member. 1703 if (FD->isBitField()) 1704 E->setObjectKind(OK_BitField); 1705 } 1706 1707 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1708 // designates a bit-field. 1709 if (auto *BD = dyn_cast<BindingDecl>(D)) 1710 if (auto *BE = BD->getBinding()) 1711 E->setObjectKind(BE->getObjectKind()); 1712 1713 return E; 1714 } 1715 1716 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1717 /// possibly a list of template arguments. 1718 /// 1719 /// If this produces template arguments, it is permitted to call 1720 /// DecomposeTemplateName. 1721 /// 1722 /// This actually loses a lot of source location information for 1723 /// non-standard name kinds; we should consider preserving that in 1724 /// some way. 1725 void 1726 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1727 TemplateArgumentListInfo &Buffer, 1728 DeclarationNameInfo &NameInfo, 1729 const TemplateArgumentListInfo *&TemplateArgs) { 1730 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1731 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1732 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1733 1734 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1735 Id.TemplateId->NumArgs); 1736 translateTemplateArguments(TemplateArgsPtr, Buffer); 1737 1738 TemplateName TName = Id.TemplateId->Template.get(); 1739 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1740 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1741 TemplateArgs = &Buffer; 1742 } else { 1743 NameInfo = GetNameFromUnqualifiedId(Id); 1744 TemplateArgs = nullptr; 1745 } 1746 } 1747 1748 static void emitEmptyLookupTypoDiagnostic( 1749 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1750 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1751 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1752 DeclContext *Ctx = 1753 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1754 if (!TC) { 1755 // Emit a special diagnostic for failed member lookups. 1756 // FIXME: computing the declaration context might fail here (?) 1757 if (Ctx) 1758 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1759 << SS.getRange(); 1760 else 1761 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1762 return; 1763 } 1764 1765 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1766 bool DroppedSpecifier = 1767 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1768 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1769 ? diag::note_implicit_param_decl 1770 : diag::note_previous_decl; 1771 if (!Ctx) 1772 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1773 SemaRef.PDiag(NoteID)); 1774 else 1775 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1776 << Typo << Ctx << DroppedSpecifier 1777 << SS.getRange(), 1778 SemaRef.PDiag(NoteID)); 1779 } 1780 1781 /// Diagnose an empty lookup. 1782 /// 1783 /// \return false if new lookup candidates were found 1784 bool 1785 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1786 std::unique_ptr<CorrectionCandidateCallback> CCC, 1787 TemplateArgumentListInfo *ExplicitTemplateArgs, 1788 ArrayRef<Expr *> Args, TypoExpr **Out) { 1789 DeclarationName Name = R.getLookupName(); 1790 1791 unsigned diagnostic = diag::err_undeclared_var_use; 1792 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1793 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1794 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1795 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1796 diagnostic = diag::err_undeclared_use; 1797 diagnostic_suggest = diag::err_undeclared_use_suggest; 1798 } 1799 1800 // If the original lookup was an unqualified lookup, fake an 1801 // unqualified lookup. This is useful when (for example) the 1802 // original lookup would not have found something because it was a 1803 // dependent name. 1804 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1805 while (DC) { 1806 if (isa<CXXRecordDecl>(DC)) { 1807 LookupQualifiedName(R, DC); 1808 1809 if (!R.empty()) { 1810 // Don't give errors about ambiguities in this lookup. 1811 R.suppressDiagnostics(); 1812 1813 // During a default argument instantiation the CurContext points 1814 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1815 // function parameter list, hence add an explicit check. 1816 bool isDefaultArgument = 1817 !CodeSynthesisContexts.empty() && 1818 CodeSynthesisContexts.back().Kind == 1819 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1820 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1821 bool isInstance = CurMethod && 1822 CurMethod->isInstance() && 1823 DC == CurMethod->getParent() && !isDefaultArgument; 1824 1825 // Give a code modification hint to insert 'this->'. 1826 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1827 // Actually quite difficult! 1828 if (getLangOpts().MSVCCompat) 1829 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1830 if (isInstance) { 1831 Diag(R.getNameLoc(), diagnostic) << Name 1832 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1833 CheckCXXThisCapture(R.getNameLoc()); 1834 } else { 1835 Diag(R.getNameLoc(), diagnostic) << Name; 1836 } 1837 1838 // Do we really want to note all of these? 1839 for (NamedDecl *D : R) 1840 Diag(D->getLocation(), diag::note_dependent_var_use); 1841 1842 // Return true if we are inside a default argument instantiation 1843 // and the found name refers to an instance member function, otherwise 1844 // the function calling DiagnoseEmptyLookup will try to create an 1845 // implicit member call and this is wrong for default argument. 1846 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1847 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1848 return true; 1849 } 1850 1851 // Tell the callee to try to recover. 1852 return false; 1853 } 1854 1855 R.clear(); 1856 } 1857 1858 // In Microsoft mode, if we are performing lookup from within a friend 1859 // function definition declared at class scope then we must set 1860 // DC to the lexical parent to be able to search into the parent 1861 // class. 1862 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1863 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1864 DC->getLexicalParent()->isRecord()) 1865 DC = DC->getLexicalParent(); 1866 else 1867 DC = DC->getParent(); 1868 } 1869 1870 // We didn't find anything, so try to correct for a typo. 1871 TypoCorrection Corrected; 1872 if (S && Out) { 1873 SourceLocation TypoLoc = R.getNameLoc(); 1874 assert(!ExplicitTemplateArgs && 1875 "Diagnosing an empty lookup with explicit template args!"); 1876 *Out = CorrectTypoDelayed( 1877 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1878 [=](const TypoCorrection &TC) { 1879 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1880 diagnostic, diagnostic_suggest); 1881 }, 1882 nullptr, CTK_ErrorRecovery); 1883 if (*Out) 1884 return true; 1885 } else if (S && (Corrected = 1886 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1887 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1888 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1889 bool DroppedSpecifier = 1890 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1891 R.setLookupName(Corrected.getCorrection()); 1892 1893 bool AcceptableWithRecovery = false; 1894 bool AcceptableWithoutRecovery = false; 1895 NamedDecl *ND = Corrected.getFoundDecl(); 1896 if (ND) { 1897 if (Corrected.isOverloaded()) { 1898 OverloadCandidateSet OCS(R.getNameLoc(), 1899 OverloadCandidateSet::CSK_Normal); 1900 OverloadCandidateSet::iterator Best; 1901 for (NamedDecl *CD : Corrected) { 1902 if (FunctionTemplateDecl *FTD = 1903 dyn_cast<FunctionTemplateDecl>(CD)) 1904 AddTemplateOverloadCandidate( 1905 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1906 Args, OCS); 1907 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1908 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1909 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1910 Args, OCS); 1911 } 1912 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1913 case OR_Success: 1914 ND = Best->FoundDecl; 1915 Corrected.setCorrectionDecl(ND); 1916 break; 1917 default: 1918 // FIXME: Arbitrarily pick the first declaration for the note. 1919 Corrected.setCorrectionDecl(ND); 1920 break; 1921 } 1922 } 1923 R.addDecl(ND); 1924 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1925 CXXRecordDecl *Record = nullptr; 1926 if (Corrected.getCorrectionSpecifier()) { 1927 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1928 Record = Ty->getAsCXXRecordDecl(); 1929 } 1930 if (!Record) 1931 Record = cast<CXXRecordDecl>( 1932 ND->getDeclContext()->getRedeclContext()); 1933 R.setNamingClass(Record); 1934 } 1935 1936 auto *UnderlyingND = ND->getUnderlyingDecl(); 1937 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1938 isa<FunctionTemplateDecl>(UnderlyingND); 1939 // FIXME: If we ended up with a typo for a type name or 1940 // Objective-C class name, we're in trouble because the parser 1941 // is in the wrong place to recover. Suggest the typo 1942 // correction, but don't make it a fix-it since we're not going 1943 // to recover well anyway. 1944 AcceptableWithoutRecovery = 1945 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1946 } else { 1947 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1948 // because we aren't able to recover. 1949 AcceptableWithoutRecovery = true; 1950 } 1951 1952 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1953 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1954 ? diag::note_implicit_param_decl 1955 : diag::note_previous_decl; 1956 if (SS.isEmpty()) 1957 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1958 PDiag(NoteID), AcceptableWithRecovery); 1959 else 1960 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1961 << Name << computeDeclContext(SS, false) 1962 << DroppedSpecifier << SS.getRange(), 1963 PDiag(NoteID), AcceptableWithRecovery); 1964 1965 // Tell the callee whether to try to recover. 1966 return !AcceptableWithRecovery; 1967 } 1968 } 1969 R.clear(); 1970 1971 // Emit a special diagnostic for failed member lookups. 1972 // FIXME: computing the declaration context might fail here (?) 1973 if (!SS.isEmpty()) { 1974 Diag(R.getNameLoc(), diag::err_no_member) 1975 << Name << computeDeclContext(SS, false) 1976 << SS.getRange(); 1977 return true; 1978 } 1979 1980 // Give up, we can't recover. 1981 Diag(R.getNameLoc(), diagnostic) << Name; 1982 return true; 1983 } 1984 1985 /// In Microsoft mode, if we are inside a template class whose parent class has 1986 /// dependent base classes, and we can't resolve an unqualified identifier, then 1987 /// assume the identifier is a member of a dependent base class. We can only 1988 /// recover successfully in static methods, instance methods, and other contexts 1989 /// where 'this' is available. This doesn't precisely match MSVC's 1990 /// instantiation model, but it's close enough. 1991 static Expr * 1992 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1993 DeclarationNameInfo &NameInfo, 1994 SourceLocation TemplateKWLoc, 1995 const TemplateArgumentListInfo *TemplateArgs) { 1996 // Only try to recover from lookup into dependent bases in static methods or 1997 // contexts where 'this' is available. 1998 QualType ThisType = S.getCurrentThisType(); 1999 const CXXRecordDecl *RD = nullptr; 2000 if (!ThisType.isNull()) 2001 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2002 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2003 RD = MD->getParent(); 2004 if (!RD || !RD->hasAnyDependentBases()) 2005 return nullptr; 2006 2007 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2008 // is available, suggest inserting 'this->' as a fixit. 2009 SourceLocation Loc = NameInfo.getLoc(); 2010 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2011 DB << NameInfo.getName() << RD; 2012 2013 if (!ThisType.isNull()) { 2014 DB << FixItHint::CreateInsertion(Loc, "this->"); 2015 return CXXDependentScopeMemberExpr::Create( 2016 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2017 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2018 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2019 } 2020 2021 // Synthesize a fake NNS that points to the derived class. This will 2022 // perform name lookup during template instantiation. 2023 CXXScopeSpec SS; 2024 auto *NNS = 2025 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2026 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2027 return DependentScopeDeclRefExpr::Create( 2028 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2029 TemplateArgs); 2030 } 2031 2032 ExprResult 2033 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2034 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2035 bool HasTrailingLParen, bool IsAddressOfOperand, 2036 std::unique_ptr<CorrectionCandidateCallback> CCC, 2037 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2038 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2039 "cannot be direct & operand and have a trailing lparen"); 2040 if (SS.isInvalid()) 2041 return ExprError(); 2042 2043 TemplateArgumentListInfo TemplateArgsBuffer; 2044 2045 // Decompose the UnqualifiedId into the following data. 2046 DeclarationNameInfo NameInfo; 2047 const TemplateArgumentListInfo *TemplateArgs; 2048 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2049 2050 DeclarationName Name = NameInfo.getName(); 2051 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2052 SourceLocation NameLoc = NameInfo.getLoc(); 2053 2054 if (II && II->isEditorPlaceholder()) { 2055 // FIXME: When typed placeholders are supported we can create a typed 2056 // placeholder expression node. 2057 return ExprError(); 2058 } 2059 2060 // C++ [temp.dep.expr]p3: 2061 // An id-expression is type-dependent if it contains: 2062 // -- an identifier that was declared with a dependent type, 2063 // (note: handled after lookup) 2064 // -- a template-id that is dependent, 2065 // (note: handled in BuildTemplateIdExpr) 2066 // -- a conversion-function-id that specifies a dependent type, 2067 // -- a nested-name-specifier that contains a class-name that 2068 // names a dependent type. 2069 // Determine whether this is a member of an unknown specialization; 2070 // we need to handle these differently. 2071 bool DependentID = false; 2072 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2073 Name.getCXXNameType()->isDependentType()) { 2074 DependentID = true; 2075 } else if (SS.isSet()) { 2076 if (DeclContext *DC = computeDeclContext(SS, false)) { 2077 if (RequireCompleteDeclContext(SS, DC)) 2078 return ExprError(); 2079 } else { 2080 DependentID = true; 2081 } 2082 } 2083 2084 if (DependentID) 2085 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2086 IsAddressOfOperand, TemplateArgs); 2087 2088 // Perform the required lookup. 2089 LookupResult R(*this, NameInfo, 2090 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2091 ? LookupObjCImplicitSelfParam 2092 : LookupOrdinaryName); 2093 if (TemplateKWLoc.isValid() || TemplateArgs) { 2094 // Lookup the template name again to correctly establish the context in 2095 // which it was found. This is really unfortunate as we already did the 2096 // lookup to determine that it was a template name in the first place. If 2097 // this becomes a performance hit, we can work harder to preserve those 2098 // results until we get here but it's likely not worth it. 2099 bool MemberOfUnknownSpecialization; 2100 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2101 MemberOfUnknownSpecialization, TemplateKWLoc)) 2102 return ExprError(); 2103 2104 if (MemberOfUnknownSpecialization || 2105 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2106 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2107 IsAddressOfOperand, TemplateArgs); 2108 } else { 2109 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2110 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2111 2112 // If the result might be in a dependent base class, this is a dependent 2113 // id-expression. 2114 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2115 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2116 IsAddressOfOperand, TemplateArgs); 2117 2118 // If this reference is in an Objective-C method, then we need to do 2119 // some special Objective-C lookup, too. 2120 if (IvarLookupFollowUp) { 2121 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2122 if (E.isInvalid()) 2123 return ExprError(); 2124 2125 if (Expr *Ex = E.getAs<Expr>()) 2126 return Ex; 2127 } 2128 } 2129 2130 if (R.isAmbiguous()) 2131 return ExprError(); 2132 2133 // This could be an implicitly declared function reference (legal in C90, 2134 // extension in C99, forbidden in C++). 2135 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2136 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2137 if (D) R.addDecl(D); 2138 } 2139 2140 // Determine whether this name might be a candidate for 2141 // argument-dependent lookup. 2142 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2143 2144 if (R.empty() && !ADL) { 2145 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2146 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2147 TemplateKWLoc, TemplateArgs)) 2148 return E; 2149 } 2150 2151 // Don't diagnose an empty lookup for inline assembly. 2152 if (IsInlineAsmIdentifier) 2153 return ExprError(); 2154 2155 // If this name wasn't predeclared and if this is not a function 2156 // call, diagnose the problem. 2157 TypoExpr *TE = nullptr; 2158 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2159 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2160 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2161 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2162 "Typo correction callback misconfigured"); 2163 if (CCC) { 2164 // Make sure the callback knows what the typo being diagnosed is. 2165 CCC->setTypoName(II); 2166 if (SS.isValid()) 2167 CCC->setTypoNNS(SS.getScopeRep()); 2168 } 2169 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2170 // a template name, but we happen to have always already looked up the name 2171 // before we get here if it must be a template name. 2172 if (DiagnoseEmptyLookup(S, SS, R, 2173 CCC ? std::move(CCC) : std::move(DefaultValidator), 2174 nullptr, None, &TE)) { 2175 if (TE && KeywordReplacement) { 2176 auto &State = getTypoExprState(TE); 2177 auto BestTC = State.Consumer->getNextCorrection(); 2178 if (BestTC.isKeyword()) { 2179 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2180 if (State.DiagHandler) 2181 State.DiagHandler(BestTC); 2182 KeywordReplacement->startToken(); 2183 KeywordReplacement->setKind(II->getTokenID()); 2184 KeywordReplacement->setIdentifierInfo(II); 2185 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2186 // Clean up the state associated with the TypoExpr, since it has 2187 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2188 clearDelayedTypo(TE); 2189 // Signal that a correction to a keyword was performed by returning a 2190 // valid-but-null ExprResult. 2191 return (Expr*)nullptr; 2192 } 2193 State.Consumer->resetCorrectionStream(); 2194 } 2195 return TE ? TE : ExprError(); 2196 } 2197 2198 assert(!R.empty() && 2199 "DiagnoseEmptyLookup returned false but added no results"); 2200 2201 // If we found an Objective-C instance variable, let 2202 // LookupInObjCMethod build the appropriate expression to 2203 // reference the ivar. 2204 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2205 R.clear(); 2206 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2207 // In a hopelessly buggy code, Objective-C instance variable 2208 // lookup fails and no expression will be built to reference it. 2209 if (!E.isInvalid() && !E.get()) 2210 return ExprError(); 2211 return E; 2212 } 2213 } 2214 2215 // This is guaranteed from this point on. 2216 assert(!R.empty() || ADL); 2217 2218 // Check whether this might be a C++ implicit instance member access. 2219 // C++ [class.mfct.non-static]p3: 2220 // When an id-expression that is not part of a class member access 2221 // syntax and not used to form a pointer to member is used in the 2222 // body of a non-static member function of class X, if name lookup 2223 // resolves the name in the id-expression to a non-static non-type 2224 // member of some class C, the id-expression is transformed into a 2225 // class member access expression using (*this) as the 2226 // postfix-expression to the left of the . operator. 2227 // 2228 // But we don't actually need to do this for '&' operands if R 2229 // resolved to a function or overloaded function set, because the 2230 // expression is ill-formed if it actually works out to be a 2231 // non-static member function: 2232 // 2233 // C++ [expr.ref]p4: 2234 // Otherwise, if E1.E2 refers to a non-static member function. . . 2235 // [t]he expression can be used only as the left-hand operand of a 2236 // member function call. 2237 // 2238 // There are other safeguards against such uses, but it's important 2239 // to get this right here so that we don't end up making a 2240 // spuriously dependent expression if we're inside a dependent 2241 // instance method. 2242 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2243 bool MightBeImplicitMember; 2244 if (!IsAddressOfOperand) 2245 MightBeImplicitMember = true; 2246 else if (!SS.isEmpty()) 2247 MightBeImplicitMember = false; 2248 else if (R.isOverloadedResult()) 2249 MightBeImplicitMember = false; 2250 else if (R.isUnresolvableResult()) 2251 MightBeImplicitMember = true; 2252 else 2253 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2254 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2255 isa<MSPropertyDecl>(R.getFoundDecl()); 2256 2257 if (MightBeImplicitMember) 2258 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2259 R, TemplateArgs, S); 2260 } 2261 2262 if (TemplateArgs || TemplateKWLoc.isValid()) { 2263 2264 // In C++1y, if this is a variable template id, then check it 2265 // in BuildTemplateIdExpr(). 2266 // The single lookup result must be a variable template declaration. 2267 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2268 Id.TemplateId->Kind == TNK_Var_template) { 2269 assert(R.getAsSingle<VarTemplateDecl>() && 2270 "There should only be one declaration found."); 2271 } 2272 2273 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2274 } 2275 2276 return BuildDeclarationNameExpr(SS, R, ADL); 2277 } 2278 2279 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2280 /// declaration name, generally during template instantiation. 2281 /// There's a large number of things which don't need to be done along 2282 /// this path. 2283 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2284 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2285 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2286 DeclContext *DC = computeDeclContext(SS, false); 2287 if (!DC) 2288 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2289 NameInfo, /*TemplateArgs=*/nullptr); 2290 2291 if (RequireCompleteDeclContext(SS, DC)) 2292 return ExprError(); 2293 2294 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2295 LookupQualifiedName(R, DC); 2296 2297 if (R.isAmbiguous()) 2298 return ExprError(); 2299 2300 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2301 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2302 NameInfo, /*TemplateArgs=*/nullptr); 2303 2304 if (R.empty()) { 2305 Diag(NameInfo.getLoc(), diag::err_no_member) 2306 << NameInfo.getName() << DC << SS.getRange(); 2307 return ExprError(); 2308 } 2309 2310 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2311 // Diagnose a missing typename if this resolved unambiguously to a type in 2312 // a dependent context. If we can recover with a type, downgrade this to 2313 // a warning in Microsoft compatibility mode. 2314 unsigned DiagID = diag::err_typename_missing; 2315 if (RecoveryTSI && getLangOpts().MSVCCompat) 2316 DiagID = diag::ext_typename_missing; 2317 SourceLocation Loc = SS.getBeginLoc(); 2318 auto D = Diag(Loc, DiagID); 2319 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2320 << SourceRange(Loc, NameInfo.getEndLoc()); 2321 2322 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2323 // context. 2324 if (!RecoveryTSI) 2325 return ExprError(); 2326 2327 // Only issue the fixit if we're prepared to recover. 2328 D << FixItHint::CreateInsertion(Loc, "typename "); 2329 2330 // Recover by pretending this was an elaborated type. 2331 QualType Ty = Context.getTypeDeclType(TD); 2332 TypeLocBuilder TLB; 2333 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2334 2335 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2336 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2337 QTL.setElaboratedKeywordLoc(SourceLocation()); 2338 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2339 2340 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2341 2342 return ExprEmpty(); 2343 } 2344 2345 // Defend against this resolving to an implicit member access. We usually 2346 // won't get here if this might be a legitimate a class member (we end up in 2347 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2348 // a pointer-to-member or in an unevaluated context in C++11. 2349 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2350 return BuildPossibleImplicitMemberExpr(SS, 2351 /*TemplateKWLoc=*/SourceLocation(), 2352 R, /*TemplateArgs=*/nullptr, S); 2353 2354 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2355 } 2356 2357 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2358 /// detected that we're currently inside an ObjC method. Perform some 2359 /// additional lookup. 2360 /// 2361 /// Ideally, most of this would be done by lookup, but there's 2362 /// actually quite a lot of extra work involved. 2363 /// 2364 /// Returns a null sentinel to indicate trivial success. 2365 ExprResult 2366 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2367 IdentifierInfo *II, bool AllowBuiltinCreation) { 2368 SourceLocation Loc = Lookup.getNameLoc(); 2369 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2370 2371 // Check for error condition which is already reported. 2372 if (!CurMethod) 2373 return ExprError(); 2374 2375 // There are two cases to handle here. 1) scoped lookup could have failed, 2376 // in which case we should look for an ivar. 2) scoped lookup could have 2377 // found a decl, but that decl is outside the current instance method (i.e. 2378 // a global variable). In these two cases, we do a lookup for an ivar with 2379 // this name, if the lookup sucedes, we replace it our current decl. 2380 2381 // If we're in a class method, we don't normally want to look for 2382 // ivars. But if we don't find anything else, and there's an 2383 // ivar, that's an error. 2384 bool IsClassMethod = CurMethod->isClassMethod(); 2385 2386 bool LookForIvars; 2387 if (Lookup.empty()) 2388 LookForIvars = true; 2389 else if (IsClassMethod) 2390 LookForIvars = false; 2391 else 2392 LookForIvars = (Lookup.isSingleResult() && 2393 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2394 ObjCInterfaceDecl *IFace = nullptr; 2395 if (LookForIvars) { 2396 IFace = CurMethod->getClassInterface(); 2397 ObjCInterfaceDecl *ClassDeclared; 2398 ObjCIvarDecl *IV = nullptr; 2399 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2400 // Diagnose using an ivar in a class method. 2401 if (IsClassMethod) 2402 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2403 << IV->getDeclName()); 2404 2405 // If we're referencing an invalid decl, just return this as a silent 2406 // error node. The error diagnostic was already emitted on the decl. 2407 if (IV->isInvalidDecl()) 2408 return ExprError(); 2409 2410 // Check if referencing a field with __attribute__((deprecated)). 2411 if (DiagnoseUseOfDecl(IV, Loc)) 2412 return ExprError(); 2413 2414 // Diagnose the use of an ivar outside of the declaring class. 2415 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2416 !declaresSameEntity(ClassDeclared, IFace) && 2417 !getLangOpts().DebuggerSupport) 2418 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2419 2420 // FIXME: This should use a new expr for a direct reference, don't 2421 // turn this into Self->ivar, just return a BareIVarExpr or something. 2422 IdentifierInfo &II = Context.Idents.get("self"); 2423 UnqualifiedId SelfName; 2424 SelfName.setIdentifier(&II, SourceLocation()); 2425 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2426 CXXScopeSpec SelfScopeSpec; 2427 SourceLocation TemplateKWLoc; 2428 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2429 SelfName, false, false); 2430 if (SelfExpr.isInvalid()) 2431 return ExprError(); 2432 2433 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2434 if (SelfExpr.isInvalid()) 2435 return ExprError(); 2436 2437 MarkAnyDeclReferenced(Loc, IV, true); 2438 2439 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2440 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2441 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2442 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2443 2444 ObjCIvarRefExpr *Result = new (Context) 2445 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2446 IV->getLocation(), SelfExpr.get(), true, true); 2447 2448 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2449 if (!isUnevaluatedContext() && 2450 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2451 getCurFunction()->recordUseOfWeak(Result); 2452 } 2453 if (getLangOpts().ObjCAutoRefCount) { 2454 if (CurContext->isClosure()) 2455 Diag(Loc, diag::warn_implicitly_retains_self) 2456 << FixItHint::CreateInsertion(Loc, "self->"); 2457 } 2458 2459 return Result; 2460 } 2461 } else if (CurMethod->isInstanceMethod()) { 2462 // We should warn if a local variable hides an ivar. 2463 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2464 ObjCInterfaceDecl *ClassDeclared; 2465 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2466 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2467 declaresSameEntity(IFace, ClassDeclared)) 2468 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2469 } 2470 } 2471 } else if (Lookup.isSingleResult() && 2472 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2473 // If accessing a stand-alone ivar in a class method, this is an error. 2474 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2475 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2476 << IV->getDeclName()); 2477 } 2478 2479 if (Lookup.empty() && II && AllowBuiltinCreation) { 2480 // FIXME. Consolidate this with similar code in LookupName. 2481 if (unsigned BuiltinID = II->getBuiltinID()) { 2482 if (!(getLangOpts().CPlusPlus && 2483 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2484 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2485 S, Lookup.isForRedeclaration(), 2486 Lookup.getNameLoc()); 2487 if (D) Lookup.addDecl(D); 2488 } 2489 } 2490 } 2491 // Sentinel value saying that we didn't do anything special. 2492 return ExprResult((Expr *)nullptr); 2493 } 2494 2495 /// Cast a base object to a member's actual type. 2496 /// 2497 /// Logically this happens in three phases: 2498 /// 2499 /// * First we cast from the base type to the naming class. 2500 /// The naming class is the class into which we were looking 2501 /// when we found the member; it's the qualifier type if a 2502 /// qualifier was provided, and otherwise it's the base type. 2503 /// 2504 /// * Next we cast from the naming class to the declaring class. 2505 /// If the member we found was brought into a class's scope by 2506 /// a using declaration, this is that class; otherwise it's 2507 /// the class declaring the member. 2508 /// 2509 /// * Finally we cast from the declaring class to the "true" 2510 /// declaring class of the member. This conversion does not 2511 /// obey access control. 2512 ExprResult 2513 Sema::PerformObjectMemberConversion(Expr *From, 2514 NestedNameSpecifier *Qualifier, 2515 NamedDecl *FoundDecl, 2516 NamedDecl *Member) { 2517 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2518 if (!RD) 2519 return From; 2520 2521 QualType DestRecordType; 2522 QualType DestType; 2523 QualType FromRecordType; 2524 QualType FromType = From->getType(); 2525 bool PointerConversions = false; 2526 if (isa<FieldDecl>(Member)) { 2527 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2528 2529 if (FromType->getAs<PointerType>()) { 2530 DestType = Context.getPointerType(DestRecordType); 2531 FromRecordType = FromType->getPointeeType(); 2532 PointerConversions = true; 2533 } else { 2534 DestType = DestRecordType; 2535 FromRecordType = FromType; 2536 } 2537 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2538 if (Method->isStatic()) 2539 return From; 2540 2541 DestType = Method->getThisType(Context); 2542 DestRecordType = DestType->getPointeeType(); 2543 2544 if (FromType->getAs<PointerType>()) { 2545 FromRecordType = FromType->getPointeeType(); 2546 PointerConversions = true; 2547 } else { 2548 FromRecordType = FromType; 2549 DestType = DestRecordType; 2550 } 2551 } else { 2552 // No conversion necessary. 2553 return From; 2554 } 2555 2556 if (DestType->isDependentType() || FromType->isDependentType()) 2557 return From; 2558 2559 // If the unqualified types are the same, no conversion is necessary. 2560 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2561 return From; 2562 2563 SourceRange FromRange = From->getSourceRange(); 2564 SourceLocation FromLoc = FromRange.getBegin(); 2565 2566 ExprValueKind VK = From->getValueKind(); 2567 2568 // C++ [class.member.lookup]p8: 2569 // [...] Ambiguities can often be resolved by qualifying a name with its 2570 // class name. 2571 // 2572 // If the member was a qualified name and the qualified referred to a 2573 // specific base subobject type, we'll cast to that intermediate type 2574 // first and then to the object in which the member is declared. That allows 2575 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2576 // 2577 // class Base { public: int x; }; 2578 // class Derived1 : public Base { }; 2579 // class Derived2 : public Base { }; 2580 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2581 // 2582 // void VeryDerived::f() { 2583 // x = 17; // error: ambiguous base subobjects 2584 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2585 // } 2586 if (Qualifier && Qualifier->getAsType()) { 2587 QualType QType = QualType(Qualifier->getAsType(), 0); 2588 assert(QType->isRecordType() && "lookup done with non-record type"); 2589 2590 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2591 2592 // In C++98, the qualifier type doesn't actually have to be a base 2593 // type of the object type, in which case we just ignore it. 2594 // Otherwise build the appropriate casts. 2595 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2596 CXXCastPath BasePath; 2597 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2598 FromLoc, FromRange, &BasePath)) 2599 return ExprError(); 2600 2601 if (PointerConversions) 2602 QType = Context.getPointerType(QType); 2603 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2604 VK, &BasePath).get(); 2605 2606 FromType = QType; 2607 FromRecordType = QRecordType; 2608 2609 // If the qualifier type was the same as the destination type, 2610 // we're done. 2611 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2612 return From; 2613 } 2614 } 2615 2616 bool IgnoreAccess = false; 2617 2618 // If we actually found the member through a using declaration, cast 2619 // down to the using declaration's type. 2620 // 2621 // Pointer equality is fine here because only one declaration of a 2622 // class ever has member declarations. 2623 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2624 assert(isa<UsingShadowDecl>(FoundDecl)); 2625 QualType URecordType = Context.getTypeDeclType( 2626 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2627 2628 // We only need to do this if the naming-class to declaring-class 2629 // conversion is non-trivial. 2630 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2631 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2632 CXXCastPath BasePath; 2633 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2634 FromLoc, FromRange, &BasePath)) 2635 return ExprError(); 2636 2637 QualType UType = URecordType; 2638 if (PointerConversions) 2639 UType = Context.getPointerType(UType); 2640 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2641 VK, &BasePath).get(); 2642 FromType = UType; 2643 FromRecordType = URecordType; 2644 } 2645 2646 // We don't do access control for the conversion from the 2647 // declaring class to the true declaring class. 2648 IgnoreAccess = true; 2649 } 2650 2651 CXXCastPath BasePath; 2652 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2653 FromLoc, FromRange, &BasePath, 2654 IgnoreAccess)) 2655 return ExprError(); 2656 2657 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2658 VK, &BasePath); 2659 } 2660 2661 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2662 const LookupResult &R, 2663 bool HasTrailingLParen) { 2664 // Only when used directly as the postfix-expression of a call. 2665 if (!HasTrailingLParen) 2666 return false; 2667 2668 // Never if a scope specifier was provided. 2669 if (SS.isSet()) 2670 return false; 2671 2672 // Only in C++ or ObjC++. 2673 if (!getLangOpts().CPlusPlus) 2674 return false; 2675 2676 // Turn off ADL when we find certain kinds of declarations during 2677 // normal lookup: 2678 for (NamedDecl *D : R) { 2679 // C++0x [basic.lookup.argdep]p3: 2680 // -- a declaration of a class member 2681 // Since using decls preserve this property, we check this on the 2682 // original decl. 2683 if (D->isCXXClassMember()) 2684 return false; 2685 2686 // C++0x [basic.lookup.argdep]p3: 2687 // -- a block-scope function declaration that is not a 2688 // using-declaration 2689 // NOTE: we also trigger this for function templates (in fact, we 2690 // don't check the decl type at all, since all other decl types 2691 // turn off ADL anyway). 2692 if (isa<UsingShadowDecl>(D)) 2693 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2694 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2695 return false; 2696 2697 // C++0x [basic.lookup.argdep]p3: 2698 // -- a declaration that is neither a function or a function 2699 // template 2700 // And also for builtin functions. 2701 if (isa<FunctionDecl>(D)) { 2702 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2703 2704 // But also builtin functions. 2705 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2706 return false; 2707 } else if (!isa<FunctionTemplateDecl>(D)) 2708 return false; 2709 } 2710 2711 return true; 2712 } 2713 2714 2715 /// Diagnoses obvious problems with the use of the given declaration 2716 /// as an expression. This is only actually called for lookups that 2717 /// were not overloaded, and it doesn't promise that the declaration 2718 /// will in fact be used. 2719 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2720 if (D->isInvalidDecl()) 2721 return true; 2722 2723 if (isa<TypedefNameDecl>(D)) { 2724 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2725 return true; 2726 } 2727 2728 if (isa<ObjCInterfaceDecl>(D)) { 2729 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2730 return true; 2731 } 2732 2733 if (isa<NamespaceDecl>(D)) { 2734 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2735 return true; 2736 } 2737 2738 return false; 2739 } 2740 2741 // Certain multiversion types should be treated as overloaded even when there is 2742 // only one result. 2743 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2744 assert(R.isSingleResult() && "Expected only a single result"); 2745 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2746 return FD && 2747 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2748 } 2749 2750 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2751 LookupResult &R, bool NeedsADL, 2752 bool AcceptInvalidDecl) { 2753 // If this is a single, fully-resolved result and we don't need ADL, 2754 // just build an ordinary singleton decl ref. 2755 if (!NeedsADL && R.isSingleResult() && 2756 !R.getAsSingle<FunctionTemplateDecl>() && 2757 !ShouldLookupResultBeMultiVersionOverload(R)) 2758 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2759 R.getRepresentativeDecl(), nullptr, 2760 AcceptInvalidDecl); 2761 2762 // We only need to check the declaration if there's exactly one 2763 // result, because in the overloaded case the results can only be 2764 // functions and function templates. 2765 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2766 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2767 return ExprError(); 2768 2769 // Otherwise, just build an unresolved lookup expression. Suppress 2770 // any lookup-related diagnostics; we'll hash these out later, when 2771 // we've picked a target. 2772 R.suppressDiagnostics(); 2773 2774 UnresolvedLookupExpr *ULE 2775 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2776 SS.getWithLocInContext(Context), 2777 R.getLookupNameInfo(), 2778 NeedsADL, R.isOverloadedResult(), 2779 R.begin(), R.end()); 2780 2781 return ULE; 2782 } 2783 2784 static void 2785 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2786 ValueDecl *var, DeclContext *DC); 2787 2788 /// Complete semantic analysis for a reference to the given declaration. 2789 ExprResult Sema::BuildDeclarationNameExpr( 2790 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2791 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2792 bool AcceptInvalidDecl) { 2793 assert(D && "Cannot refer to a NULL declaration"); 2794 assert(!isa<FunctionTemplateDecl>(D) && 2795 "Cannot refer unambiguously to a function template"); 2796 2797 SourceLocation Loc = NameInfo.getLoc(); 2798 if (CheckDeclInExpr(*this, Loc, D)) 2799 return ExprError(); 2800 2801 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2802 // Specifically diagnose references to class templates that are missing 2803 // a template argument list. 2804 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2805 return ExprError(); 2806 } 2807 2808 // Make sure that we're referring to a value. 2809 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2810 if (!VD) { 2811 Diag(Loc, diag::err_ref_non_value) 2812 << D << SS.getRange(); 2813 Diag(D->getLocation(), diag::note_declared_at); 2814 return ExprError(); 2815 } 2816 2817 // Check whether this declaration can be used. Note that we suppress 2818 // this check when we're going to perform argument-dependent lookup 2819 // on this function name, because this might not be the function 2820 // that overload resolution actually selects. 2821 if (DiagnoseUseOfDecl(VD, Loc)) 2822 return ExprError(); 2823 2824 // Only create DeclRefExpr's for valid Decl's. 2825 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2826 return ExprError(); 2827 2828 // Handle members of anonymous structs and unions. If we got here, 2829 // and the reference is to a class member indirect field, then this 2830 // must be the subject of a pointer-to-member expression. 2831 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2832 if (!indirectField->isCXXClassMember()) 2833 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2834 indirectField); 2835 2836 { 2837 QualType type = VD->getType(); 2838 if (type.isNull()) 2839 return ExprError(); 2840 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2841 // C++ [except.spec]p17: 2842 // An exception-specification is considered to be needed when: 2843 // - in an expression, the function is the unique lookup result or 2844 // the selected member of a set of overloaded functions. 2845 ResolveExceptionSpec(Loc, FPT); 2846 type = VD->getType(); 2847 } 2848 ExprValueKind valueKind = VK_RValue; 2849 2850 switch (D->getKind()) { 2851 // Ignore all the non-ValueDecl kinds. 2852 #define ABSTRACT_DECL(kind) 2853 #define VALUE(type, base) 2854 #define DECL(type, base) \ 2855 case Decl::type: 2856 #include "clang/AST/DeclNodes.inc" 2857 llvm_unreachable("invalid value decl kind"); 2858 2859 // These shouldn't make it here. 2860 case Decl::ObjCAtDefsField: 2861 case Decl::ObjCIvar: 2862 llvm_unreachable("forming non-member reference to ivar?"); 2863 2864 // Enum constants are always r-values and never references. 2865 // Unresolved using declarations are dependent. 2866 case Decl::EnumConstant: 2867 case Decl::UnresolvedUsingValue: 2868 case Decl::OMPDeclareReduction: 2869 valueKind = VK_RValue; 2870 break; 2871 2872 // Fields and indirect fields that got here must be for 2873 // pointer-to-member expressions; we just call them l-values for 2874 // internal consistency, because this subexpression doesn't really 2875 // exist in the high-level semantics. 2876 case Decl::Field: 2877 case Decl::IndirectField: 2878 assert(getLangOpts().CPlusPlus && 2879 "building reference to field in C?"); 2880 2881 // These can't have reference type in well-formed programs, but 2882 // for internal consistency we do this anyway. 2883 type = type.getNonReferenceType(); 2884 valueKind = VK_LValue; 2885 break; 2886 2887 // Non-type template parameters are either l-values or r-values 2888 // depending on the type. 2889 case Decl::NonTypeTemplateParm: { 2890 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2891 type = reftype->getPointeeType(); 2892 valueKind = VK_LValue; // even if the parameter is an r-value reference 2893 break; 2894 } 2895 2896 // For non-references, we need to strip qualifiers just in case 2897 // the template parameter was declared as 'const int' or whatever. 2898 valueKind = VK_RValue; 2899 type = type.getUnqualifiedType(); 2900 break; 2901 } 2902 2903 case Decl::Var: 2904 case Decl::VarTemplateSpecialization: 2905 case Decl::VarTemplatePartialSpecialization: 2906 case Decl::Decomposition: 2907 case Decl::OMPCapturedExpr: 2908 // In C, "extern void blah;" is valid and is an r-value. 2909 if (!getLangOpts().CPlusPlus && 2910 !type.hasQualifiers() && 2911 type->isVoidType()) { 2912 valueKind = VK_RValue; 2913 break; 2914 } 2915 LLVM_FALLTHROUGH; 2916 2917 case Decl::ImplicitParam: 2918 case Decl::ParmVar: { 2919 // These are always l-values. 2920 valueKind = VK_LValue; 2921 type = type.getNonReferenceType(); 2922 2923 // FIXME: Does the addition of const really only apply in 2924 // potentially-evaluated contexts? Since the variable isn't actually 2925 // captured in an unevaluated context, it seems that the answer is no. 2926 if (!isUnevaluatedContext()) { 2927 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2928 if (!CapturedType.isNull()) 2929 type = CapturedType; 2930 } 2931 2932 break; 2933 } 2934 2935 case Decl::Binding: { 2936 // These are always lvalues. 2937 valueKind = VK_LValue; 2938 type = type.getNonReferenceType(); 2939 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2940 // decides how that's supposed to work. 2941 auto *BD = cast<BindingDecl>(VD); 2942 if (BD->getDeclContext()->isFunctionOrMethod() && 2943 BD->getDeclContext() != CurContext) 2944 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2945 break; 2946 } 2947 2948 case Decl::Function: { 2949 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2950 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2951 type = Context.BuiltinFnTy; 2952 valueKind = VK_RValue; 2953 break; 2954 } 2955 } 2956 2957 const FunctionType *fty = type->castAs<FunctionType>(); 2958 2959 // If we're referring to a function with an __unknown_anytype 2960 // result type, make the entire expression __unknown_anytype. 2961 if (fty->getReturnType() == Context.UnknownAnyTy) { 2962 type = Context.UnknownAnyTy; 2963 valueKind = VK_RValue; 2964 break; 2965 } 2966 2967 // Functions are l-values in C++. 2968 if (getLangOpts().CPlusPlus) { 2969 valueKind = VK_LValue; 2970 break; 2971 } 2972 2973 // C99 DR 316 says that, if a function type comes from a 2974 // function definition (without a prototype), that type is only 2975 // used for checking compatibility. Therefore, when referencing 2976 // the function, we pretend that we don't have the full function 2977 // type. 2978 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2979 isa<FunctionProtoType>(fty)) 2980 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2981 fty->getExtInfo()); 2982 2983 // Functions are r-values in C. 2984 valueKind = VK_RValue; 2985 break; 2986 } 2987 2988 case Decl::CXXDeductionGuide: 2989 llvm_unreachable("building reference to deduction guide"); 2990 2991 case Decl::MSProperty: 2992 valueKind = VK_LValue; 2993 break; 2994 2995 case Decl::CXXMethod: 2996 // If we're referring to a method with an __unknown_anytype 2997 // result type, make the entire expression __unknown_anytype. 2998 // This should only be possible with a type written directly. 2999 if (const FunctionProtoType *proto 3000 = dyn_cast<FunctionProtoType>(VD->getType())) 3001 if (proto->getReturnType() == Context.UnknownAnyTy) { 3002 type = Context.UnknownAnyTy; 3003 valueKind = VK_RValue; 3004 break; 3005 } 3006 3007 // C++ methods are l-values if static, r-values if non-static. 3008 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3009 valueKind = VK_LValue; 3010 break; 3011 } 3012 LLVM_FALLTHROUGH; 3013 3014 case Decl::CXXConversion: 3015 case Decl::CXXDestructor: 3016 case Decl::CXXConstructor: 3017 valueKind = VK_RValue; 3018 break; 3019 } 3020 3021 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3022 TemplateArgs); 3023 } 3024 } 3025 3026 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3027 SmallString<32> &Target) { 3028 Target.resize(CharByteWidth * (Source.size() + 1)); 3029 char *ResultPtr = &Target[0]; 3030 const llvm::UTF8 *ErrorPtr; 3031 bool success = 3032 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3033 (void)success; 3034 assert(success); 3035 Target.resize(ResultPtr - &Target[0]); 3036 } 3037 3038 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3039 PredefinedExpr::IdentKind IK) { 3040 // Pick the current block, lambda, captured statement or function. 3041 Decl *currentDecl = nullptr; 3042 if (const BlockScopeInfo *BSI = getCurBlock()) 3043 currentDecl = BSI->TheDecl; 3044 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3045 currentDecl = LSI->CallOperator; 3046 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3047 currentDecl = CSI->TheCapturedDecl; 3048 else 3049 currentDecl = getCurFunctionOrMethodDecl(); 3050 3051 if (!currentDecl) { 3052 Diag(Loc, diag::ext_predef_outside_function); 3053 currentDecl = Context.getTranslationUnitDecl(); 3054 } 3055 3056 QualType ResTy; 3057 StringLiteral *SL = nullptr; 3058 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3059 ResTy = Context.DependentTy; 3060 else { 3061 // Pre-defined identifiers are of type char[x], where x is the length of 3062 // the string. 3063 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3064 unsigned Length = Str.length(); 3065 3066 llvm::APInt LengthI(32, Length + 1); 3067 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3068 ResTy = 3069 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3070 SmallString<32> RawChars; 3071 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3072 Str, RawChars); 3073 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3074 /*IndexTypeQuals*/ 0); 3075 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3076 /*Pascal*/ false, ResTy, Loc); 3077 } else { 3078 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3079 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3080 /*IndexTypeQuals*/ 0); 3081 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3082 /*Pascal*/ false, ResTy, Loc); 3083 } 3084 } 3085 3086 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3087 } 3088 3089 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3090 PredefinedExpr::IdentKind IK; 3091 3092 switch (Kind) { 3093 default: llvm_unreachable("Unknown simple primary expr!"); 3094 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3095 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3096 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3097 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3098 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3099 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3100 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3101 } 3102 3103 return BuildPredefinedExpr(Loc, IK); 3104 } 3105 3106 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3107 SmallString<16> CharBuffer; 3108 bool Invalid = false; 3109 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3110 if (Invalid) 3111 return ExprError(); 3112 3113 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3114 PP, Tok.getKind()); 3115 if (Literal.hadError()) 3116 return ExprError(); 3117 3118 QualType Ty; 3119 if (Literal.isWide()) 3120 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3121 else if (Literal.isUTF8() && getLangOpts().Char8) 3122 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3123 else if (Literal.isUTF16()) 3124 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3125 else if (Literal.isUTF32()) 3126 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3127 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3128 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3129 else 3130 Ty = Context.CharTy; // 'x' -> char in C++ 3131 3132 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3133 if (Literal.isWide()) 3134 Kind = CharacterLiteral::Wide; 3135 else if (Literal.isUTF16()) 3136 Kind = CharacterLiteral::UTF16; 3137 else if (Literal.isUTF32()) 3138 Kind = CharacterLiteral::UTF32; 3139 else if (Literal.isUTF8()) 3140 Kind = CharacterLiteral::UTF8; 3141 3142 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3143 Tok.getLocation()); 3144 3145 if (Literal.getUDSuffix().empty()) 3146 return Lit; 3147 3148 // We're building a user-defined literal. 3149 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3150 SourceLocation UDSuffixLoc = 3151 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3152 3153 // Make sure we're allowed user-defined literals here. 3154 if (!UDLScope) 3155 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3156 3157 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3158 // operator "" X (ch) 3159 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3160 Lit, Tok.getLocation()); 3161 } 3162 3163 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3164 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3165 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3166 Context.IntTy, Loc); 3167 } 3168 3169 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3170 QualType Ty, SourceLocation Loc) { 3171 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3172 3173 using llvm::APFloat; 3174 APFloat Val(Format); 3175 3176 APFloat::opStatus result = Literal.GetFloatValue(Val); 3177 3178 // Overflow is always an error, but underflow is only an error if 3179 // we underflowed to zero (APFloat reports denormals as underflow). 3180 if ((result & APFloat::opOverflow) || 3181 ((result & APFloat::opUnderflow) && Val.isZero())) { 3182 unsigned diagnostic; 3183 SmallString<20> buffer; 3184 if (result & APFloat::opOverflow) { 3185 diagnostic = diag::warn_float_overflow; 3186 APFloat::getLargest(Format).toString(buffer); 3187 } else { 3188 diagnostic = diag::warn_float_underflow; 3189 APFloat::getSmallest(Format).toString(buffer); 3190 } 3191 3192 S.Diag(Loc, diagnostic) 3193 << Ty 3194 << StringRef(buffer.data(), buffer.size()); 3195 } 3196 3197 bool isExact = (result == APFloat::opOK); 3198 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3199 } 3200 3201 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3202 assert(E && "Invalid expression"); 3203 3204 if (E->isValueDependent()) 3205 return false; 3206 3207 QualType QT = E->getType(); 3208 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3209 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3210 return true; 3211 } 3212 3213 llvm::APSInt ValueAPS; 3214 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3215 3216 if (R.isInvalid()) 3217 return true; 3218 3219 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3220 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3221 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3222 << ValueAPS.toString(10) << ValueIsPositive; 3223 return true; 3224 } 3225 3226 return false; 3227 } 3228 3229 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3230 // Fast path for a single digit (which is quite common). A single digit 3231 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3232 if (Tok.getLength() == 1) { 3233 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3234 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3235 } 3236 3237 SmallString<128> SpellingBuffer; 3238 // NumericLiteralParser wants to overread by one character. Add padding to 3239 // the buffer in case the token is copied to the buffer. If getSpelling() 3240 // returns a StringRef to the memory buffer, it should have a null char at 3241 // the EOF, so it is also safe. 3242 SpellingBuffer.resize(Tok.getLength() + 1); 3243 3244 // Get the spelling of the token, which eliminates trigraphs, etc. 3245 bool Invalid = false; 3246 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3247 if (Invalid) 3248 return ExprError(); 3249 3250 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3251 if (Literal.hadError) 3252 return ExprError(); 3253 3254 if (Literal.hasUDSuffix()) { 3255 // We're building a user-defined literal. 3256 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3257 SourceLocation UDSuffixLoc = 3258 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3259 3260 // Make sure we're allowed user-defined literals here. 3261 if (!UDLScope) 3262 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3263 3264 QualType CookedTy; 3265 if (Literal.isFloatingLiteral()) { 3266 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3267 // long double, the literal is treated as a call of the form 3268 // operator "" X (f L) 3269 CookedTy = Context.LongDoubleTy; 3270 } else { 3271 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3272 // unsigned long long, the literal is treated as a call of the form 3273 // operator "" X (n ULL) 3274 CookedTy = Context.UnsignedLongLongTy; 3275 } 3276 3277 DeclarationName OpName = 3278 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3279 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3280 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3281 3282 SourceLocation TokLoc = Tok.getLocation(); 3283 3284 // Perform literal operator lookup to determine if we're building a raw 3285 // literal or a cooked one. 3286 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3287 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3288 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3289 /*AllowStringTemplate*/ false, 3290 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3291 case LOLR_ErrorNoDiagnostic: 3292 // Lookup failure for imaginary constants isn't fatal, there's still the 3293 // GNU extension producing _Complex types. 3294 break; 3295 case LOLR_Error: 3296 return ExprError(); 3297 case LOLR_Cooked: { 3298 Expr *Lit; 3299 if (Literal.isFloatingLiteral()) { 3300 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3301 } else { 3302 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3303 if (Literal.GetIntegerValue(ResultVal)) 3304 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3305 << /* Unsigned */ 1; 3306 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3307 Tok.getLocation()); 3308 } 3309 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3310 } 3311 3312 case LOLR_Raw: { 3313 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3314 // literal is treated as a call of the form 3315 // operator "" X ("n") 3316 unsigned Length = Literal.getUDSuffixOffset(); 3317 QualType StrTy = Context.getConstantArrayType( 3318 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3319 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3320 Expr *Lit = StringLiteral::Create( 3321 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3322 /*Pascal*/false, StrTy, &TokLoc, 1); 3323 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3324 } 3325 3326 case LOLR_Template: { 3327 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3328 // template), L is treated as a call fo the form 3329 // operator "" X <'c1', 'c2', ... 'ck'>() 3330 // where n is the source character sequence c1 c2 ... ck. 3331 TemplateArgumentListInfo ExplicitArgs; 3332 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3333 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3334 llvm::APSInt Value(CharBits, CharIsUnsigned); 3335 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3336 Value = TokSpelling[I]; 3337 TemplateArgument Arg(Context, Value, Context.CharTy); 3338 TemplateArgumentLocInfo ArgInfo; 3339 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3340 } 3341 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3342 &ExplicitArgs); 3343 } 3344 case LOLR_StringTemplate: 3345 llvm_unreachable("unexpected literal operator lookup result"); 3346 } 3347 } 3348 3349 Expr *Res; 3350 3351 if (Literal.isFixedPointLiteral()) { 3352 QualType Ty; 3353 3354 if (Literal.isAccum) { 3355 if (Literal.isHalf) { 3356 Ty = Context.ShortAccumTy; 3357 } else if (Literal.isLong) { 3358 Ty = Context.LongAccumTy; 3359 } else { 3360 Ty = Context.AccumTy; 3361 } 3362 } else if (Literal.isFract) { 3363 if (Literal.isHalf) { 3364 Ty = Context.ShortFractTy; 3365 } else if (Literal.isLong) { 3366 Ty = Context.LongFractTy; 3367 } else { 3368 Ty = Context.FractTy; 3369 } 3370 } 3371 3372 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3373 3374 bool isSigned = !Literal.isUnsigned; 3375 unsigned scale = Context.getFixedPointScale(Ty); 3376 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3377 3378 llvm::APInt Val(bit_width, 0, isSigned); 3379 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3380 bool ValIsZero = Val.isNullValue() && !Overflowed; 3381 3382 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3383 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3384 // Clause 6.4.4 - The value of a constant shall be in the range of 3385 // representable values for its type, with exception for constants of a 3386 // fract type with a value of exactly 1; such a constant shall denote 3387 // the maximal value for the type. 3388 --Val; 3389 else if (Val.ugt(MaxVal) || Overflowed) 3390 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3391 3392 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3393 Tok.getLocation(), scale); 3394 } else if (Literal.isFloatingLiteral()) { 3395 QualType Ty; 3396 if (Literal.isHalf){ 3397 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3398 Ty = Context.HalfTy; 3399 else { 3400 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3401 return ExprError(); 3402 } 3403 } else if (Literal.isFloat) 3404 Ty = Context.FloatTy; 3405 else if (Literal.isLong) 3406 Ty = Context.LongDoubleTy; 3407 else if (Literal.isFloat16) 3408 Ty = Context.Float16Ty; 3409 else if (Literal.isFloat128) 3410 Ty = Context.Float128Ty; 3411 else 3412 Ty = Context.DoubleTy; 3413 3414 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3415 3416 if (Ty == Context.DoubleTy) { 3417 if (getLangOpts().SinglePrecisionConstants) { 3418 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3419 if (BTy->getKind() != BuiltinType::Float) { 3420 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3421 } 3422 } else if (getLangOpts().OpenCL && 3423 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3424 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3425 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3426 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3427 } 3428 } 3429 } else if (!Literal.isIntegerLiteral()) { 3430 return ExprError(); 3431 } else { 3432 QualType Ty; 3433 3434 // 'long long' is a C99 or C++11 feature. 3435 if (!getLangOpts().C99 && Literal.isLongLong) { 3436 if (getLangOpts().CPlusPlus) 3437 Diag(Tok.getLocation(), 3438 getLangOpts().CPlusPlus11 ? 3439 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3440 else 3441 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3442 } 3443 3444 // Get the value in the widest-possible width. 3445 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3446 llvm::APInt ResultVal(MaxWidth, 0); 3447 3448 if (Literal.GetIntegerValue(ResultVal)) { 3449 // If this value didn't fit into uintmax_t, error and force to ull. 3450 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3451 << /* Unsigned */ 1; 3452 Ty = Context.UnsignedLongLongTy; 3453 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3454 "long long is not intmax_t?"); 3455 } else { 3456 // If this value fits into a ULL, try to figure out what else it fits into 3457 // according to the rules of C99 6.4.4.1p5. 3458 3459 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3460 // be an unsigned int. 3461 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3462 3463 // Check from smallest to largest, picking the smallest type we can. 3464 unsigned Width = 0; 3465 3466 // Microsoft specific integer suffixes are explicitly sized. 3467 if (Literal.MicrosoftInteger) { 3468 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3469 Width = 8; 3470 Ty = Context.CharTy; 3471 } else { 3472 Width = Literal.MicrosoftInteger; 3473 Ty = Context.getIntTypeForBitwidth(Width, 3474 /*Signed=*/!Literal.isUnsigned); 3475 } 3476 } 3477 3478 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3479 // Are int/unsigned possibilities? 3480 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3481 3482 // Does it fit in a unsigned int? 3483 if (ResultVal.isIntN(IntSize)) { 3484 // Does it fit in a signed int? 3485 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3486 Ty = Context.IntTy; 3487 else if (AllowUnsigned) 3488 Ty = Context.UnsignedIntTy; 3489 Width = IntSize; 3490 } 3491 } 3492 3493 // Are long/unsigned long possibilities? 3494 if (Ty.isNull() && !Literal.isLongLong) { 3495 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3496 3497 // Does it fit in a unsigned long? 3498 if (ResultVal.isIntN(LongSize)) { 3499 // Does it fit in a signed long? 3500 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3501 Ty = Context.LongTy; 3502 else if (AllowUnsigned) 3503 Ty = Context.UnsignedLongTy; 3504 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3505 // is compatible. 3506 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3507 const unsigned LongLongSize = 3508 Context.getTargetInfo().getLongLongWidth(); 3509 Diag(Tok.getLocation(), 3510 getLangOpts().CPlusPlus 3511 ? Literal.isLong 3512 ? diag::warn_old_implicitly_unsigned_long_cxx 3513 : /*C++98 UB*/ diag:: 3514 ext_old_implicitly_unsigned_long_cxx 3515 : diag::warn_old_implicitly_unsigned_long) 3516 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3517 : /*will be ill-formed*/ 1); 3518 Ty = Context.UnsignedLongTy; 3519 } 3520 Width = LongSize; 3521 } 3522 } 3523 3524 // Check long long if needed. 3525 if (Ty.isNull()) { 3526 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3527 3528 // Does it fit in a unsigned long long? 3529 if (ResultVal.isIntN(LongLongSize)) { 3530 // Does it fit in a signed long long? 3531 // To be compatible with MSVC, hex integer literals ending with the 3532 // LL or i64 suffix are always signed in Microsoft mode. 3533 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3534 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3535 Ty = Context.LongLongTy; 3536 else if (AllowUnsigned) 3537 Ty = Context.UnsignedLongLongTy; 3538 Width = LongLongSize; 3539 } 3540 } 3541 3542 // If we still couldn't decide a type, we probably have something that 3543 // does not fit in a signed long long, but has no U suffix. 3544 if (Ty.isNull()) { 3545 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3546 Ty = Context.UnsignedLongLongTy; 3547 Width = Context.getTargetInfo().getLongLongWidth(); 3548 } 3549 3550 if (ResultVal.getBitWidth() != Width) 3551 ResultVal = ResultVal.trunc(Width); 3552 } 3553 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3554 } 3555 3556 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3557 if (Literal.isImaginary) { 3558 Res = new (Context) ImaginaryLiteral(Res, 3559 Context.getComplexType(Res->getType())); 3560 3561 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3562 } 3563 return Res; 3564 } 3565 3566 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3567 assert(E && "ActOnParenExpr() missing expr"); 3568 return new (Context) ParenExpr(L, R, E); 3569 } 3570 3571 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3572 SourceLocation Loc, 3573 SourceRange ArgRange) { 3574 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3575 // scalar or vector data type argument..." 3576 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3577 // type (C99 6.2.5p18) or void. 3578 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3579 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3580 << T << ArgRange; 3581 return true; 3582 } 3583 3584 assert((T->isVoidType() || !T->isIncompleteType()) && 3585 "Scalar types should always be complete"); 3586 return false; 3587 } 3588 3589 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3590 SourceLocation Loc, 3591 SourceRange ArgRange, 3592 UnaryExprOrTypeTrait TraitKind) { 3593 // Invalid types must be hard errors for SFINAE in C++. 3594 if (S.LangOpts.CPlusPlus) 3595 return true; 3596 3597 // C99 6.5.3.4p1: 3598 if (T->isFunctionType() && 3599 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3600 TraitKind == UETT_PreferredAlignOf)) { 3601 // sizeof(function)/alignof(function) is allowed as an extension. 3602 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3603 << TraitKind << ArgRange; 3604 return false; 3605 } 3606 3607 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3608 // this is an error (OpenCL v1.1 s6.3.k) 3609 if (T->isVoidType()) { 3610 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3611 : diag::ext_sizeof_alignof_void_type; 3612 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3613 return false; 3614 } 3615 3616 return true; 3617 } 3618 3619 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3620 SourceLocation Loc, 3621 SourceRange ArgRange, 3622 UnaryExprOrTypeTrait TraitKind) { 3623 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3624 // runtime doesn't allow it. 3625 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3626 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3627 << T << (TraitKind == UETT_SizeOf) 3628 << ArgRange; 3629 return true; 3630 } 3631 3632 return false; 3633 } 3634 3635 /// Check whether E is a pointer from a decayed array type (the decayed 3636 /// pointer type is equal to T) and emit a warning if it is. 3637 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3638 Expr *E) { 3639 // Don't warn if the operation changed the type. 3640 if (T != E->getType()) 3641 return; 3642 3643 // Now look for array decays. 3644 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3645 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3646 return; 3647 3648 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3649 << ICE->getType() 3650 << ICE->getSubExpr()->getType(); 3651 } 3652 3653 /// Check the constraints on expression operands to unary type expression 3654 /// and type traits. 3655 /// 3656 /// Completes any types necessary and validates the constraints on the operand 3657 /// expression. The logic mostly mirrors the type-based overload, but may modify 3658 /// the expression as it completes the type for that expression through template 3659 /// instantiation, etc. 3660 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3661 UnaryExprOrTypeTrait ExprKind) { 3662 QualType ExprTy = E->getType(); 3663 assert(!ExprTy->isReferenceType()); 3664 3665 if (ExprKind == UETT_VecStep) 3666 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3667 E->getSourceRange()); 3668 3669 // Whitelist some types as extensions 3670 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3671 E->getSourceRange(), ExprKind)) 3672 return false; 3673 3674 // 'alignof' applied to an expression only requires the base element type of 3675 // the expression to be complete. 'sizeof' requires the expression's type to 3676 // be complete (and will attempt to complete it if it's an array of unknown 3677 // bound). 3678 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3679 if (RequireCompleteType(E->getExprLoc(), 3680 Context.getBaseElementType(E->getType()), 3681 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3682 E->getSourceRange())) 3683 return true; 3684 } else { 3685 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3686 ExprKind, E->getSourceRange())) 3687 return true; 3688 } 3689 3690 // Completing the expression's type may have changed it. 3691 ExprTy = E->getType(); 3692 assert(!ExprTy->isReferenceType()); 3693 3694 if (ExprTy->isFunctionType()) { 3695 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3696 << ExprKind << E->getSourceRange(); 3697 return true; 3698 } 3699 3700 // The operand for sizeof and alignof is in an unevaluated expression context, 3701 // so side effects could result in unintended consequences. 3702 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3703 ExprKind == UETT_PreferredAlignOf) && 3704 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3705 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3706 3707 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3708 E->getSourceRange(), ExprKind)) 3709 return true; 3710 3711 if (ExprKind == UETT_SizeOf) { 3712 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3713 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3714 QualType OType = PVD->getOriginalType(); 3715 QualType Type = PVD->getType(); 3716 if (Type->isPointerType() && OType->isArrayType()) { 3717 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3718 << Type << OType; 3719 Diag(PVD->getLocation(), diag::note_declared_at); 3720 } 3721 } 3722 } 3723 3724 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3725 // decays into a pointer and returns an unintended result. This is most 3726 // likely a typo for "sizeof(array) op x". 3727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3728 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3729 BO->getLHS()); 3730 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3731 BO->getRHS()); 3732 } 3733 } 3734 3735 return false; 3736 } 3737 3738 /// Check the constraints on operands to unary expression and type 3739 /// traits. 3740 /// 3741 /// This will complete any types necessary, and validate the various constraints 3742 /// on those operands. 3743 /// 3744 /// The UsualUnaryConversions() function is *not* called by this routine. 3745 /// C99 6.3.2.1p[2-4] all state: 3746 /// Except when it is the operand of the sizeof operator ... 3747 /// 3748 /// C++ [expr.sizeof]p4 3749 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3750 /// standard conversions are not applied to the operand of sizeof. 3751 /// 3752 /// This policy is followed for all of the unary trait expressions. 3753 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3754 SourceLocation OpLoc, 3755 SourceRange ExprRange, 3756 UnaryExprOrTypeTrait ExprKind) { 3757 if (ExprType->isDependentType()) 3758 return false; 3759 3760 // C++ [expr.sizeof]p2: 3761 // When applied to a reference or a reference type, the result 3762 // is the size of the referenced type. 3763 // C++11 [expr.alignof]p3: 3764 // When alignof is applied to a reference type, the result 3765 // shall be the alignment of the referenced type. 3766 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3767 ExprType = Ref->getPointeeType(); 3768 3769 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3770 // When alignof or _Alignof is applied to an array type, the result 3771 // is the alignment of the element type. 3772 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3773 ExprKind == UETT_OpenMPRequiredSimdAlign) 3774 ExprType = Context.getBaseElementType(ExprType); 3775 3776 if (ExprKind == UETT_VecStep) 3777 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3778 3779 // Whitelist some types as extensions 3780 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3781 ExprKind)) 3782 return false; 3783 3784 if (RequireCompleteType(OpLoc, ExprType, 3785 diag::err_sizeof_alignof_incomplete_type, 3786 ExprKind, ExprRange)) 3787 return true; 3788 3789 if (ExprType->isFunctionType()) { 3790 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3791 << ExprKind << ExprRange; 3792 return true; 3793 } 3794 3795 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3796 ExprKind)) 3797 return true; 3798 3799 return false; 3800 } 3801 3802 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3803 E = E->IgnoreParens(); 3804 3805 // Cannot know anything else if the expression is dependent. 3806 if (E->isTypeDependent()) 3807 return false; 3808 3809 if (E->getObjectKind() == OK_BitField) { 3810 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3811 << 1 << E->getSourceRange(); 3812 return true; 3813 } 3814 3815 ValueDecl *D = nullptr; 3816 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3817 D = DRE->getDecl(); 3818 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3819 D = ME->getMemberDecl(); 3820 } 3821 3822 // If it's a field, require the containing struct to have a 3823 // complete definition so that we can compute the layout. 3824 // 3825 // This can happen in C++11 onwards, either by naming the member 3826 // in a way that is not transformed into a member access expression 3827 // (in an unevaluated operand, for instance), or by naming the member 3828 // in a trailing-return-type. 3829 // 3830 // For the record, since __alignof__ on expressions is a GCC 3831 // extension, GCC seems to permit this but always gives the 3832 // nonsensical answer 0. 3833 // 3834 // We don't really need the layout here --- we could instead just 3835 // directly check for all the appropriate alignment-lowing 3836 // attributes --- but that would require duplicating a lot of 3837 // logic that just isn't worth duplicating for such a marginal 3838 // use-case. 3839 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3840 // Fast path this check, since we at least know the record has a 3841 // definition if we can find a member of it. 3842 if (!FD->getParent()->isCompleteDefinition()) { 3843 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3844 << E->getSourceRange(); 3845 return true; 3846 } 3847 3848 // Otherwise, if it's a field, and the field doesn't have 3849 // reference type, then it must have a complete type (or be a 3850 // flexible array member, which we explicitly want to 3851 // white-list anyway), which makes the following checks trivial. 3852 if (!FD->getType()->isReferenceType()) 3853 return false; 3854 } 3855 3856 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3857 } 3858 3859 bool Sema::CheckVecStepExpr(Expr *E) { 3860 E = E->IgnoreParens(); 3861 3862 // Cannot know anything else if the expression is dependent. 3863 if (E->isTypeDependent()) 3864 return false; 3865 3866 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3867 } 3868 3869 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3870 CapturingScopeInfo *CSI) { 3871 assert(T->isVariablyModifiedType()); 3872 assert(CSI != nullptr); 3873 3874 // We're going to walk down into the type and look for VLA expressions. 3875 do { 3876 const Type *Ty = T.getTypePtr(); 3877 switch (Ty->getTypeClass()) { 3878 #define TYPE(Class, Base) 3879 #define ABSTRACT_TYPE(Class, Base) 3880 #define NON_CANONICAL_TYPE(Class, Base) 3881 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3882 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3883 #include "clang/AST/TypeNodes.def" 3884 T = QualType(); 3885 break; 3886 // These types are never variably-modified. 3887 case Type::Builtin: 3888 case Type::Complex: 3889 case Type::Vector: 3890 case Type::ExtVector: 3891 case Type::Record: 3892 case Type::Enum: 3893 case Type::Elaborated: 3894 case Type::TemplateSpecialization: 3895 case Type::ObjCObject: 3896 case Type::ObjCInterface: 3897 case Type::ObjCObjectPointer: 3898 case Type::ObjCTypeParam: 3899 case Type::Pipe: 3900 llvm_unreachable("type class is never variably-modified!"); 3901 case Type::Adjusted: 3902 T = cast<AdjustedType>(Ty)->getOriginalType(); 3903 break; 3904 case Type::Decayed: 3905 T = cast<DecayedType>(Ty)->getPointeeType(); 3906 break; 3907 case Type::Pointer: 3908 T = cast<PointerType>(Ty)->getPointeeType(); 3909 break; 3910 case Type::BlockPointer: 3911 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3912 break; 3913 case Type::LValueReference: 3914 case Type::RValueReference: 3915 T = cast<ReferenceType>(Ty)->getPointeeType(); 3916 break; 3917 case Type::MemberPointer: 3918 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3919 break; 3920 case Type::ConstantArray: 3921 case Type::IncompleteArray: 3922 // Losing element qualification here is fine. 3923 T = cast<ArrayType>(Ty)->getElementType(); 3924 break; 3925 case Type::VariableArray: { 3926 // Losing element qualification here is fine. 3927 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3928 3929 // Unknown size indication requires no size computation. 3930 // Otherwise, evaluate and record it. 3931 if (auto Size = VAT->getSizeExpr()) { 3932 if (!CSI->isVLATypeCaptured(VAT)) { 3933 RecordDecl *CapRecord = nullptr; 3934 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3935 CapRecord = LSI->Lambda; 3936 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3937 CapRecord = CRSI->TheRecordDecl; 3938 } 3939 if (CapRecord) { 3940 auto ExprLoc = Size->getExprLoc(); 3941 auto SizeType = Context.getSizeType(); 3942 // Build the non-static data member. 3943 auto Field = 3944 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3945 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3946 /*BW*/ nullptr, /*Mutable*/ false, 3947 /*InitStyle*/ ICIS_NoInit); 3948 Field->setImplicit(true); 3949 Field->setAccess(AS_private); 3950 Field->setCapturedVLAType(VAT); 3951 CapRecord->addDecl(Field); 3952 3953 CSI->addVLATypeCapture(ExprLoc, SizeType); 3954 } 3955 } 3956 } 3957 T = VAT->getElementType(); 3958 break; 3959 } 3960 case Type::FunctionProto: 3961 case Type::FunctionNoProto: 3962 T = cast<FunctionType>(Ty)->getReturnType(); 3963 break; 3964 case Type::Paren: 3965 case Type::TypeOf: 3966 case Type::UnaryTransform: 3967 case Type::Attributed: 3968 case Type::SubstTemplateTypeParm: 3969 case Type::PackExpansion: 3970 // Keep walking after single level desugaring. 3971 T = T.getSingleStepDesugaredType(Context); 3972 break; 3973 case Type::Typedef: 3974 T = cast<TypedefType>(Ty)->desugar(); 3975 break; 3976 case Type::Decltype: 3977 T = cast<DecltypeType>(Ty)->desugar(); 3978 break; 3979 case Type::Auto: 3980 case Type::DeducedTemplateSpecialization: 3981 T = cast<DeducedType>(Ty)->getDeducedType(); 3982 break; 3983 case Type::TypeOfExpr: 3984 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3985 break; 3986 case Type::Atomic: 3987 T = cast<AtomicType>(Ty)->getValueType(); 3988 break; 3989 } 3990 } while (!T.isNull() && T->isVariablyModifiedType()); 3991 } 3992 3993 /// Build a sizeof or alignof expression given a type operand. 3994 ExprResult 3995 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3996 SourceLocation OpLoc, 3997 UnaryExprOrTypeTrait ExprKind, 3998 SourceRange R) { 3999 if (!TInfo) 4000 return ExprError(); 4001 4002 QualType T = TInfo->getType(); 4003 4004 if (!T->isDependentType() && 4005 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4006 return ExprError(); 4007 4008 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4009 if (auto *TT = T->getAs<TypedefType>()) { 4010 for (auto I = FunctionScopes.rbegin(), 4011 E = std::prev(FunctionScopes.rend()); 4012 I != E; ++I) { 4013 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4014 if (CSI == nullptr) 4015 break; 4016 DeclContext *DC = nullptr; 4017 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4018 DC = LSI->CallOperator; 4019 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4020 DC = CRSI->TheCapturedDecl; 4021 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4022 DC = BSI->TheDecl; 4023 if (DC) { 4024 if (DC->containsDecl(TT->getDecl())) 4025 break; 4026 captureVariablyModifiedType(Context, T, CSI); 4027 } 4028 } 4029 } 4030 } 4031 4032 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4033 return new (Context) UnaryExprOrTypeTraitExpr( 4034 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4035 } 4036 4037 /// Build a sizeof or alignof expression given an expression 4038 /// operand. 4039 ExprResult 4040 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4041 UnaryExprOrTypeTrait ExprKind) { 4042 ExprResult PE = CheckPlaceholderExpr(E); 4043 if (PE.isInvalid()) 4044 return ExprError(); 4045 4046 E = PE.get(); 4047 4048 // Verify that the operand is valid. 4049 bool isInvalid = false; 4050 if (E->isTypeDependent()) { 4051 // Delay type-checking for type-dependent expressions. 4052 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4053 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4054 } else if (ExprKind == UETT_VecStep) { 4055 isInvalid = CheckVecStepExpr(E); 4056 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4057 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4058 isInvalid = true; 4059 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4060 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4061 isInvalid = true; 4062 } else { 4063 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4064 } 4065 4066 if (isInvalid) 4067 return ExprError(); 4068 4069 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4070 PE = TransformToPotentiallyEvaluated(E); 4071 if (PE.isInvalid()) return ExprError(); 4072 E = PE.get(); 4073 } 4074 4075 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4076 return new (Context) UnaryExprOrTypeTraitExpr( 4077 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4078 } 4079 4080 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4081 /// expr and the same for @c alignof and @c __alignof 4082 /// Note that the ArgRange is invalid if isType is false. 4083 ExprResult 4084 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4085 UnaryExprOrTypeTrait ExprKind, bool IsType, 4086 void *TyOrEx, SourceRange ArgRange) { 4087 // If error parsing type, ignore. 4088 if (!TyOrEx) return ExprError(); 4089 4090 if (IsType) { 4091 TypeSourceInfo *TInfo; 4092 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4093 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4094 } 4095 4096 Expr *ArgEx = (Expr *)TyOrEx; 4097 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4098 return Result; 4099 } 4100 4101 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4102 bool IsReal) { 4103 if (V.get()->isTypeDependent()) 4104 return S.Context.DependentTy; 4105 4106 // _Real and _Imag are only l-values for normal l-values. 4107 if (V.get()->getObjectKind() != OK_Ordinary) { 4108 V = S.DefaultLvalueConversion(V.get()); 4109 if (V.isInvalid()) 4110 return QualType(); 4111 } 4112 4113 // These operators return the element type of a complex type. 4114 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4115 return CT->getElementType(); 4116 4117 // Otherwise they pass through real integer and floating point types here. 4118 if (V.get()->getType()->isArithmeticType()) 4119 return V.get()->getType(); 4120 4121 // Test for placeholders. 4122 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4123 if (PR.isInvalid()) return QualType(); 4124 if (PR.get() != V.get()) { 4125 V = PR; 4126 return CheckRealImagOperand(S, V, Loc, IsReal); 4127 } 4128 4129 // Reject anything else. 4130 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4131 << (IsReal ? "__real" : "__imag"); 4132 return QualType(); 4133 } 4134 4135 4136 4137 ExprResult 4138 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4139 tok::TokenKind Kind, Expr *Input) { 4140 UnaryOperatorKind Opc; 4141 switch (Kind) { 4142 default: llvm_unreachable("Unknown unary op!"); 4143 case tok::plusplus: Opc = UO_PostInc; break; 4144 case tok::minusminus: Opc = UO_PostDec; break; 4145 } 4146 4147 // Since this might is a postfix expression, get rid of ParenListExprs. 4148 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4149 if (Result.isInvalid()) return ExprError(); 4150 Input = Result.get(); 4151 4152 return BuildUnaryOp(S, OpLoc, Opc, Input); 4153 } 4154 4155 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4156 /// 4157 /// \return true on error 4158 static bool checkArithmeticOnObjCPointer(Sema &S, 4159 SourceLocation opLoc, 4160 Expr *op) { 4161 assert(op->getType()->isObjCObjectPointerType()); 4162 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4163 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4164 return false; 4165 4166 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4167 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4168 << op->getSourceRange(); 4169 return true; 4170 } 4171 4172 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4173 auto *BaseNoParens = Base->IgnoreParens(); 4174 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4175 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4176 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4177 } 4178 4179 ExprResult 4180 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4181 Expr *idx, SourceLocation rbLoc) { 4182 if (base && !base->getType().isNull() && 4183 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4184 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4185 /*Length=*/nullptr, rbLoc); 4186 4187 // Since this might be a postfix expression, get rid of ParenListExprs. 4188 if (isa<ParenListExpr>(base)) { 4189 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4190 if (result.isInvalid()) return ExprError(); 4191 base = result.get(); 4192 } 4193 4194 // Handle any non-overload placeholder types in the base and index 4195 // expressions. We can't handle overloads here because the other 4196 // operand might be an overloadable type, in which case the overload 4197 // resolution for the operator overload should get the first crack 4198 // at the overload. 4199 bool IsMSPropertySubscript = false; 4200 if (base->getType()->isNonOverloadPlaceholderType()) { 4201 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4202 if (!IsMSPropertySubscript) { 4203 ExprResult result = CheckPlaceholderExpr(base); 4204 if (result.isInvalid()) 4205 return ExprError(); 4206 base = result.get(); 4207 } 4208 } 4209 if (idx->getType()->isNonOverloadPlaceholderType()) { 4210 ExprResult result = CheckPlaceholderExpr(idx); 4211 if (result.isInvalid()) return ExprError(); 4212 idx = result.get(); 4213 } 4214 4215 // Build an unanalyzed expression if either operand is type-dependent. 4216 if (getLangOpts().CPlusPlus && 4217 (base->isTypeDependent() || idx->isTypeDependent())) { 4218 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4219 VK_LValue, OK_Ordinary, rbLoc); 4220 } 4221 4222 // MSDN, property (C++) 4223 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4224 // This attribute can also be used in the declaration of an empty array in a 4225 // class or structure definition. For example: 4226 // __declspec(property(get=GetX, put=PutX)) int x[]; 4227 // The above statement indicates that x[] can be used with one or more array 4228 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4229 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4230 if (IsMSPropertySubscript) { 4231 // Build MS property subscript expression if base is MS property reference 4232 // or MS property subscript. 4233 return new (Context) MSPropertySubscriptExpr( 4234 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4235 } 4236 4237 // Use C++ overloaded-operator rules if either operand has record 4238 // type. The spec says to do this if either type is *overloadable*, 4239 // but enum types can't declare subscript operators or conversion 4240 // operators, so there's nothing interesting for overload resolution 4241 // to do if there aren't any record types involved. 4242 // 4243 // ObjC pointers have their own subscripting logic that is not tied 4244 // to overload resolution and so should not take this path. 4245 if (getLangOpts().CPlusPlus && 4246 (base->getType()->isRecordType() || 4247 (!base->getType()->isObjCObjectPointerType() && 4248 idx->getType()->isRecordType()))) { 4249 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4250 } 4251 4252 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4253 } 4254 4255 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4256 Expr *LowerBound, 4257 SourceLocation ColonLoc, Expr *Length, 4258 SourceLocation RBLoc) { 4259 if (Base->getType()->isPlaceholderType() && 4260 !Base->getType()->isSpecificPlaceholderType( 4261 BuiltinType::OMPArraySection)) { 4262 ExprResult Result = CheckPlaceholderExpr(Base); 4263 if (Result.isInvalid()) 4264 return ExprError(); 4265 Base = Result.get(); 4266 } 4267 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4268 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4269 if (Result.isInvalid()) 4270 return ExprError(); 4271 Result = DefaultLvalueConversion(Result.get()); 4272 if (Result.isInvalid()) 4273 return ExprError(); 4274 LowerBound = Result.get(); 4275 } 4276 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4277 ExprResult Result = CheckPlaceholderExpr(Length); 4278 if (Result.isInvalid()) 4279 return ExprError(); 4280 Result = DefaultLvalueConversion(Result.get()); 4281 if (Result.isInvalid()) 4282 return ExprError(); 4283 Length = Result.get(); 4284 } 4285 4286 // Build an unanalyzed expression if either operand is type-dependent. 4287 if (Base->isTypeDependent() || 4288 (LowerBound && 4289 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4290 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4291 return new (Context) 4292 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4293 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4294 } 4295 4296 // Perform default conversions. 4297 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4298 QualType ResultTy; 4299 if (OriginalTy->isAnyPointerType()) { 4300 ResultTy = OriginalTy->getPointeeType(); 4301 } else if (OriginalTy->isArrayType()) { 4302 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4303 } else { 4304 return ExprError( 4305 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4306 << Base->getSourceRange()); 4307 } 4308 // C99 6.5.2.1p1 4309 if (LowerBound) { 4310 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4311 LowerBound); 4312 if (Res.isInvalid()) 4313 return ExprError(Diag(LowerBound->getExprLoc(), 4314 diag::err_omp_typecheck_section_not_integer) 4315 << 0 << LowerBound->getSourceRange()); 4316 LowerBound = Res.get(); 4317 4318 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4319 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4320 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4321 << 0 << LowerBound->getSourceRange(); 4322 } 4323 if (Length) { 4324 auto Res = 4325 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4326 if (Res.isInvalid()) 4327 return ExprError(Diag(Length->getExprLoc(), 4328 diag::err_omp_typecheck_section_not_integer) 4329 << 1 << Length->getSourceRange()); 4330 Length = Res.get(); 4331 4332 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4333 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4334 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4335 << 1 << Length->getSourceRange(); 4336 } 4337 4338 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4339 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4340 // type. Note that functions are not objects, and that (in C99 parlance) 4341 // incomplete types are not object types. 4342 if (ResultTy->isFunctionType()) { 4343 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4344 << ResultTy << Base->getSourceRange(); 4345 return ExprError(); 4346 } 4347 4348 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4349 diag::err_omp_section_incomplete_type, Base)) 4350 return ExprError(); 4351 4352 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4353 llvm::APSInt LowerBoundValue; 4354 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4355 // OpenMP 4.5, [2.4 Array Sections] 4356 // The array section must be a subset of the original array. 4357 if (LowerBoundValue.isNegative()) { 4358 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4359 << LowerBound->getSourceRange(); 4360 return ExprError(); 4361 } 4362 } 4363 } 4364 4365 if (Length) { 4366 llvm::APSInt LengthValue; 4367 if (Length->EvaluateAsInt(LengthValue, Context)) { 4368 // OpenMP 4.5, [2.4 Array Sections] 4369 // The length must evaluate to non-negative integers. 4370 if (LengthValue.isNegative()) { 4371 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4372 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4373 << Length->getSourceRange(); 4374 return ExprError(); 4375 } 4376 } 4377 } else if (ColonLoc.isValid() && 4378 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4379 !OriginalTy->isVariableArrayType()))) { 4380 // OpenMP 4.5, [2.4 Array Sections] 4381 // When the size of the array dimension is not known, the length must be 4382 // specified explicitly. 4383 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4384 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4385 return ExprError(); 4386 } 4387 4388 if (!Base->getType()->isSpecificPlaceholderType( 4389 BuiltinType::OMPArraySection)) { 4390 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4391 if (Result.isInvalid()) 4392 return ExprError(); 4393 Base = Result.get(); 4394 } 4395 return new (Context) 4396 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4397 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4398 } 4399 4400 ExprResult 4401 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4402 Expr *Idx, SourceLocation RLoc) { 4403 Expr *LHSExp = Base; 4404 Expr *RHSExp = Idx; 4405 4406 ExprValueKind VK = VK_LValue; 4407 ExprObjectKind OK = OK_Ordinary; 4408 4409 // Per C++ core issue 1213, the result is an xvalue if either operand is 4410 // a non-lvalue array, and an lvalue otherwise. 4411 if (getLangOpts().CPlusPlus11) { 4412 for (auto *Op : {LHSExp, RHSExp}) { 4413 Op = Op->IgnoreImplicit(); 4414 if (Op->getType()->isArrayType() && !Op->isLValue()) 4415 VK = VK_XValue; 4416 } 4417 } 4418 4419 // Perform default conversions. 4420 if (!LHSExp->getType()->getAs<VectorType>()) { 4421 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4422 if (Result.isInvalid()) 4423 return ExprError(); 4424 LHSExp = Result.get(); 4425 } 4426 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4427 if (Result.isInvalid()) 4428 return ExprError(); 4429 RHSExp = Result.get(); 4430 4431 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4432 4433 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4434 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4435 // in the subscript position. As a result, we need to derive the array base 4436 // and index from the expression types. 4437 Expr *BaseExpr, *IndexExpr; 4438 QualType ResultType; 4439 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4440 BaseExpr = LHSExp; 4441 IndexExpr = RHSExp; 4442 ResultType = Context.DependentTy; 4443 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4444 BaseExpr = LHSExp; 4445 IndexExpr = RHSExp; 4446 ResultType = PTy->getPointeeType(); 4447 } else if (const ObjCObjectPointerType *PTy = 4448 LHSTy->getAs<ObjCObjectPointerType>()) { 4449 BaseExpr = LHSExp; 4450 IndexExpr = RHSExp; 4451 4452 // Use custom logic if this should be the pseudo-object subscript 4453 // expression. 4454 if (!LangOpts.isSubscriptPointerArithmetic()) 4455 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4456 nullptr); 4457 4458 ResultType = PTy->getPointeeType(); 4459 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4460 // Handle the uncommon case of "123[Ptr]". 4461 BaseExpr = RHSExp; 4462 IndexExpr = LHSExp; 4463 ResultType = PTy->getPointeeType(); 4464 } else if (const ObjCObjectPointerType *PTy = 4465 RHSTy->getAs<ObjCObjectPointerType>()) { 4466 // Handle the uncommon case of "123[Ptr]". 4467 BaseExpr = RHSExp; 4468 IndexExpr = LHSExp; 4469 ResultType = PTy->getPointeeType(); 4470 if (!LangOpts.isSubscriptPointerArithmetic()) { 4471 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4472 << ResultType << BaseExpr->getSourceRange(); 4473 return ExprError(); 4474 } 4475 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4476 BaseExpr = LHSExp; // vectors: V[123] 4477 IndexExpr = RHSExp; 4478 // We apply C++ DR1213 to vector subscripting too. 4479 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4480 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4481 if (Materialized.isInvalid()) 4482 return ExprError(); 4483 LHSExp = Materialized.get(); 4484 } 4485 VK = LHSExp->getValueKind(); 4486 if (VK != VK_RValue) 4487 OK = OK_VectorComponent; 4488 4489 ResultType = VTy->getElementType(); 4490 QualType BaseType = BaseExpr->getType(); 4491 Qualifiers BaseQuals = BaseType.getQualifiers(); 4492 Qualifiers MemberQuals = ResultType.getQualifiers(); 4493 Qualifiers Combined = BaseQuals + MemberQuals; 4494 if (Combined != MemberQuals) 4495 ResultType = Context.getQualifiedType(ResultType, Combined); 4496 } else if (LHSTy->isArrayType()) { 4497 // If we see an array that wasn't promoted by 4498 // DefaultFunctionArrayLvalueConversion, it must be an array that 4499 // wasn't promoted because of the C90 rule that doesn't 4500 // allow promoting non-lvalue arrays. Warn, then 4501 // force the promotion here. 4502 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4503 << LHSExp->getSourceRange(); 4504 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4505 CK_ArrayToPointerDecay).get(); 4506 LHSTy = LHSExp->getType(); 4507 4508 BaseExpr = LHSExp; 4509 IndexExpr = RHSExp; 4510 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4511 } else if (RHSTy->isArrayType()) { 4512 // Same as previous, except for 123[f().a] case 4513 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4514 << RHSExp->getSourceRange(); 4515 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4516 CK_ArrayToPointerDecay).get(); 4517 RHSTy = RHSExp->getType(); 4518 4519 BaseExpr = RHSExp; 4520 IndexExpr = LHSExp; 4521 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4522 } else { 4523 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4524 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4525 } 4526 // C99 6.5.2.1p1 4527 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4528 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4529 << IndexExpr->getSourceRange()); 4530 4531 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4532 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4533 && !IndexExpr->isTypeDependent()) 4534 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4535 4536 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4537 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4538 // type. Note that Functions are not objects, and that (in C99 parlance) 4539 // incomplete types are not object types. 4540 if (ResultType->isFunctionType()) { 4541 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4542 << ResultType << BaseExpr->getSourceRange(); 4543 return ExprError(); 4544 } 4545 4546 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4547 // GNU extension: subscripting on pointer to void 4548 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4549 << BaseExpr->getSourceRange(); 4550 4551 // C forbids expressions of unqualified void type from being l-values. 4552 // See IsCForbiddenLValueType. 4553 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4554 } else if (!ResultType->isDependentType() && 4555 RequireCompleteType(LLoc, ResultType, 4556 diag::err_subscript_incomplete_type, BaseExpr)) 4557 return ExprError(); 4558 4559 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4560 !ResultType.isCForbiddenLValueType()); 4561 4562 return new (Context) 4563 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4564 } 4565 4566 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4567 ParmVarDecl *Param) { 4568 if (Param->hasUnparsedDefaultArg()) { 4569 Diag(CallLoc, 4570 diag::err_use_of_default_argument_to_function_declared_later) << 4571 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4572 Diag(UnparsedDefaultArgLocs[Param], 4573 diag::note_default_argument_declared_here); 4574 return true; 4575 } 4576 4577 if (Param->hasUninstantiatedDefaultArg()) { 4578 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4579 4580 EnterExpressionEvaluationContext EvalContext( 4581 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4582 4583 // Instantiate the expression. 4584 // 4585 // FIXME: Pass in a correct Pattern argument, otherwise 4586 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4587 // 4588 // template<typename T> 4589 // struct A { 4590 // static int FooImpl(); 4591 // 4592 // template<typename Tp> 4593 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4594 // // template argument list [[T], [Tp]], should be [[Tp]]. 4595 // friend A<Tp> Foo(int a); 4596 // }; 4597 // 4598 // template<typename T> 4599 // A<T> Foo(int a = A<T>::FooImpl()); 4600 MultiLevelTemplateArgumentList MutiLevelArgList 4601 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4602 4603 InstantiatingTemplate Inst(*this, CallLoc, Param, 4604 MutiLevelArgList.getInnermost()); 4605 if (Inst.isInvalid()) 4606 return true; 4607 if (Inst.isAlreadyInstantiating()) { 4608 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4609 Param->setInvalidDecl(); 4610 return true; 4611 } 4612 4613 ExprResult Result; 4614 { 4615 // C++ [dcl.fct.default]p5: 4616 // The names in the [default argument] expression are bound, and 4617 // the semantic constraints are checked, at the point where the 4618 // default argument expression appears. 4619 ContextRAII SavedContext(*this, FD); 4620 LocalInstantiationScope Local(*this); 4621 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4622 /*DirectInit*/false); 4623 } 4624 if (Result.isInvalid()) 4625 return true; 4626 4627 // Check the expression as an initializer for the parameter. 4628 InitializedEntity Entity 4629 = InitializedEntity::InitializeParameter(Context, Param); 4630 InitializationKind Kind = InitializationKind::CreateCopy( 4631 Param->getLocation(), 4632 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4633 Expr *ResultE = Result.getAs<Expr>(); 4634 4635 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4636 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4637 if (Result.isInvalid()) 4638 return true; 4639 4640 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4641 Param->getOuterLocStart()); 4642 if (Result.isInvalid()) 4643 return true; 4644 4645 // Remember the instantiated default argument. 4646 Param->setDefaultArg(Result.getAs<Expr>()); 4647 if (ASTMutationListener *L = getASTMutationListener()) { 4648 L->DefaultArgumentInstantiated(Param); 4649 } 4650 } 4651 4652 // If the default argument expression is not set yet, we are building it now. 4653 if (!Param->hasInit()) { 4654 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4655 Param->setInvalidDecl(); 4656 return true; 4657 } 4658 4659 // If the default expression creates temporaries, we need to 4660 // push them to the current stack of expression temporaries so they'll 4661 // be properly destroyed. 4662 // FIXME: We should really be rebuilding the default argument with new 4663 // bound temporaries; see the comment in PR5810. 4664 // We don't need to do that with block decls, though, because 4665 // blocks in default argument expression can never capture anything. 4666 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4667 // Set the "needs cleanups" bit regardless of whether there are 4668 // any explicit objects. 4669 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4670 4671 // Append all the objects to the cleanup list. Right now, this 4672 // should always be a no-op, because blocks in default argument 4673 // expressions should never be able to capture anything. 4674 assert(!Init->getNumObjects() && 4675 "default argument expression has capturing blocks?"); 4676 } 4677 4678 // We already type-checked the argument, so we know it works. 4679 // Just mark all of the declarations in this potentially-evaluated expression 4680 // as being "referenced". 4681 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4682 /*SkipLocalVariables=*/true); 4683 return false; 4684 } 4685 4686 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4687 FunctionDecl *FD, ParmVarDecl *Param) { 4688 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4689 return ExprError(); 4690 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4691 } 4692 4693 Sema::VariadicCallType 4694 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4695 Expr *Fn) { 4696 if (Proto && Proto->isVariadic()) { 4697 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4698 return VariadicConstructor; 4699 else if (Fn && Fn->getType()->isBlockPointerType()) 4700 return VariadicBlock; 4701 else if (FDecl) { 4702 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4703 if (Method->isInstance()) 4704 return VariadicMethod; 4705 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4706 return VariadicMethod; 4707 return VariadicFunction; 4708 } 4709 return VariadicDoesNotApply; 4710 } 4711 4712 namespace { 4713 class FunctionCallCCC : public FunctionCallFilterCCC { 4714 public: 4715 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4716 unsigned NumArgs, MemberExpr *ME) 4717 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4718 FunctionName(FuncName) {} 4719 4720 bool ValidateCandidate(const TypoCorrection &candidate) override { 4721 if (!candidate.getCorrectionSpecifier() || 4722 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4723 return false; 4724 } 4725 4726 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4727 } 4728 4729 private: 4730 const IdentifierInfo *const FunctionName; 4731 }; 4732 } 4733 4734 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4735 FunctionDecl *FDecl, 4736 ArrayRef<Expr *> Args) { 4737 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4738 DeclarationName FuncName = FDecl->getDeclName(); 4739 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4740 4741 if (TypoCorrection Corrected = S.CorrectTypo( 4742 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4743 S.getScopeForContext(S.CurContext), nullptr, 4744 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4745 Args.size(), ME), 4746 Sema::CTK_ErrorRecovery)) { 4747 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4748 if (Corrected.isOverloaded()) { 4749 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4750 OverloadCandidateSet::iterator Best; 4751 for (NamedDecl *CD : Corrected) { 4752 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4753 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4754 OCS); 4755 } 4756 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4757 case OR_Success: 4758 ND = Best->FoundDecl; 4759 Corrected.setCorrectionDecl(ND); 4760 break; 4761 default: 4762 break; 4763 } 4764 } 4765 ND = ND->getUnderlyingDecl(); 4766 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4767 return Corrected; 4768 } 4769 } 4770 return TypoCorrection(); 4771 } 4772 4773 /// ConvertArgumentsForCall - Converts the arguments specified in 4774 /// Args/NumArgs to the parameter types of the function FDecl with 4775 /// function prototype Proto. Call is the call expression itself, and 4776 /// Fn is the function expression. For a C++ member function, this 4777 /// routine does not attempt to convert the object argument. Returns 4778 /// true if the call is ill-formed. 4779 bool 4780 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4781 FunctionDecl *FDecl, 4782 const FunctionProtoType *Proto, 4783 ArrayRef<Expr *> Args, 4784 SourceLocation RParenLoc, 4785 bool IsExecConfig) { 4786 // Bail out early if calling a builtin with custom typechecking. 4787 if (FDecl) 4788 if (unsigned ID = FDecl->getBuiltinID()) 4789 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4790 return false; 4791 4792 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4793 // assignment, to the types of the corresponding parameter, ... 4794 unsigned NumParams = Proto->getNumParams(); 4795 bool Invalid = false; 4796 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4797 unsigned FnKind = Fn->getType()->isBlockPointerType() 4798 ? 1 /* block */ 4799 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4800 : 0 /* function */); 4801 4802 // If too few arguments are available (and we don't have default 4803 // arguments for the remaining parameters), don't make the call. 4804 if (Args.size() < NumParams) { 4805 if (Args.size() < MinArgs) { 4806 TypoCorrection TC; 4807 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4808 unsigned diag_id = 4809 MinArgs == NumParams && !Proto->isVariadic() 4810 ? diag::err_typecheck_call_too_few_args_suggest 4811 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4812 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4813 << static_cast<unsigned>(Args.size()) 4814 << TC.getCorrectionRange()); 4815 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4816 Diag(RParenLoc, 4817 MinArgs == NumParams && !Proto->isVariadic() 4818 ? diag::err_typecheck_call_too_few_args_one 4819 : diag::err_typecheck_call_too_few_args_at_least_one) 4820 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4821 else 4822 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4823 ? diag::err_typecheck_call_too_few_args 4824 : diag::err_typecheck_call_too_few_args_at_least) 4825 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4826 << Fn->getSourceRange(); 4827 4828 // Emit the location of the prototype. 4829 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4830 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4831 4832 return true; 4833 } 4834 Call->setNumArgs(Context, NumParams); 4835 } 4836 4837 // If too many are passed and not variadic, error on the extras and drop 4838 // them. 4839 if (Args.size() > NumParams) { 4840 if (!Proto->isVariadic()) { 4841 TypoCorrection TC; 4842 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4843 unsigned diag_id = 4844 MinArgs == NumParams && !Proto->isVariadic() 4845 ? diag::err_typecheck_call_too_many_args_suggest 4846 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4847 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4848 << static_cast<unsigned>(Args.size()) 4849 << TC.getCorrectionRange()); 4850 } else if (NumParams == 1 && FDecl && 4851 FDecl->getParamDecl(0)->getDeclName()) 4852 Diag(Args[NumParams]->getBeginLoc(), 4853 MinArgs == NumParams 4854 ? diag::err_typecheck_call_too_many_args_one 4855 : diag::err_typecheck_call_too_many_args_at_most_one) 4856 << FnKind << FDecl->getParamDecl(0) 4857 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4858 << SourceRange(Args[NumParams]->getBeginLoc(), 4859 Args.back()->getEndLoc()); 4860 else 4861 Diag(Args[NumParams]->getBeginLoc(), 4862 MinArgs == NumParams 4863 ? diag::err_typecheck_call_too_many_args 4864 : diag::err_typecheck_call_too_many_args_at_most) 4865 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4866 << Fn->getSourceRange() 4867 << SourceRange(Args[NumParams]->getBeginLoc(), 4868 Args.back()->getEndLoc()); 4869 4870 // Emit the location of the prototype. 4871 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4872 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4873 4874 // This deletes the extra arguments. 4875 Call->setNumArgs(Context, NumParams); 4876 return true; 4877 } 4878 } 4879 SmallVector<Expr *, 8> AllArgs; 4880 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4881 4882 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4883 AllArgs, CallType); 4884 if (Invalid) 4885 return true; 4886 unsigned TotalNumArgs = AllArgs.size(); 4887 for (unsigned i = 0; i < TotalNumArgs; ++i) 4888 Call->setArg(i, AllArgs[i]); 4889 4890 return false; 4891 } 4892 4893 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4894 const FunctionProtoType *Proto, 4895 unsigned FirstParam, ArrayRef<Expr *> Args, 4896 SmallVectorImpl<Expr *> &AllArgs, 4897 VariadicCallType CallType, bool AllowExplicit, 4898 bool IsListInitialization) { 4899 unsigned NumParams = Proto->getNumParams(); 4900 bool Invalid = false; 4901 size_t ArgIx = 0; 4902 // Continue to check argument types (even if we have too few/many args). 4903 for (unsigned i = FirstParam; i < NumParams; i++) { 4904 QualType ProtoArgType = Proto->getParamType(i); 4905 4906 Expr *Arg; 4907 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4908 if (ArgIx < Args.size()) { 4909 Arg = Args[ArgIx++]; 4910 4911 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 4912 diag::err_call_incomplete_argument, Arg)) 4913 return true; 4914 4915 // Strip the unbridged-cast placeholder expression off, if applicable. 4916 bool CFAudited = false; 4917 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4918 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4919 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4920 Arg = stripARCUnbridgedCast(Arg); 4921 else if (getLangOpts().ObjCAutoRefCount && 4922 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4923 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4924 CFAudited = true; 4925 4926 if (Proto->getExtParameterInfo(i).isNoEscape()) 4927 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4928 BE->getBlockDecl()->setDoesNotEscape(); 4929 4930 InitializedEntity Entity = 4931 Param ? InitializedEntity::InitializeParameter(Context, Param, 4932 ProtoArgType) 4933 : InitializedEntity::InitializeParameter( 4934 Context, ProtoArgType, Proto->isParamConsumed(i)); 4935 4936 // Remember that parameter belongs to a CF audited API. 4937 if (CFAudited) 4938 Entity.setParameterCFAudited(); 4939 4940 ExprResult ArgE = PerformCopyInitialization( 4941 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4942 if (ArgE.isInvalid()) 4943 return true; 4944 4945 Arg = ArgE.getAs<Expr>(); 4946 } else { 4947 assert(Param && "can't use default arguments without a known callee"); 4948 4949 ExprResult ArgExpr = 4950 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4951 if (ArgExpr.isInvalid()) 4952 return true; 4953 4954 Arg = ArgExpr.getAs<Expr>(); 4955 } 4956 4957 // Check for array bounds violations for each argument to the call. This 4958 // check only triggers warnings when the argument isn't a more complex Expr 4959 // with its own checking, such as a BinaryOperator. 4960 CheckArrayAccess(Arg); 4961 4962 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4963 CheckStaticArrayArgument(CallLoc, Param, Arg); 4964 4965 AllArgs.push_back(Arg); 4966 } 4967 4968 // If this is a variadic call, handle args passed through "...". 4969 if (CallType != VariadicDoesNotApply) { 4970 // Assume that extern "C" functions with variadic arguments that 4971 // return __unknown_anytype aren't *really* variadic. 4972 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4973 FDecl->isExternC()) { 4974 for (Expr *A : Args.slice(ArgIx)) { 4975 QualType paramType; // ignored 4976 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4977 Invalid |= arg.isInvalid(); 4978 AllArgs.push_back(arg.get()); 4979 } 4980 4981 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4982 } else { 4983 for (Expr *A : Args.slice(ArgIx)) { 4984 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4985 Invalid |= Arg.isInvalid(); 4986 AllArgs.push_back(Arg.get()); 4987 } 4988 } 4989 4990 // Check for array bounds violations. 4991 for (Expr *A : Args.slice(ArgIx)) 4992 CheckArrayAccess(A); 4993 } 4994 return Invalid; 4995 } 4996 4997 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4998 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4999 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5000 TL = DTL.getOriginalLoc(); 5001 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5002 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5003 << ATL.getLocalSourceRange(); 5004 } 5005 5006 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5007 /// array parameter, check that it is non-null, and that if it is formed by 5008 /// array-to-pointer decay, the underlying array is sufficiently large. 5009 /// 5010 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5011 /// array type derivation, then for each call to the function, the value of the 5012 /// corresponding actual argument shall provide access to the first element of 5013 /// an array with at least as many elements as specified by the size expression. 5014 void 5015 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5016 ParmVarDecl *Param, 5017 const Expr *ArgExpr) { 5018 // Static array parameters are not supported in C++. 5019 if (!Param || getLangOpts().CPlusPlus) 5020 return; 5021 5022 QualType OrigTy = Param->getOriginalType(); 5023 5024 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5025 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5026 return; 5027 5028 if (ArgExpr->isNullPointerConstant(Context, 5029 Expr::NPC_NeverValueDependent)) { 5030 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5031 DiagnoseCalleeStaticArrayParam(*this, Param); 5032 return; 5033 } 5034 5035 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5036 if (!CAT) 5037 return; 5038 5039 const ConstantArrayType *ArgCAT = 5040 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5041 if (!ArgCAT) 5042 return; 5043 5044 if (ArgCAT->getSize().ult(CAT->getSize())) { 5045 Diag(CallLoc, diag::warn_static_array_too_small) 5046 << ArgExpr->getSourceRange() 5047 << (unsigned) ArgCAT->getSize().getZExtValue() 5048 << (unsigned) CAT->getSize().getZExtValue(); 5049 DiagnoseCalleeStaticArrayParam(*this, Param); 5050 } 5051 } 5052 5053 /// Given a function expression of unknown-any type, try to rebuild it 5054 /// to have a function type. 5055 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5056 5057 /// Is the given type a placeholder that we need to lower out 5058 /// immediately during argument processing? 5059 static bool isPlaceholderToRemoveAsArg(QualType type) { 5060 // Placeholders are never sugared. 5061 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5062 if (!placeholder) return false; 5063 5064 switch (placeholder->getKind()) { 5065 // Ignore all the non-placeholder types. 5066 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5067 case BuiltinType::Id: 5068 #include "clang/Basic/OpenCLImageTypes.def" 5069 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5070 case BuiltinType::Id: 5071 #include "clang/Basic/OpenCLExtensionTypes.def" 5072 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5073 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5074 #include "clang/AST/BuiltinTypes.def" 5075 return false; 5076 5077 // We cannot lower out overload sets; they might validly be resolved 5078 // by the call machinery. 5079 case BuiltinType::Overload: 5080 return false; 5081 5082 // Unbridged casts in ARC can be handled in some call positions and 5083 // should be left in place. 5084 case BuiltinType::ARCUnbridgedCast: 5085 return false; 5086 5087 // Pseudo-objects should be converted as soon as possible. 5088 case BuiltinType::PseudoObject: 5089 return true; 5090 5091 // The debugger mode could theoretically but currently does not try 5092 // to resolve unknown-typed arguments based on known parameter types. 5093 case BuiltinType::UnknownAny: 5094 return true; 5095 5096 // These are always invalid as call arguments and should be reported. 5097 case BuiltinType::BoundMember: 5098 case BuiltinType::BuiltinFn: 5099 case BuiltinType::OMPArraySection: 5100 return true; 5101 5102 } 5103 llvm_unreachable("bad builtin type kind"); 5104 } 5105 5106 /// Check an argument list for placeholders that we won't try to 5107 /// handle later. 5108 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5109 // Apply this processing to all the arguments at once instead of 5110 // dying at the first failure. 5111 bool hasInvalid = false; 5112 for (size_t i = 0, e = args.size(); i != e; i++) { 5113 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5114 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5115 if (result.isInvalid()) hasInvalid = true; 5116 else args[i] = result.get(); 5117 } else if (hasInvalid) { 5118 (void)S.CorrectDelayedTyposInExpr(args[i]); 5119 } 5120 } 5121 return hasInvalid; 5122 } 5123 5124 /// If a builtin function has a pointer argument with no explicit address 5125 /// space, then it should be able to accept a pointer to any address 5126 /// space as input. In order to do this, we need to replace the 5127 /// standard builtin declaration with one that uses the same address space 5128 /// as the call. 5129 /// 5130 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5131 /// it does not contain any pointer arguments without 5132 /// an address space qualifer. Otherwise the rewritten 5133 /// FunctionDecl is returned. 5134 /// TODO: Handle pointer return types. 5135 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5136 const FunctionDecl *FDecl, 5137 MultiExprArg ArgExprs) { 5138 5139 QualType DeclType = FDecl->getType(); 5140 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5141 5142 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5143 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5144 return nullptr; 5145 5146 bool NeedsNewDecl = false; 5147 unsigned i = 0; 5148 SmallVector<QualType, 8> OverloadParams; 5149 5150 for (QualType ParamType : FT->param_types()) { 5151 5152 // Convert array arguments to pointer to simplify type lookup. 5153 ExprResult ArgRes = 5154 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5155 if (ArgRes.isInvalid()) 5156 return nullptr; 5157 Expr *Arg = ArgRes.get(); 5158 QualType ArgType = Arg->getType(); 5159 if (!ParamType->isPointerType() || 5160 ParamType.getQualifiers().hasAddressSpace() || 5161 !ArgType->isPointerType() || 5162 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5163 OverloadParams.push_back(ParamType); 5164 continue; 5165 } 5166 5167 QualType PointeeType = ParamType->getPointeeType(); 5168 if (PointeeType.getQualifiers().hasAddressSpace()) 5169 continue; 5170 5171 NeedsNewDecl = true; 5172 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5173 5174 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5175 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5176 } 5177 5178 if (!NeedsNewDecl) 5179 return nullptr; 5180 5181 FunctionProtoType::ExtProtoInfo EPI; 5182 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5183 OverloadParams, EPI); 5184 DeclContext *Parent = Context.getTranslationUnitDecl(); 5185 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5186 FDecl->getLocation(), 5187 FDecl->getLocation(), 5188 FDecl->getIdentifier(), 5189 OverloadTy, 5190 /*TInfo=*/nullptr, 5191 SC_Extern, false, 5192 /*hasPrototype=*/true); 5193 SmallVector<ParmVarDecl*, 16> Params; 5194 FT = cast<FunctionProtoType>(OverloadTy); 5195 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5196 QualType ParamType = FT->getParamType(i); 5197 ParmVarDecl *Parm = 5198 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5199 SourceLocation(), nullptr, ParamType, 5200 /*TInfo=*/nullptr, SC_None, nullptr); 5201 Parm->setScopeInfo(0, i); 5202 Params.push_back(Parm); 5203 } 5204 OverloadDecl->setParams(Params); 5205 return OverloadDecl; 5206 } 5207 5208 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5209 FunctionDecl *Callee, 5210 MultiExprArg ArgExprs) { 5211 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5212 // similar attributes) really don't like it when functions are called with an 5213 // invalid number of args. 5214 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5215 /*PartialOverloading=*/false) && 5216 !Callee->isVariadic()) 5217 return; 5218 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5219 return; 5220 5221 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5222 S.Diag(Fn->getBeginLoc(), 5223 isa<CXXMethodDecl>(Callee) 5224 ? diag::err_ovl_no_viable_member_function_in_call 5225 : diag::err_ovl_no_viable_function_in_call) 5226 << Callee << Callee->getSourceRange(); 5227 S.Diag(Callee->getLocation(), 5228 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5229 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5230 return; 5231 } 5232 } 5233 5234 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5235 const UnresolvedMemberExpr *const UME, Sema &S) { 5236 5237 const auto GetFunctionLevelDCIfCXXClass = 5238 [](Sema &S) -> const CXXRecordDecl * { 5239 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5240 if (!DC || !DC->getParent()) 5241 return nullptr; 5242 5243 // If the call to some member function was made from within a member 5244 // function body 'M' return return 'M's parent. 5245 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5246 return MD->getParent()->getCanonicalDecl(); 5247 // else the call was made from within a default member initializer of a 5248 // class, so return the class. 5249 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5250 return RD->getCanonicalDecl(); 5251 return nullptr; 5252 }; 5253 // If our DeclContext is neither a member function nor a class (in the 5254 // case of a lambda in a default member initializer), we can't have an 5255 // enclosing 'this'. 5256 5257 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5258 if (!CurParentClass) 5259 return false; 5260 5261 // The naming class for implicit member functions call is the class in which 5262 // name lookup starts. 5263 const CXXRecordDecl *const NamingClass = 5264 UME->getNamingClass()->getCanonicalDecl(); 5265 assert(NamingClass && "Must have naming class even for implicit access"); 5266 5267 // If the unresolved member functions were found in a 'naming class' that is 5268 // related (either the same or derived from) to the class that contains the 5269 // member function that itself contained the implicit member access. 5270 5271 return CurParentClass == NamingClass || 5272 CurParentClass->isDerivedFrom(NamingClass); 5273 } 5274 5275 static void 5276 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5277 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5278 5279 if (!UME) 5280 return; 5281 5282 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5283 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5284 // already been captured, or if this is an implicit member function call (if 5285 // it isn't, an attempt to capture 'this' should already have been made). 5286 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5287 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5288 return; 5289 5290 // Check if the naming class in which the unresolved members were found is 5291 // related (same as or is a base of) to the enclosing class. 5292 5293 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5294 return; 5295 5296 5297 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5298 // If the enclosing function is not dependent, then this lambda is 5299 // capture ready, so if we can capture this, do so. 5300 if (!EnclosingFunctionCtx->isDependentContext()) { 5301 // If the current lambda and all enclosing lambdas can capture 'this' - 5302 // then go ahead and capture 'this' (since our unresolved overload set 5303 // contains at least one non-static member function). 5304 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5305 S.CheckCXXThisCapture(CallLoc); 5306 } else if (S.CurContext->isDependentContext()) { 5307 // ... since this is an implicit member reference, that might potentially 5308 // involve a 'this' capture, mark 'this' for potential capture in 5309 // enclosing lambdas. 5310 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5311 CurLSI->addPotentialThisCapture(CallLoc); 5312 } 5313 } 5314 5315 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5316 /// This provides the location of the left/right parens and a list of comma 5317 /// locations. 5318 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5319 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5320 Expr *ExecConfig, bool IsExecConfig) { 5321 // Since this might be a postfix expression, get rid of ParenListExprs. 5322 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5323 if (Result.isInvalid()) return ExprError(); 5324 Fn = Result.get(); 5325 5326 if (checkArgsForPlaceholders(*this, ArgExprs)) 5327 return ExprError(); 5328 5329 if (getLangOpts().CPlusPlus) { 5330 // If this is a pseudo-destructor expression, build the call immediately. 5331 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5332 if (!ArgExprs.empty()) { 5333 // Pseudo-destructor calls should not have any arguments. 5334 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5335 << FixItHint::CreateRemoval( 5336 SourceRange(ArgExprs.front()->getBeginLoc(), 5337 ArgExprs.back()->getEndLoc())); 5338 } 5339 5340 return new (Context) 5341 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5342 } 5343 if (Fn->getType() == Context.PseudoObjectTy) { 5344 ExprResult result = CheckPlaceholderExpr(Fn); 5345 if (result.isInvalid()) return ExprError(); 5346 Fn = result.get(); 5347 } 5348 5349 // Determine whether this is a dependent call inside a C++ template, 5350 // in which case we won't do any semantic analysis now. 5351 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5352 if (ExecConfig) { 5353 return new (Context) CUDAKernelCallExpr( 5354 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5355 Context.DependentTy, VK_RValue, RParenLoc); 5356 } else { 5357 5358 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5359 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5360 Fn->getBeginLoc()); 5361 5362 return new (Context) CallExpr( 5363 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5364 } 5365 } 5366 5367 // Determine whether this is a call to an object (C++ [over.call.object]). 5368 if (Fn->getType()->isRecordType()) 5369 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5370 RParenLoc); 5371 5372 if (Fn->getType() == Context.UnknownAnyTy) { 5373 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5374 if (result.isInvalid()) return ExprError(); 5375 Fn = result.get(); 5376 } 5377 5378 if (Fn->getType() == Context.BoundMemberTy) { 5379 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5380 RParenLoc); 5381 } 5382 } 5383 5384 // Check for overloaded calls. This can happen even in C due to extensions. 5385 if (Fn->getType() == Context.OverloadTy) { 5386 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5387 5388 // We aren't supposed to apply this logic if there's an '&' involved. 5389 if (!find.HasFormOfMemberPointer) { 5390 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5391 return new (Context) CallExpr( 5392 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5393 OverloadExpr *ovl = find.Expression; 5394 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5395 return BuildOverloadedCallExpr( 5396 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5397 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5398 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5399 RParenLoc); 5400 } 5401 } 5402 5403 // If we're directly calling a function, get the appropriate declaration. 5404 if (Fn->getType() == Context.UnknownAnyTy) { 5405 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5406 if (result.isInvalid()) return ExprError(); 5407 Fn = result.get(); 5408 } 5409 5410 Expr *NakedFn = Fn->IgnoreParens(); 5411 5412 bool CallingNDeclIndirectly = false; 5413 NamedDecl *NDecl = nullptr; 5414 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5415 if (UnOp->getOpcode() == UO_AddrOf) { 5416 CallingNDeclIndirectly = true; 5417 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5418 } 5419 } 5420 5421 if (isa<DeclRefExpr>(NakedFn)) { 5422 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5423 5424 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5425 if (FDecl && FDecl->getBuiltinID()) { 5426 // Rewrite the function decl for this builtin by replacing parameters 5427 // with no explicit address space with the address space of the arguments 5428 // in ArgExprs. 5429 if ((FDecl = 5430 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5431 NDecl = FDecl; 5432 Fn = DeclRefExpr::Create( 5433 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5434 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5435 } 5436 } 5437 } else if (isa<MemberExpr>(NakedFn)) 5438 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5439 5440 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5441 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5442 FD, /*Complain=*/true, Fn->getBeginLoc())) 5443 return ExprError(); 5444 5445 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5446 return ExprError(); 5447 5448 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5449 } 5450 5451 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5452 ExecConfig, IsExecConfig); 5453 } 5454 5455 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5456 /// 5457 /// __builtin_astype( value, dst type ) 5458 /// 5459 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5460 SourceLocation BuiltinLoc, 5461 SourceLocation RParenLoc) { 5462 ExprValueKind VK = VK_RValue; 5463 ExprObjectKind OK = OK_Ordinary; 5464 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5465 QualType SrcTy = E->getType(); 5466 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5467 return ExprError(Diag(BuiltinLoc, 5468 diag::err_invalid_astype_of_different_size) 5469 << DstTy 5470 << SrcTy 5471 << E->getSourceRange()); 5472 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5473 } 5474 5475 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5476 /// provided arguments. 5477 /// 5478 /// __builtin_convertvector( value, dst type ) 5479 /// 5480 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5481 SourceLocation BuiltinLoc, 5482 SourceLocation RParenLoc) { 5483 TypeSourceInfo *TInfo; 5484 GetTypeFromParser(ParsedDestTy, &TInfo); 5485 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5486 } 5487 5488 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5489 /// i.e. an expression not of \p OverloadTy. The expression should 5490 /// unary-convert to an expression of function-pointer or 5491 /// block-pointer type. 5492 /// 5493 /// \param NDecl the declaration being called, if available 5494 ExprResult 5495 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5496 SourceLocation LParenLoc, 5497 ArrayRef<Expr *> Args, 5498 SourceLocation RParenLoc, 5499 Expr *Config, bool IsExecConfig) { 5500 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5501 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5502 5503 // Functions with 'interrupt' attribute cannot be called directly. 5504 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5505 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5506 return ExprError(); 5507 } 5508 5509 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5510 // so there's some risk when calling out to non-interrupt handler functions 5511 // that the callee might not preserve them. This is easy to diagnose here, 5512 // but can be very challenging to debug. 5513 if (auto *Caller = getCurFunctionDecl()) 5514 if (Caller->hasAttr<ARMInterruptAttr>()) { 5515 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5516 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5517 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5518 } 5519 5520 // Promote the function operand. 5521 // We special-case function promotion here because we only allow promoting 5522 // builtin functions to function pointers in the callee of a call. 5523 ExprResult Result; 5524 if (BuiltinID && 5525 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5526 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5527 CK_BuiltinFnToFnPtr).get(); 5528 } else { 5529 Result = CallExprUnaryConversions(Fn); 5530 } 5531 if (Result.isInvalid()) 5532 return ExprError(); 5533 Fn = Result.get(); 5534 5535 // Make the call expr early, before semantic checks. This guarantees cleanup 5536 // of arguments and function on error. 5537 CallExpr *TheCall; 5538 if (Config) 5539 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5540 cast<CallExpr>(Config), Args, 5541 Context.BoolTy, VK_RValue, 5542 RParenLoc); 5543 else 5544 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5545 VK_RValue, RParenLoc); 5546 5547 if (!getLangOpts().CPlusPlus) { 5548 // C cannot always handle TypoExpr nodes in builtin calls and direct 5549 // function calls as their argument checking don't necessarily handle 5550 // dependent types properly, so make sure any TypoExprs have been 5551 // dealt with. 5552 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5553 if (!Result.isUsable()) return ExprError(); 5554 TheCall = dyn_cast<CallExpr>(Result.get()); 5555 if (!TheCall) return Result; 5556 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5557 } 5558 5559 // Bail out early if calling a builtin with custom typechecking. 5560 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5561 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5562 5563 retry: 5564 const FunctionType *FuncT; 5565 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5566 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5567 // have type pointer to function". 5568 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5569 if (!FuncT) 5570 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5571 << Fn->getType() << Fn->getSourceRange()); 5572 } else if (const BlockPointerType *BPT = 5573 Fn->getType()->getAs<BlockPointerType>()) { 5574 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5575 } else { 5576 // Handle calls to expressions of unknown-any type. 5577 if (Fn->getType() == Context.UnknownAnyTy) { 5578 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5579 if (rewrite.isInvalid()) return ExprError(); 5580 Fn = rewrite.get(); 5581 TheCall->setCallee(Fn); 5582 goto retry; 5583 } 5584 5585 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5586 << Fn->getType() << Fn->getSourceRange()); 5587 } 5588 5589 if (getLangOpts().CUDA) { 5590 if (Config) { 5591 // CUDA: Kernel calls must be to global functions 5592 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5593 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5594 << FDecl << Fn->getSourceRange()); 5595 5596 // CUDA: Kernel function must have 'void' return type 5597 if (!FuncT->getReturnType()->isVoidType()) 5598 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5599 << Fn->getType() << Fn->getSourceRange()); 5600 } else { 5601 // CUDA: Calls to global functions must be configured 5602 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5603 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5604 << FDecl << Fn->getSourceRange()); 5605 } 5606 } 5607 5608 // Check for a valid return type 5609 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5610 FDecl)) 5611 return ExprError(); 5612 5613 // We know the result type of the call, set it. 5614 TheCall->setType(FuncT->getCallResultType(Context)); 5615 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5616 5617 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5618 if (Proto) { 5619 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5620 IsExecConfig)) 5621 return ExprError(); 5622 } else { 5623 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5624 5625 if (FDecl) { 5626 // Check if we have too few/too many template arguments, based 5627 // on our knowledge of the function definition. 5628 const FunctionDecl *Def = nullptr; 5629 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5630 Proto = Def->getType()->getAs<FunctionProtoType>(); 5631 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5632 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5633 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5634 } 5635 5636 // If the function we're calling isn't a function prototype, but we have 5637 // a function prototype from a prior declaratiom, use that prototype. 5638 if (!FDecl->hasPrototype()) 5639 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5640 } 5641 5642 // Promote the arguments (C99 6.5.2.2p6). 5643 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5644 Expr *Arg = Args[i]; 5645 5646 if (Proto && i < Proto->getNumParams()) { 5647 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5648 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5649 ExprResult ArgE = 5650 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5651 if (ArgE.isInvalid()) 5652 return true; 5653 5654 Arg = ArgE.getAs<Expr>(); 5655 5656 } else { 5657 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5658 5659 if (ArgE.isInvalid()) 5660 return true; 5661 5662 Arg = ArgE.getAs<Expr>(); 5663 } 5664 5665 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5666 diag::err_call_incomplete_argument, Arg)) 5667 return ExprError(); 5668 5669 TheCall->setArg(i, Arg); 5670 } 5671 } 5672 5673 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5674 if (!Method->isStatic()) 5675 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5676 << Fn->getSourceRange()); 5677 5678 // Check for sentinels 5679 if (NDecl) 5680 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5681 5682 // Do special checking on direct calls to functions. 5683 if (FDecl) { 5684 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5685 return ExprError(); 5686 5687 if (BuiltinID) 5688 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5689 } else if (NDecl) { 5690 if (CheckPointerCall(NDecl, TheCall, Proto)) 5691 return ExprError(); 5692 } else { 5693 if (CheckOtherCall(TheCall, Proto)) 5694 return ExprError(); 5695 } 5696 5697 return MaybeBindToTemporary(TheCall); 5698 } 5699 5700 ExprResult 5701 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5702 SourceLocation RParenLoc, Expr *InitExpr) { 5703 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5704 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5705 5706 TypeSourceInfo *TInfo; 5707 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5708 if (!TInfo) 5709 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5710 5711 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5712 } 5713 5714 ExprResult 5715 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5716 SourceLocation RParenLoc, Expr *LiteralExpr) { 5717 QualType literalType = TInfo->getType(); 5718 5719 if (literalType->isArrayType()) { 5720 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5721 diag::err_illegal_decl_array_incomplete_type, 5722 SourceRange(LParenLoc, 5723 LiteralExpr->getSourceRange().getEnd()))) 5724 return ExprError(); 5725 if (literalType->isVariableArrayType()) 5726 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5727 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5728 } else if (!literalType->isDependentType() && 5729 RequireCompleteType(LParenLoc, literalType, 5730 diag::err_typecheck_decl_incomplete_type, 5731 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5732 return ExprError(); 5733 5734 InitializedEntity Entity 5735 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5736 InitializationKind Kind 5737 = InitializationKind::CreateCStyleCast(LParenLoc, 5738 SourceRange(LParenLoc, RParenLoc), 5739 /*InitList=*/true); 5740 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5741 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5742 &literalType); 5743 if (Result.isInvalid()) 5744 return ExprError(); 5745 LiteralExpr = Result.get(); 5746 5747 bool isFileScope = !CurContext->isFunctionOrMethod(); 5748 5749 // In C, compound literals are l-values for some reason. 5750 // For GCC compatibility, in C++, file-scope array compound literals with 5751 // constant initializers are also l-values, and compound literals are 5752 // otherwise prvalues. 5753 // 5754 // (GCC also treats C++ list-initialized file-scope array prvalues with 5755 // constant initializers as l-values, but that's non-conforming, so we don't 5756 // follow it there.) 5757 // 5758 // FIXME: It would be better to handle the lvalue cases as materializing and 5759 // lifetime-extending a temporary object, but our materialized temporaries 5760 // representation only supports lifetime extension from a variable, not "out 5761 // of thin air". 5762 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5763 // is bound to the result of applying array-to-pointer decay to the compound 5764 // literal. 5765 // FIXME: GCC supports compound literals of reference type, which should 5766 // obviously have a value kind derived from the kind of reference involved. 5767 ExprValueKind VK = 5768 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5769 ? VK_RValue 5770 : VK_LValue; 5771 5772 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5773 VK, LiteralExpr, isFileScope); 5774 if (isFileScope) { 5775 if (!LiteralExpr->isTypeDependent() && 5776 !LiteralExpr->isValueDependent() && 5777 !literalType->isDependentType()) // C99 6.5.2.5p3 5778 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5779 return ExprError(); 5780 E = new (Context) ConstantExpr(E); 5781 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 5782 literalType.getAddressSpace() != LangAS::Default) { 5783 // Embedded-C extensions to C99 6.5.2.5: 5784 // "If the compound literal occurs inside the body of a function, the 5785 // type name shall not be qualified by an address-space qualifier." 5786 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 5787 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 5788 return ExprError(); 5789 } 5790 5791 return MaybeBindToTemporary(E); 5792 } 5793 5794 ExprResult 5795 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5796 SourceLocation RBraceLoc) { 5797 // Immediately handle non-overload placeholders. Overloads can be 5798 // resolved contextually, but everything else here can't. 5799 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5800 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5801 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5802 5803 // Ignore failures; dropping the entire initializer list because 5804 // of one failure would be terrible for indexing/etc. 5805 if (result.isInvalid()) continue; 5806 5807 InitArgList[I] = result.get(); 5808 } 5809 } 5810 5811 // Semantic analysis for initializers is done by ActOnDeclarator() and 5812 // CheckInitializer() - it requires knowledge of the object being initialized. 5813 5814 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5815 RBraceLoc); 5816 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5817 return E; 5818 } 5819 5820 /// Do an explicit extend of the given block pointer if we're in ARC. 5821 void Sema::maybeExtendBlockObject(ExprResult &E) { 5822 assert(E.get()->getType()->isBlockPointerType()); 5823 assert(E.get()->isRValue()); 5824 5825 // Only do this in an r-value context. 5826 if (!getLangOpts().ObjCAutoRefCount) return; 5827 5828 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5829 CK_ARCExtendBlockObject, E.get(), 5830 /*base path*/ nullptr, VK_RValue); 5831 Cleanup.setExprNeedsCleanups(true); 5832 } 5833 5834 /// Prepare a conversion of the given expression to an ObjC object 5835 /// pointer type. 5836 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5837 QualType type = E.get()->getType(); 5838 if (type->isObjCObjectPointerType()) { 5839 return CK_BitCast; 5840 } else if (type->isBlockPointerType()) { 5841 maybeExtendBlockObject(E); 5842 return CK_BlockPointerToObjCPointerCast; 5843 } else { 5844 assert(type->isPointerType()); 5845 return CK_CPointerToObjCPointerCast; 5846 } 5847 } 5848 5849 /// Prepares for a scalar cast, performing all the necessary stages 5850 /// except the final cast and returning the kind required. 5851 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5852 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5853 // Also, callers should have filtered out the invalid cases with 5854 // pointers. Everything else should be possible. 5855 5856 QualType SrcTy = Src.get()->getType(); 5857 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5858 return CK_NoOp; 5859 5860 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5861 case Type::STK_MemberPointer: 5862 llvm_unreachable("member pointer type in C"); 5863 5864 case Type::STK_CPointer: 5865 case Type::STK_BlockPointer: 5866 case Type::STK_ObjCObjectPointer: 5867 switch (DestTy->getScalarTypeKind()) { 5868 case Type::STK_CPointer: { 5869 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5870 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5871 if (SrcAS != DestAS) 5872 return CK_AddressSpaceConversion; 5873 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 5874 return CK_NoOp; 5875 return CK_BitCast; 5876 } 5877 case Type::STK_BlockPointer: 5878 return (SrcKind == Type::STK_BlockPointer 5879 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5880 case Type::STK_ObjCObjectPointer: 5881 if (SrcKind == Type::STK_ObjCObjectPointer) 5882 return CK_BitCast; 5883 if (SrcKind == Type::STK_CPointer) 5884 return CK_CPointerToObjCPointerCast; 5885 maybeExtendBlockObject(Src); 5886 return CK_BlockPointerToObjCPointerCast; 5887 case Type::STK_Bool: 5888 return CK_PointerToBoolean; 5889 case Type::STK_Integral: 5890 return CK_PointerToIntegral; 5891 case Type::STK_Floating: 5892 case Type::STK_FloatingComplex: 5893 case Type::STK_IntegralComplex: 5894 case Type::STK_MemberPointer: 5895 case Type::STK_FixedPoint: 5896 llvm_unreachable("illegal cast from pointer"); 5897 } 5898 llvm_unreachable("Should have returned before this"); 5899 5900 case Type::STK_FixedPoint: 5901 switch (DestTy->getScalarTypeKind()) { 5902 case Type::STK_FixedPoint: 5903 return CK_FixedPointCast; 5904 case Type::STK_Bool: 5905 return CK_FixedPointToBoolean; 5906 case Type::STK_Integral: 5907 case Type::STK_Floating: 5908 case Type::STK_IntegralComplex: 5909 case Type::STK_FloatingComplex: 5910 Diag(Src.get()->getExprLoc(), 5911 diag::err_unimplemented_conversion_with_fixed_point_type) 5912 << DestTy; 5913 return CK_IntegralCast; 5914 case Type::STK_CPointer: 5915 case Type::STK_ObjCObjectPointer: 5916 case Type::STK_BlockPointer: 5917 case Type::STK_MemberPointer: 5918 llvm_unreachable("illegal cast to pointer type"); 5919 } 5920 llvm_unreachable("Should have returned before this"); 5921 5922 case Type::STK_Bool: // casting from bool is like casting from an integer 5923 case Type::STK_Integral: 5924 switch (DestTy->getScalarTypeKind()) { 5925 case Type::STK_CPointer: 5926 case Type::STK_ObjCObjectPointer: 5927 case Type::STK_BlockPointer: 5928 if (Src.get()->isNullPointerConstant(Context, 5929 Expr::NPC_ValueDependentIsNull)) 5930 return CK_NullToPointer; 5931 return CK_IntegralToPointer; 5932 case Type::STK_Bool: 5933 return CK_IntegralToBoolean; 5934 case Type::STK_Integral: 5935 return CK_IntegralCast; 5936 case Type::STK_Floating: 5937 return CK_IntegralToFloating; 5938 case Type::STK_IntegralComplex: 5939 Src = ImpCastExprToType(Src.get(), 5940 DestTy->castAs<ComplexType>()->getElementType(), 5941 CK_IntegralCast); 5942 return CK_IntegralRealToComplex; 5943 case Type::STK_FloatingComplex: 5944 Src = ImpCastExprToType(Src.get(), 5945 DestTy->castAs<ComplexType>()->getElementType(), 5946 CK_IntegralToFloating); 5947 return CK_FloatingRealToComplex; 5948 case Type::STK_MemberPointer: 5949 llvm_unreachable("member pointer type in C"); 5950 case Type::STK_FixedPoint: 5951 Diag(Src.get()->getExprLoc(), 5952 diag::err_unimplemented_conversion_with_fixed_point_type) 5953 << SrcTy; 5954 return CK_IntegralCast; 5955 } 5956 llvm_unreachable("Should have returned before this"); 5957 5958 case Type::STK_Floating: 5959 switch (DestTy->getScalarTypeKind()) { 5960 case Type::STK_Floating: 5961 return CK_FloatingCast; 5962 case Type::STK_Bool: 5963 return CK_FloatingToBoolean; 5964 case Type::STK_Integral: 5965 return CK_FloatingToIntegral; 5966 case Type::STK_FloatingComplex: 5967 Src = ImpCastExprToType(Src.get(), 5968 DestTy->castAs<ComplexType>()->getElementType(), 5969 CK_FloatingCast); 5970 return CK_FloatingRealToComplex; 5971 case Type::STK_IntegralComplex: 5972 Src = ImpCastExprToType(Src.get(), 5973 DestTy->castAs<ComplexType>()->getElementType(), 5974 CK_FloatingToIntegral); 5975 return CK_IntegralRealToComplex; 5976 case Type::STK_CPointer: 5977 case Type::STK_ObjCObjectPointer: 5978 case Type::STK_BlockPointer: 5979 llvm_unreachable("valid float->pointer cast?"); 5980 case Type::STK_MemberPointer: 5981 llvm_unreachable("member pointer type in C"); 5982 case Type::STK_FixedPoint: 5983 Diag(Src.get()->getExprLoc(), 5984 diag::err_unimplemented_conversion_with_fixed_point_type) 5985 << SrcTy; 5986 return CK_IntegralCast; 5987 } 5988 llvm_unreachable("Should have returned before this"); 5989 5990 case Type::STK_FloatingComplex: 5991 switch (DestTy->getScalarTypeKind()) { 5992 case Type::STK_FloatingComplex: 5993 return CK_FloatingComplexCast; 5994 case Type::STK_IntegralComplex: 5995 return CK_FloatingComplexToIntegralComplex; 5996 case Type::STK_Floating: { 5997 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5998 if (Context.hasSameType(ET, DestTy)) 5999 return CK_FloatingComplexToReal; 6000 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6001 return CK_FloatingCast; 6002 } 6003 case Type::STK_Bool: 6004 return CK_FloatingComplexToBoolean; 6005 case Type::STK_Integral: 6006 Src = ImpCastExprToType(Src.get(), 6007 SrcTy->castAs<ComplexType>()->getElementType(), 6008 CK_FloatingComplexToReal); 6009 return CK_FloatingToIntegral; 6010 case Type::STK_CPointer: 6011 case Type::STK_ObjCObjectPointer: 6012 case Type::STK_BlockPointer: 6013 llvm_unreachable("valid complex float->pointer cast?"); 6014 case Type::STK_MemberPointer: 6015 llvm_unreachable("member pointer type in C"); 6016 case Type::STK_FixedPoint: 6017 Diag(Src.get()->getExprLoc(), 6018 diag::err_unimplemented_conversion_with_fixed_point_type) 6019 << SrcTy; 6020 return CK_IntegralCast; 6021 } 6022 llvm_unreachable("Should have returned before this"); 6023 6024 case Type::STK_IntegralComplex: 6025 switch (DestTy->getScalarTypeKind()) { 6026 case Type::STK_FloatingComplex: 6027 return CK_IntegralComplexToFloatingComplex; 6028 case Type::STK_IntegralComplex: 6029 return CK_IntegralComplexCast; 6030 case Type::STK_Integral: { 6031 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6032 if (Context.hasSameType(ET, DestTy)) 6033 return CK_IntegralComplexToReal; 6034 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6035 return CK_IntegralCast; 6036 } 6037 case Type::STK_Bool: 6038 return CK_IntegralComplexToBoolean; 6039 case Type::STK_Floating: 6040 Src = ImpCastExprToType(Src.get(), 6041 SrcTy->castAs<ComplexType>()->getElementType(), 6042 CK_IntegralComplexToReal); 6043 return CK_IntegralToFloating; 6044 case Type::STK_CPointer: 6045 case Type::STK_ObjCObjectPointer: 6046 case Type::STK_BlockPointer: 6047 llvm_unreachable("valid complex int->pointer cast?"); 6048 case Type::STK_MemberPointer: 6049 llvm_unreachable("member pointer type in C"); 6050 case Type::STK_FixedPoint: 6051 Diag(Src.get()->getExprLoc(), 6052 diag::err_unimplemented_conversion_with_fixed_point_type) 6053 << SrcTy; 6054 return CK_IntegralCast; 6055 } 6056 llvm_unreachable("Should have returned before this"); 6057 } 6058 6059 llvm_unreachable("Unhandled scalar cast"); 6060 } 6061 6062 static bool breakDownVectorType(QualType type, uint64_t &len, 6063 QualType &eltType) { 6064 // Vectors are simple. 6065 if (const VectorType *vecType = type->getAs<VectorType>()) { 6066 len = vecType->getNumElements(); 6067 eltType = vecType->getElementType(); 6068 assert(eltType->isScalarType()); 6069 return true; 6070 } 6071 6072 // We allow lax conversion to and from non-vector types, but only if 6073 // they're real types (i.e. non-complex, non-pointer scalar types). 6074 if (!type->isRealType()) return false; 6075 6076 len = 1; 6077 eltType = type; 6078 return true; 6079 } 6080 6081 /// Are the two types lax-compatible vector types? That is, given 6082 /// that one of them is a vector, do they have equal storage sizes, 6083 /// where the storage size is the number of elements times the element 6084 /// size? 6085 /// 6086 /// This will also return false if either of the types is neither a 6087 /// vector nor a real type. 6088 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6089 assert(destTy->isVectorType() || srcTy->isVectorType()); 6090 6091 // Disallow lax conversions between scalars and ExtVectors (these 6092 // conversions are allowed for other vector types because common headers 6093 // depend on them). Most scalar OP ExtVector cases are handled by the 6094 // splat path anyway, which does what we want (convert, not bitcast). 6095 // What this rules out for ExtVectors is crazy things like char4*float. 6096 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6097 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6098 6099 uint64_t srcLen, destLen; 6100 QualType srcEltTy, destEltTy; 6101 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6102 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6103 6104 // ASTContext::getTypeSize will return the size rounded up to a 6105 // power of 2, so instead of using that, we need to use the raw 6106 // element size multiplied by the element count. 6107 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6108 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6109 6110 return (srcLen * srcEltSize == destLen * destEltSize); 6111 } 6112 6113 /// Is this a legal conversion between two types, one of which is 6114 /// known to be a vector type? 6115 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6116 assert(destTy->isVectorType() || srcTy->isVectorType()); 6117 6118 if (!Context.getLangOpts().LaxVectorConversions) 6119 return false; 6120 return areLaxCompatibleVectorTypes(srcTy, destTy); 6121 } 6122 6123 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6124 CastKind &Kind) { 6125 assert(VectorTy->isVectorType() && "Not a vector type!"); 6126 6127 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6128 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6129 return Diag(R.getBegin(), 6130 Ty->isVectorType() ? 6131 diag::err_invalid_conversion_between_vectors : 6132 diag::err_invalid_conversion_between_vector_and_integer) 6133 << VectorTy << Ty << R; 6134 } else 6135 return Diag(R.getBegin(), 6136 diag::err_invalid_conversion_between_vector_and_scalar) 6137 << VectorTy << Ty << R; 6138 6139 Kind = CK_BitCast; 6140 return false; 6141 } 6142 6143 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6144 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6145 6146 if (DestElemTy == SplattedExpr->getType()) 6147 return SplattedExpr; 6148 6149 assert(DestElemTy->isFloatingType() || 6150 DestElemTy->isIntegralOrEnumerationType()); 6151 6152 CastKind CK; 6153 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6154 // OpenCL requires that we convert `true` boolean expressions to -1, but 6155 // only when splatting vectors. 6156 if (DestElemTy->isFloatingType()) { 6157 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6158 // in two steps: boolean to signed integral, then to floating. 6159 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6160 CK_BooleanToSignedIntegral); 6161 SplattedExpr = CastExprRes.get(); 6162 CK = CK_IntegralToFloating; 6163 } else { 6164 CK = CK_BooleanToSignedIntegral; 6165 } 6166 } else { 6167 ExprResult CastExprRes = SplattedExpr; 6168 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6169 if (CastExprRes.isInvalid()) 6170 return ExprError(); 6171 SplattedExpr = CastExprRes.get(); 6172 } 6173 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6174 } 6175 6176 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6177 Expr *CastExpr, CastKind &Kind) { 6178 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6179 6180 QualType SrcTy = CastExpr->getType(); 6181 6182 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6183 // an ExtVectorType. 6184 // In OpenCL, casts between vectors of different types are not allowed. 6185 // (See OpenCL 6.2). 6186 if (SrcTy->isVectorType()) { 6187 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6188 (getLangOpts().OpenCL && 6189 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6190 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6191 << DestTy << SrcTy << R; 6192 return ExprError(); 6193 } 6194 Kind = CK_BitCast; 6195 return CastExpr; 6196 } 6197 6198 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6199 // conversion will take place first from scalar to elt type, and then 6200 // splat from elt type to vector. 6201 if (SrcTy->isPointerType()) 6202 return Diag(R.getBegin(), 6203 diag::err_invalid_conversion_between_vector_and_scalar) 6204 << DestTy << SrcTy << R; 6205 6206 Kind = CK_VectorSplat; 6207 return prepareVectorSplat(DestTy, CastExpr); 6208 } 6209 6210 ExprResult 6211 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6212 Declarator &D, ParsedType &Ty, 6213 SourceLocation RParenLoc, Expr *CastExpr) { 6214 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6215 "ActOnCastExpr(): missing type or expr"); 6216 6217 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6218 if (D.isInvalidType()) 6219 return ExprError(); 6220 6221 if (getLangOpts().CPlusPlus) { 6222 // Check that there are no default arguments (C++ only). 6223 CheckExtraCXXDefaultArguments(D); 6224 } else { 6225 // Make sure any TypoExprs have been dealt with. 6226 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6227 if (!Res.isUsable()) 6228 return ExprError(); 6229 CastExpr = Res.get(); 6230 } 6231 6232 checkUnusedDeclAttributes(D); 6233 6234 QualType castType = castTInfo->getType(); 6235 Ty = CreateParsedType(castType, castTInfo); 6236 6237 bool isVectorLiteral = false; 6238 6239 // Check for an altivec or OpenCL literal, 6240 // i.e. all the elements are integer constants. 6241 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6242 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6243 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6244 && castType->isVectorType() && (PE || PLE)) { 6245 if (PLE && PLE->getNumExprs() == 0) { 6246 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6247 return ExprError(); 6248 } 6249 if (PE || PLE->getNumExprs() == 1) { 6250 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6251 if (!E->getType()->isVectorType()) 6252 isVectorLiteral = true; 6253 } 6254 else 6255 isVectorLiteral = true; 6256 } 6257 6258 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6259 // then handle it as such. 6260 if (isVectorLiteral) 6261 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6262 6263 // If the Expr being casted is a ParenListExpr, handle it specially. 6264 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6265 // sequence of BinOp comma operators. 6266 if (isa<ParenListExpr>(CastExpr)) { 6267 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6268 if (Result.isInvalid()) return ExprError(); 6269 CastExpr = Result.get(); 6270 } 6271 6272 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6273 !getSourceManager().isInSystemMacro(LParenLoc)) 6274 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6275 6276 CheckTollFreeBridgeCast(castType, CastExpr); 6277 6278 CheckObjCBridgeRelatedCast(castType, CastExpr); 6279 6280 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6281 6282 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6283 } 6284 6285 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6286 SourceLocation RParenLoc, Expr *E, 6287 TypeSourceInfo *TInfo) { 6288 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6289 "Expected paren or paren list expression"); 6290 6291 Expr **exprs; 6292 unsigned numExprs; 6293 Expr *subExpr; 6294 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6295 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6296 LiteralLParenLoc = PE->getLParenLoc(); 6297 LiteralRParenLoc = PE->getRParenLoc(); 6298 exprs = PE->getExprs(); 6299 numExprs = PE->getNumExprs(); 6300 } else { // isa<ParenExpr> by assertion at function entrance 6301 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6302 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6303 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6304 exprs = &subExpr; 6305 numExprs = 1; 6306 } 6307 6308 QualType Ty = TInfo->getType(); 6309 assert(Ty->isVectorType() && "Expected vector type"); 6310 6311 SmallVector<Expr *, 8> initExprs; 6312 const VectorType *VTy = Ty->getAs<VectorType>(); 6313 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6314 6315 // '(...)' form of vector initialization in AltiVec: the number of 6316 // initializers must be one or must match the size of the vector. 6317 // If a single value is specified in the initializer then it will be 6318 // replicated to all the components of the vector 6319 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6320 // The number of initializers must be one or must match the size of the 6321 // vector. If a single value is specified in the initializer then it will 6322 // be replicated to all the components of the vector 6323 if (numExprs == 1) { 6324 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6325 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6326 if (Literal.isInvalid()) 6327 return ExprError(); 6328 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6329 PrepareScalarCast(Literal, ElemTy)); 6330 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6331 } 6332 else if (numExprs < numElems) { 6333 Diag(E->getExprLoc(), 6334 diag::err_incorrect_number_of_vector_initializers); 6335 return ExprError(); 6336 } 6337 else 6338 initExprs.append(exprs, exprs + numExprs); 6339 } 6340 else { 6341 // For OpenCL, when the number of initializers is a single value, 6342 // it will be replicated to all components of the vector. 6343 if (getLangOpts().OpenCL && 6344 VTy->getVectorKind() == VectorType::GenericVector && 6345 numExprs == 1) { 6346 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6347 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6348 if (Literal.isInvalid()) 6349 return ExprError(); 6350 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6351 PrepareScalarCast(Literal, ElemTy)); 6352 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6353 } 6354 6355 initExprs.append(exprs, exprs + numExprs); 6356 } 6357 // FIXME: This means that pretty-printing the final AST will produce curly 6358 // braces instead of the original commas. 6359 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6360 initExprs, LiteralRParenLoc); 6361 initE->setType(Ty); 6362 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6363 } 6364 6365 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6366 /// the ParenListExpr into a sequence of comma binary operators. 6367 ExprResult 6368 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6369 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6370 if (!E) 6371 return OrigExpr; 6372 6373 ExprResult Result(E->getExpr(0)); 6374 6375 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6376 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6377 E->getExpr(i)); 6378 6379 if (Result.isInvalid()) return ExprError(); 6380 6381 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6382 } 6383 6384 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6385 SourceLocation R, 6386 MultiExprArg Val) { 6387 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6388 return expr; 6389 } 6390 6391 /// Emit a specialized diagnostic when one expression is a null pointer 6392 /// constant and the other is not a pointer. Returns true if a diagnostic is 6393 /// emitted. 6394 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6395 SourceLocation QuestionLoc) { 6396 Expr *NullExpr = LHSExpr; 6397 Expr *NonPointerExpr = RHSExpr; 6398 Expr::NullPointerConstantKind NullKind = 6399 NullExpr->isNullPointerConstant(Context, 6400 Expr::NPC_ValueDependentIsNotNull); 6401 6402 if (NullKind == Expr::NPCK_NotNull) { 6403 NullExpr = RHSExpr; 6404 NonPointerExpr = LHSExpr; 6405 NullKind = 6406 NullExpr->isNullPointerConstant(Context, 6407 Expr::NPC_ValueDependentIsNotNull); 6408 } 6409 6410 if (NullKind == Expr::NPCK_NotNull) 6411 return false; 6412 6413 if (NullKind == Expr::NPCK_ZeroExpression) 6414 return false; 6415 6416 if (NullKind == Expr::NPCK_ZeroLiteral) { 6417 // In this case, check to make sure that we got here from a "NULL" 6418 // string in the source code. 6419 NullExpr = NullExpr->IgnoreParenImpCasts(); 6420 SourceLocation loc = NullExpr->getExprLoc(); 6421 if (!findMacroSpelling(loc, "NULL")) 6422 return false; 6423 } 6424 6425 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6426 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6427 << NonPointerExpr->getType() << DiagType 6428 << NonPointerExpr->getSourceRange(); 6429 return true; 6430 } 6431 6432 /// Return false if the condition expression is valid, true otherwise. 6433 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6434 QualType CondTy = Cond->getType(); 6435 6436 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6437 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6438 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6439 << CondTy << Cond->getSourceRange(); 6440 return true; 6441 } 6442 6443 // C99 6.5.15p2 6444 if (CondTy->isScalarType()) return false; 6445 6446 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6447 << CondTy << Cond->getSourceRange(); 6448 return true; 6449 } 6450 6451 /// Handle when one or both operands are void type. 6452 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6453 ExprResult &RHS) { 6454 Expr *LHSExpr = LHS.get(); 6455 Expr *RHSExpr = RHS.get(); 6456 6457 if (!LHSExpr->getType()->isVoidType()) 6458 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6459 << RHSExpr->getSourceRange(); 6460 if (!RHSExpr->getType()->isVoidType()) 6461 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6462 << LHSExpr->getSourceRange(); 6463 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6464 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6465 return S.Context.VoidTy; 6466 } 6467 6468 /// Return false if the NullExpr can be promoted to PointerTy, 6469 /// true otherwise. 6470 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6471 QualType PointerTy) { 6472 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6473 !NullExpr.get()->isNullPointerConstant(S.Context, 6474 Expr::NPC_ValueDependentIsNull)) 6475 return true; 6476 6477 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6478 return false; 6479 } 6480 6481 /// Checks compatibility between two pointers and return the resulting 6482 /// type. 6483 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6484 ExprResult &RHS, 6485 SourceLocation Loc) { 6486 QualType LHSTy = LHS.get()->getType(); 6487 QualType RHSTy = RHS.get()->getType(); 6488 6489 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6490 // Two identical pointers types are always compatible. 6491 return LHSTy; 6492 } 6493 6494 QualType lhptee, rhptee; 6495 6496 // Get the pointee types. 6497 bool IsBlockPointer = false; 6498 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6499 lhptee = LHSBTy->getPointeeType(); 6500 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6501 IsBlockPointer = true; 6502 } else { 6503 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6504 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6505 } 6506 6507 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6508 // differently qualified versions of compatible types, the result type is 6509 // a pointer to an appropriately qualified version of the composite 6510 // type. 6511 6512 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6513 // clause doesn't make sense for our extensions. E.g. address space 2 should 6514 // be incompatible with address space 3: they may live on different devices or 6515 // anything. 6516 Qualifiers lhQual = lhptee.getQualifiers(); 6517 Qualifiers rhQual = rhptee.getQualifiers(); 6518 6519 LangAS ResultAddrSpace = LangAS::Default; 6520 LangAS LAddrSpace = lhQual.getAddressSpace(); 6521 LangAS RAddrSpace = rhQual.getAddressSpace(); 6522 6523 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6524 // spaces is disallowed. 6525 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6526 ResultAddrSpace = LAddrSpace; 6527 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6528 ResultAddrSpace = RAddrSpace; 6529 else { 6530 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6531 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6532 << RHS.get()->getSourceRange(); 6533 return QualType(); 6534 } 6535 6536 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6537 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6538 lhQual.removeCVRQualifiers(); 6539 rhQual.removeCVRQualifiers(); 6540 6541 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6542 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6543 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6544 // qual types are compatible iff 6545 // * corresponded types are compatible 6546 // * CVR qualifiers are equal 6547 // * address spaces are equal 6548 // Thus for conditional operator we merge CVR and address space unqualified 6549 // pointees and if there is a composite type we return a pointer to it with 6550 // merged qualifiers. 6551 LHSCastKind = 6552 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6553 RHSCastKind = 6554 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6555 lhQual.removeAddressSpace(); 6556 rhQual.removeAddressSpace(); 6557 6558 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6559 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6560 6561 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6562 6563 if (CompositeTy.isNull()) { 6564 // In this situation, we assume void* type. No especially good 6565 // reason, but this is what gcc does, and we do have to pick 6566 // to get a consistent AST. 6567 QualType incompatTy; 6568 incompatTy = S.Context.getPointerType( 6569 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6570 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6571 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6572 6573 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6574 // for casts between types with incompatible address space qualifiers. 6575 // For the following code the compiler produces casts between global and 6576 // local address spaces of the corresponded innermost pointees: 6577 // local int *global *a; 6578 // global int *global *b; 6579 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6580 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6581 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6582 << RHS.get()->getSourceRange(); 6583 6584 return incompatTy; 6585 } 6586 6587 // The pointer types are compatible. 6588 // In case of OpenCL ResultTy should have the address space qualifier 6589 // which is a superset of address spaces of both the 2nd and the 3rd 6590 // operands of the conditional operator. 6591 QualType ResultTy = [&, ResultAddrSpace]() { 6592 if (S.getLangOpts().OpenCL) { 6593 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6594 CompositeQuals.setAddressSpace(ResultAddrSpace); 6595 return S.Context 6596 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6597 .withCVRQualifiers(MergedCVRQual); 6598 } 6599 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6600 }(); 6601 if (IsBlockPointer) 6602 ResultTy = S.Context.getBlockPointerType(ResultTy); 6603 else 6604 ResultTy = S.Context.getPointerType(ResultTy); 6605 6606 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6607 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6608 return ResultTy; 6609 } 6610 6611 /// Return the resulting type when the operands are both block pointers. 6612 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6613 ExprResult &LHS, 6614 ExprResult &RHS, 6615 SourceLocation Loc) { 6616 QualType LHSTy = LHS.get()->getType(); 6617 QualType RHSTy = RHS.get()->getType(); 6618 6619 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6620 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6621 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6622 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6623 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6624 return destType; 6625 } 6626 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6627 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6628 << RHS.get()->getSourceRange(); 6629 return QualType(); 6630 } 6631 6632 // We have 2 block pointer types. 6633 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6634 } 6635 6636 /// Return the resulting type when the operands are both pointers. 6637 static QualType 6638 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6639 ExprResult &RHS, 6640 SourceLocation Loc) { 6641 // get the pointer types 6642 QualType LHSTy = LHS.get()->getType(); 6643 QualType RHSTy = RHS.get()->getType(); 6644 6645 // get the "pointed to" types 6646 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6647 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6648 6649 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6650 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6651 // Figure out necessary qualifiers (C99 6.5.15p6) 6652 QualType destPointee 6653 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6654 QualType destType = S.Context.getPointerType(destPointee); 6655 // Add qualifiers if necessary. 6656 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6657 // Promote to void*. 6658 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6659 return destType; 6660 } 6661 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6662 QualType destPointee 6663 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6664 QualType destType = S.Context.getPointerType(destPointee); 6665 // Add qualifiers if necessary. 6666 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6667 // Promote to void*. 6668 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6669 return destType; 6670 } 6671 6672 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6673 } 6674 6675 /// Return false if the first expression is not an integer and the second 6676 /// expression is not a pointer, true otherwise. 6677 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6678 Expr* PointerExpr, SourceLocation Loc, 6679 bool IsIntFirstExpr) { 6680 if (!PointerExpr->getType()->isPointerType() || 6681 !Int.get()->getType()->isIntegerType()) 6682 return false; 6683 6684 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6685 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6686 6687 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6688 << Expr1->getType() << Expr2->getType() 6689 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6690 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6691 CK_IntegralToPointer); 6692 return true; 6693 } 6694 6695 /// Simple conversion between integer and floating point types. 6696 /// 6697 /// Used when handling the OpenCL conditional operator where the 6698 /// condition is a vector while the other operands are scalar. 6699 /// 6700 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6701 /// types are either integer or floating type. Between the two 6702 /// operands, the type with the higher rank is defined as the "result 6703 /// type". The other operand needs to be promoted to the same type. No 6704 /// other type promotion is allowed. We cannot use 6705 /// UsualArithmeticConversions() for this purpose, since it always 6706 /// promotes promotable types. 6707 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6708 ExprResult &RHS, 6709 SourceLocation QuestionLoc) { 6710 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6711 if (LHS.isInvalid()) 6712 return QualType(); 6713 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6714 if (RHS.isInvalid()) 6715 return QualType(); 6716 6717 // For conversion purposes, we ignore any qualifiers. 6718 // For example, "const float" and "float" are equivalent. 6719 QualType LHSType = 6720 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6721 QualType RHSType = 6722 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6723 6724 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6725 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6726 << LHSType << LHS.get()->getSourceRange(); 6727 return QualType(); 6728 } 6729 6730 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6731 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6732 << RHSType << RHS.get()->getSourceRange(); 6733 return QualType(); 6734 } 6735 6736 // If both types are identical, no conversion is needed. 6737 if (LHSType == RHSType) 6738 return LHSType; 6739 6740 // Now handle "real" floating types (i.e. float, double, long double). 6741 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6742 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6743 /*IsCompAssign = */ false); 6744 6745 // Finally, we have two differing integer types. 6746 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6747 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6748 } 6749 6750 /// Convert scalar operands to a vector that matches the 6751 /// condition in length. 6752 /// 6753 /// Used when handling the OpenCL conditional operator where the 6754 /// condition is a vector while the other operands are scalar. 6755 /// 6756 /// We first compute the "result type" for the scalar operands 6757 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6758 /// into a vector of that type where the length matches the condition 6759 /// vector type. s6.11.6 requires that the element types of the result 6760 /// and the condition must have the same number of bits. 6761 static QualType 6762 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6763 QualType CondTy, SourceLocation QuestionLoc) { 6764 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6765 if (ResTy.isNull()) return QualType(); 6766 6767 const VectorType *CV = CondTy->getAs<VectorType>(); 6768 assert(CV); 6769 6770 // Determine the vector result type 6771 unsigned NumElements = CV->getNumElements(); 6772 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6773 6774 // Ensure that all types have the same number of bits 6775 if (S.Context.getTypeSize(CV->getElementType()) 6776 != S.Context.getTypeSize(ResTy)) { 6777 // Since VectorTy is created internally, it does not pretty print 6778 // with an OpenCL name. Instead, we just print a description. 6779 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6780 SmallString<64> Str; 6781 llvm::raw_svector_ostream OS(Str); 6782 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6783 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6784 << CondTy << OS.str(); 6785 return QualType(); 6786 } 6787 6788 // Convert operands to the vector result type 6789 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6790 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6791 6792 return VectorTy; 6793 } 6794 6795 /// Return false if this is a valid OpenCL condition vector 6796 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6797 SourceLocation QuestionLoc) { 6798 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6799 // integral type. 6800 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6801 assert(CondTy); 6802 QualType EleTy = CondTy->getElementType(); 6803 if (EleTy->isIntegerType()) return false; 6804 6805 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6806 << Cond->getType() << Cond->getSourceRange(); 6807 return true; 6808 } 6809 6810 /// Return false if the vector condition type and the vector 6811 /// result type are compatible. 6812 /// 6813 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6814 /// number of elements, and their element types have the same number 6815 /// of bits. 6816 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6817 SourceLocation QuestionLoc) { 6818 const VectorType *CV = CondTy->getAs<VectorType>(); 6819 const VectorType *RV = VecResTy->getAs<VectorType>(); 6820 assert(CV && RV); 6821 6822 if (CV->getNumElements() != RV->getNumElements()) { 6823 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6824 << CondTy << VecResTy; 6825 return true; 6826 } 6827 6828 QualType CVE = CV->getElementType(); 6829 QualType RVE = RV->getElementType(); 6830 6831 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6832 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6833 << CondTy << VecResTy; 6834 return true; 6835 } 6836 6837 return false; 6838 } 6839 6840 /// Return the resulting type for the conditional operator in 6841 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6842 /// s6.3.i) when the condition is a vector type. 6843 static QualType 6844 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6845 ExprResult &LHS, ExprResult &RHS, 6846 SourceLocation QuestionLoc) { 6847 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6848 if (Cond.isInvalid()) 6849 return QualType(); 6850 QualType CondTy = Cond.get()->getType(); 6851 6852 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6853 return QualType(); 6854 6855 // If either operand is a vector then find the vector type of the 6856 // result as specified in OpenCL v1.1 s6.3.i. 6857 if (LHS.get()->getType()->isVectorType() || 6858 RHS.get()->getType()->isVectorType()) { 6859 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6860 /*isCompAssign*/false, 6861 /*AllowBothBool*/true, 6862 /*AllowBoolConversions*/false); 6863 if (VecResTy.isNull()) return QualType(); 6864 // The result type must match the condition type as specified in 6865 // OpenCL v1.1 s6.11.6. 6866 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6867 return QualType(); 6868 return VecResTy; 6869 } 6870 6871 // Both operands are scalar. 6872 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6873 } 6874 6875 /// Return true if the Expr is block type 6876 static bool checkBlockType(Sema &S, const Expr *E) { 6877 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6878 QualType Ty = CE->getCallee()->getType(); 6879 if (Ty->isBlockPointerType()) { 6880 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6881 return true; 6882 } 6883 } 6884 return false; 6885 } 6886 6887 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6888 /// In that case, LHS = cond. 6889 /// C99 6.5.15 6890 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6891 ExprResult &RHS, ExprValueKind &VK, 6892 ExprObjectKind &OK, 6893 SourceLocation QuestionLoc) { 6894 6895 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6896 if (!LHSResult.isUsable()) return QualType(); 6897 LHS = LHSResult; 6898 6899 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6900 if (!RHSResult.isUsable()) return QualType(); 6901 RHS = RHSResult; 6902 6903 // C++ is sufficiently different to merit its own checker. 6904 if (getLangOpts().CPlusPlus) 6905 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6906 6907 VK = VK_RValue; 6908 OK = OK_Ordinary; 6909 6910 // The OpenCL operator with a vector condition is sufficiently 6911 // different to merit its own checker. 6912 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6913 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6914 6915 // First, check the condition. 6916 Cond = UsualUnaryConversions(Cond.get()); 6917 if (Cond.isInvalid()) 6918 return QualType(); 6919 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6920 return QualType(); 6921 6922 // Now check the two expressions. 6923 if (LHS.get()->getType()->isVectorType() || 6924 RHS.get()->getType()->isVectorType()) 6925 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6926 /*AllowBothBool*/true, 6927 /*AllowBoolConversions*/false); 6928 6929 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6930 if (LHS.isInvalid() || RHS.isInvalid()) 6931 return QualType(); 6932 6933 QualType LHSTy = LHS.get()->getType(); 6934 QualType RHSTy = RHS.get()->getType(); 6935 6936 // Diagnose attempts to convert between __float128 and long double where 6937 // such conversions currently can't be handled. 6938 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6939 Diag(QuestionLoc, 6940 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6941 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6942 return QualType(); 6943 } 6944 6945 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6946 // selection operator (?:). 6947 if (getLangOpts().OpenCL && 6948 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6949 return QualType(); 6950 } 6951 6952 // If both operands have arithmetic type, do the usual arithmetic conversions 6953 // to find a common type: C99 6.5.15p3,5. 6954 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6955 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6956 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6957 6958 return ResTy; 6959 } 6960 6961 // If both operands are the same structure or union type, the result is that 6962 // type. 6963 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6964 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6965 if (LHSRT->getDecl() == RHSRT->getDecl()) 6966 // "If both the operands have structure or union type, the result has 6967 // that type." This implies that CV qualifiers are dropped. 6968 return LHSTy.getUnqualifiedType(); 6969 // FIXME: Type of conditional expression must be complete in C mode. 6970 } 6971 6972 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6973 // The following || allows only one side to be void (a GCC-ism). 6974 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6975 return checkConditionalVoidType(*this, LHS, RHS); 6976 } 6977 6978 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6979 // the type of the other operand." 6980 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6981 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6982 6983 // All objective-c pointer type analysis is done here. 6984 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6985 QuestionLoc); 6986 if (LHS.isInvalid() || RHS.isInvalid()) 6987 return QualType(); 6988 if (!compositeType.isNull()) 6989 return compositeType; 6990 6991 6992 // Handle block pointer types. 6993 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6994 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6995 QuestionLoc); 6996 6997 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6998 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6999 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7000 QuestionLoc); 7001 7002 // GCC compatibility: soften pointer/integer mismatch. Note that 7003 // null pointers have been filtered out by this point. 7004 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7005 /*isIntFirstExpr=*/true)) 7006 return RHSTy; 7007 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7008 /*isIntFirstExpr=*/false)) 7009 return LHSTy; 7010 7011 // Emit a better diagnostic if one of the expressions is a null pointer 7012 // constant and the other is not a pointer type. In this case, the user most 7013 // likely forgot to take the address of the other expression. 7014 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7015 return QualType(); 7016 7017 // Otherwise, the operands are not compatible. 7018 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7019 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7020 << RHS.get()->getSourceRange(); 7021 return QualType(); 7022 } 7023 7024 /// FindCompositeObjCPointerType - Helper method to find composite type of 7025 /// two objective-c pointer types of the two input expressions. 7026 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7027 SourceLocation QuestionLoc) { 7028 QualType LHSTy = LHS.get()->getType(); 7029 QualType RHSTy = RHS.get()->getType(); 7030 7031 // Handle things like Class and struct objc_class*. Here we case the result 7032 // to the pseudo-builtin, because that will be implicitly cast back to the 7033 // redefinition type if an attempt is made to access its fields. 7034 if (LHSTy->isObjCClassType() && 7035 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7036 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7037 return LHSTy; 7038 } 7039 if (RHSTy->isObjCClassType() && 7040 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7041 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7042 return RHSTy; 7043 } 7044 // And the same for struct objc_object* / id 7045 if (LHSTy->isObjCIdType() && 7046 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7047 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7048 return LHSTy; 7049 } 7050 if (RHSTy->isObjCIdType() && 7051 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7052 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7053 return RHSTy; 7054 } 7055 // And the same for struct objc_selector* / SEL 7056 if (Context.isObjCSelType(LHSTy) && 7057 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7058 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7059 return LHSTy; 7060 } 7061 if (Context.isObjCSelType(RHSTy) && 7062 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7063 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7064 return RHSTy; 7065 } 7066 // Check constraints for Objective-C object pointers types. 7067 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7068 7069 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7070 // Two identical object pointer types are always compatible. 7071 return LHSTy; 7072 } 7073 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7074 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7075 QualType compositeType = LHSTy; 7076 7077 // If both operands are interfaces and either operand can be 7078 // assigned to the other, use that type as the composite 7079 // type. This allows 7080 // xxx ? (A*) a : (B*) b 7081 // where B is a subclass of A. 7082 // 7083 // Additionally, as for assignment, if either type is 'id' 7084 // allow silent coercion. Finally, if the types are 7085 // incompatible then make sure to use 'id' as the composite 7086 // type so the result is acceptable for sending messages to. 7087 7088 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7089 // It could return the composite type. 7090 if (!(compositeType = 7091 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7092 // Nothing more to do. 7093 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7094 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7095 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7096 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7097 } else if ((LHSTy->isObjCQualifiedIdType() || 7098 RHSTy->isObjCQualifiedIdType()) && 7099 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7100 // Need to handle "id<xx>" explicitly. 7101 // GCC allows qualified id and any Objective-C type to devolve to 7102 // id. Currently localizing to here until clear this should be 7103 // part of ObjCQualifiedIdTypesAreCompatible. 7104 compositeType = Context.getObjCIdType(); 7105 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7106 compositeType = Context.getObjCIdType(); 7107 } else { 7108 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7109 << LHSTy << RHSTy 7110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7111 QualType incompatTy = Context.getObjCIdType(); 7112 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7113 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7114 return incompatTy; 7115 } 7116 // The object pointer types are compatible. 7117 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7118 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7119 return compositeType; 7120 } 7121 // Check Objective-C object pointer types and 'void *' 7122 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7123 if (getLangOpts().ObjCAutoRefCount) { 7124 // ARC forbids the implicit conversion of object pointers to 'void *', 7125 // so these types are not compatible. 7126 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7127 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7128 LHS = RHS = true; 7129 return QualType(); 7130 } 7131 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7132 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7133 QualType destPointee 7134 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7135 QualType destType = Context.getPointerType(destPointee); 7136 // Add qualifiers if necessary. 7137 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7138 // Promote to void*. 7139 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7140 return destType; 7141 } 7142 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7143 if (getLangOpts().ObjCAutoRefCount) { 7144 // ARC forbids the implicit conversion of object pointers to 'void *', 7145 // so these types are not compatible. 7146 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7147 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7148 LHS = RHS = true; 7149 return QualType(); 7150 } 7151 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7152 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7153 QualType destPointee 7154 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7155 QualType destType = Context.getPointerType(destPointee); 7156 // Add qualifiers if necessary. 7157 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7158 // Promote to void*. 7159 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7160 return destType; 7161 } 7162 return QualType(); 7163 } 7164 7165 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7166 /// ParenRange in parentheses. 7167 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7168 const PartialDiagnostic &Note, 7169 SourceRange ParenRange) { 7170 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7171 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7172 EndLoc.isValid()) { 7173 Self.Diag(Loc, Note) 7174 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7175 << FixItHint::CreateInsertion(EndLoc, ")"); 7176 } else { 7177 // We can't display the parentheses, so just show the bare note. 7178 Self.Diag(Loc, Note) << ParenRange; 7179 } 7180 } 7181 7182 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7183 return BinaryOperator::isAdditiveOp(Opc) || 7184 BinaryOperator::isMultiplicativeOp(Opc) || 7185 BinaryOperator::isShiftOp(Opc); 7186 } 7187 7188 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7189 /// expression, either using a built-in or overloaded operator, 7190 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7191 /// expression. 7192 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7193 Expr **RHSExprs) { 7194 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7195 E = E->IgnoreImpCasts(); 7196 E = E->IgnoreConversionOperator(); 7197 E = E->IgnoreImpCasts(); 7198 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7199 E = MTE->GetTemporaryExpr(); 7200 E = E->IgnoreImpCasts(); 7201 } 7202 7203 // Built-in binary operator. 7204 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7205 if (IsArithmeticOp(OP->getOpcode())) { 7206 *Opcode = OP->getOpcode(); 7207 *RHSExprs = OP->getRHS(); 7208 return true; 7209 } 7210 } 7211 7212 // Overloaded operator. 7213 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7214 if (Call->getNumArgs() != 2) 7215 return false; 7216 7217 // Make sure this is really a binary operator that is safe to pass into 7218 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7219 OverloadedOperatorKind OO = Call->getOperator(); 7220 if (OO < OO_Plus || OO > OO_Arrow || 7221 OO == OO_PlusPlus || OO == OO_MinusMinus) 7222 return false; 7223 7224 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7225 if (IsArithmeticOp(OpKind)) { 7226 *Opcode = OpKind; 7227 *RHSExprs = Call->getArg(1); 7228 return true; 7229 } 7230 } 7231 7232 return false; 7233 } 7234 7235 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7236 /// or is a logical expression such as (x==y) which has int type, but is 7237 /// commonly interpreted as boolean. 7238 static bool ExprLooksBoolean(Expr *E) { 7239 E = E->IgnoreParenImpCasts(); 7240 7241 if (E->getType()->isBooleanType()) 7242 return true; 7243 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7244 return OP->isComparisonOp() || OP->isLogicalOp(); 7245 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7246 return OP->getOpcode() == UO_LNot; 7247 if (E->getType()->isPointerType()) 7248 return true; 7249 // FIXME: What about overloaded operator calls returning "unspecified boolean 7250 // type"s (commonly pointer-to-members)? 7251 7252 return false; 7253 } 7254 7255 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7256 /// and binary operator are mixed in a way that suggests the programmer assumed 7257 /// the conditional operator has higher precedence, for example: 7258 /// "int x = a + someBinaryCondition ? 1 : 2". 7259 static void DiagnoseConditionalPrecedence(Sema &Self, 7260 SourceLocation OpLoc, 7261 Expr *Condition, 7262 Expr *LHSExpr, 7263 Expr *RHSExpr) { 7264 BinaryOperatorKind CondOpcode; 7265 Expr *CondRHS; 7266 7267 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7268 return; 7269 if (!ExprLooksBoolean(CondRHS)) 7270 return; 7271 7272 // The condition is an arithmetic binary expression, with a right- 7273 // hand side that looks boolean, so warn. 7274 7275 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7276 << Condition->getSourceRange() 7277 << BinaryOperator::getOpcodeStr(CondOpcode); 7278 7279 SuggestParentheses( 7280 Self, OpLoc, 7281 Self.PDiag(diag::note_precedence_silence) 7282 << BinaryOperator::getOpcodeStr(CondOpcode), 7283 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7284 7285 SuggestParentheses(Self, OpLoc, 7286 Self.PDiag(diag::note_precedence_conditional_first), 7287 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7288 } 7289 7290 /// Compute the nullability of a conditional expression. 7291 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7292 QualType LHSTy, QualType RHSTy, 7293 ASTContext &Ctx) { 7294 if (!ResTy->isAnyPointerType()) 7295 return ResTy; 7296 7297 auto GetNullability = [&Ctx](QualType Ty) { 7298 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7299 if (Kind) 7300 return *Kind; 7301 return NullabilityKind::Unspecified; 7302 }; 7303 7304 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7305 NullabilityKind MergedKind; 7306 7307 // Compute nullability of a binary conditional expression. 7308 if (IsBin) { 7309 if (LHSKind == NullabilityKind::NonNull) 7310 MergedKind = NullabilityKind::NonNull; 7311 else 7312 MergedKind = RHSKind; 7313 // Compute nullability of a normal conditional expression. 7314 } else { 7315 if (LHSKind == NullabilityKind::Nullable || 7316 RHSKind == NullabilityKind::Nullable) 7317 MergedKind = NullabilityKind::Nullable; 7318 else if (LHSKind == NullabilityKind::NonNull) 7319 MergedKind = RHSKind; 7320 else if (RHSKind == NullabilityKind::NonNull) 7321 MergedKind = LHSKind; 7322 else 7323 MergedKind = NullabilityKind::Unspecified; 7324 } 7325 7326 // Return if ResTy already has the correct nullability. 7327 if (GetNullability(ResTy) == MergedKind) 7328 return ResTy; 7329 7330 // Strip all nullability from ResTy. 7331 while (ResTy->getNullability(Ctx)) 7332 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7333 7334 // Create a new AttributedType with the new nullability kind. 7335 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7336 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7337 } 7338 7339 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7340 /// in the case of a the GNU conditional expr extension. 7341 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7342 SourceLocation ColonLoc, 7343 Expr *CondExpr, Expr *LHSExpr, 7344 Expr *RHSExpr) { 7345 if (!getLangOpts().CPlusPlus) { 7346 // C cannot handle TypoExpr nodes in the condition because it 7347 // doesn't handle dependent types properly, so make sure any TypoExprs have 7348 // been dealt with before checking the operands. 7349 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7350 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7351 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7352 7353 if (!CondResult.isUsable()) 7354 return ExprError(); 7355 7356 if (LHSExpr) { 7357 if (!LHSResult.isUsable()) 7358 return ExprError(); 7359 } 7360 7361 if (!RHSResult.isUsable()) 7362 return ExprError(); 7363 7364 CondExpr = CondResult.get(); 7365 LHSExpr = LHSResult.get(); 7366 RHSExpr = RHSResult.get(); 7367 } 7368 7369 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7370 // was the condition. 7371 OpaqueValueExpr *opaqueValue = nullptr; 7372 Expr *commonExpr = nullptr; 7373 if (!LHSExpr) { 7374 commonExpr = CondExpr; 7375 // Lower out placeholder types first. This is important so that we don't 7376 // try to capture a placeholder. This happens in few cases in C++; such 7377 // as Objective-C++'s dictionary subscripting syntax. 7378 if (commonExpr->hasPlaceholderType()) { 7379 ExprResult result = CheckPlaceholderExpr(commonExpr); 7380 if (!result.isUsable()) return ExprError(); 7381 commonExpr = result.get(); 7382 } 7383 // We usually want to apply unary conversions *before* saving, except 7384 // in the special case of a C++ l-value conditional. 7385 if (!(getLangOpts().CPlusPlus 7386 && !commonExpr->isTypeDependent() 7387 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7388 && commonExpr->isGLValue() 7389 && commonExpr->isOrdinaryOrBitFieldObject() 7390 && RHSExpr->isOrdinaryOrBitFieldObject() 7391 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7392 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7393 if (commonRes.isInvalid()) 7394 return ExprError(); 7395 commonExpr = commonRes.get(); 7396 } 7397 7398 // If the common expression is a class or array prvalue, materialize it 7399 // so that we can safely refer to it multiple times. 7400 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7401 commonExpr->getType()->isArrayType())) { 7402 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7403 if (MatExpr.isInvalid()) 7404 return ExprError(); 7405 commonExpr = MatExpr.get(); 7406 } 7407 7408 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7409 commonExpr->getType(), 7410 commonExpr->getValueKind(), 7411 commonExpr->getObjectKind(), 7412 commonExpr); 7413 LHSExpr = CondExpr = opaqueValue; 7414 } 7415 7416 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7417 ExprValueKind VK = VK_RValue; 7418 ExprObjectKind OK = OK_Ordinary; 7419 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7420 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7421 VK, OK, QuestionLoc); 7422 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7423 RHS.isInvalid()) 7424 return ExprError(); 7425 7426 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7427 RHS.get()); 7428 7429 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7430 7431 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7432 Context); 7433 7434 if (!commonExpr) 7435 return new (Context) 7436 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7437 RHS.get(), result, VK, OK); 7438 7439 return new (Context) BinaryConditionalOperator( 7440 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7441 ColonLoc, result, VK, OK); 7442 } 7443 7444 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7445 // being closely modeled after the C99 spec:-). The odd characteristic of this 7446 // routine is it effectively iqnores the qualifiers on the top level pointee. 7447 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7448 // FIXME: add a couple examples in this comment. 7449 static Sema::AssignConvertType 7450 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7451 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7452 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7453 7454 // get the "pointed to" type (ignoring qualifiers at the top level) 7455 const Type *lhptee, *rhptee; 7456 Qualifiers lhq, rhq; 7457 std::tie(lhptee, lhq) = 7458 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7459 std::tie(rhptee, rhq) = 7460 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7461 7462 Sema::AssignConvertType ConvTy = Sema::Compatible; 7463 7464 // C99 6.5.16.1p1: This following citation is common to constraints 7465 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7466 // qualifiers of the type *pointed to* by the right; 7467 7468 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7469 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7470 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7471 // Ignore lifetime for further calculation. 7472 lhq.removeObjCLifetime(); 7473 rhq.removeObjCLifetime(); 7474 } 7475 7476 if (!lhq.compatiblyIncludes(rhq)) { 7477 // Treat address-space mismatches as fatal. TODO: address subspaces 7478 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7479 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7480 7481 // It's okay to add or remove GC or lifetime qualifiers when converting to 7482 // and from void*. 7483 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7484 .compatiblyIncludes( 7485 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7486 && (lhptee->isVoidType() || rhptee->isVoidType())) 7487 ; // keep old 7488 7489 // Treat lifetime mismatches as fatal. 7490 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7491 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7492 7493 // For GCC/MS compatibility, other qualifier mismatches are treated 7494 // as still compatible in C. 7495 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7496 } 7497 7498 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7499 // incomplete type and the other is a pointer to a qualified or unqualified 7500 // version of void... 7501 if (lhptee->isVoidType()) { 7502 if (rhptee->isIncompleteOrObjectType()) 7503 return ConvTy; 7504 7505 // As an extension, we allow cast to/from void* to function pointer. 7506 assert(rhptee->isFunctionType()); 7507 return Sema::FunctionVoidPointer; 7508 } 7509 7510 if (rhptee->isVoidType()) { 7511 if (lhptee->isIncompleteOrObjectType()) 7512 return ConvTy; 7513 7514 // As an extension, we allow cast to/from void* to function pointer. 7515 assert(lhptee->isFunctionType()); 7516 return Sema::FunctionVoidPointer; 7517 } 7518 7519 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7520 // unqualified versions of compatible types, ... 7521 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7522 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7523 // Check if the pointee types are compatible ignoring the sign. 7524 // We explicitly check for char so that we catch "char" vs 7525 // "unsigned char" on systems where "char" is unsigned. 7526 if (lhptee->isCharType()) 7527 ltrans = S.Context.UnsignedCharTy; 7528 else if (lhptee->hasSignedIntegerRepresentation()) 7529 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7530 7531 if (rhptee->isCharType()) 7532 rtrans = S.Context.UnsignedCharTy; 7533 else if (rhptee->hasSignedIntegerRepresentation()) 7534 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7535 7536 if (ltrans == rtrans) { 7537 // Types are compatible ignoring the sign. Qualifier incompatibility 7538 // takes priority over sign incompatibility because the sign 7539 // warning can be disabled. 7540 if (ConvTy != Sema::Compatible) 7541 return ConvTy; 7542 7543 return Sema::IncompatiblePointerSign; 7544 } 7545 7546 // If we are a multi-level pointer, it's possible that our issue is simply 7547 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7548 // the eventual target type is the same and the pointers have the same 7549 // level of indirection, this must be the issue. 7550 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7551 do { 7552 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7553 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7554 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7555 7556 if (lhptee == rhptee) 7557 return Sema::IncompatibleNestedPointerQualifiers; 7558 } 7559 7560 // General pointer incompatibility takes priority over qualifiers. 7561 return Sema::IncompatiblePointer; 7562 } 7563 if (!S.getLangOpts().CPlusPlus && 7564 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7565 return Sema::IncompatiblePointer; 7566 return ConvTy; 7567 } 7568 7569 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7570 /// block pointer types are compatible or whether a block and normal pointer 7571 /// are compatible. It is more restrict than comparing two function pointer 7572 // types. 7573 static Sema::AssignConvertType 7574 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7575 QualType RHSType) { 7576 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7577 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7578 7579 QualType lhptee, rhptee; 7580 7581 // get the "pointed to" type (ignoring qualifiers at the top level) 7582 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7583 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7584 7585 // In C++, the types have to match exactly. 7586 if (S.getLangOpts().CPlusPlus) 7587 return Sema::IncompatibleBlockPointer; 7588 7589 Sema::AssignConvertType ConvTy = Sema::Compatible; 7590 7591 // For blocks we enforce that qualifiers are identical. 7592 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7593 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7594 if (S.getLangOpts().OpenCL) { 7595 LQuals.removeAddressSpace(); 7596 RQuals.removeAddressSpace(); 7597 } 7598 if (LQuals != RQuals) 7599 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7600 7601 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7602 // assignment. 7603 // The current behavior is similar to C++ lambdas. A block might be 7604 // assigned to a variable iff its return type and parameters are compatible 7605 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7606 // an assignment. Presumably it should behave in way that a function pointer 7607 // assignment does in C, so for each parameter and return type: 7608 // * CVR and address space of LHS should be a superset of CVR and address 7609 // space of RHS. 7610 // * unqualified types should be compatible. 7611 if (S.getLangOpts().OpenCL) { 7612 if (!S.Context.typesAreBlockPointerCompatible( 7613 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7614 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7615 return Sema::IncompatibleBlockPointer; 7616 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7617 return Sema::IncompatibleBlockPointer; 7618 7619 return ConvTy; 7620 } 7621 7622 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7623 /// for assignment compatibility. 7624 static Sema::AssignConvertType 7625 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7626 QualType RHSType) { 7627 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7628 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7629 7630 if (LHSType->isObjCBuiltinType()) { 7631 // Class is not compatible with ObjC object pointers. 7632 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7633 !RHSType->isObjCQualifiedClassType()) 7634 return Sema::IncompatiblePointer; 7635 return Sema::Compatible; 7636 } 7637 if (RHSType->isObjCBuiltinType()) { 7638 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7639 !LHSType->isObjCQualifiedClassType()) 7640 return Sema::IncompatiblePointer; 7641 return Sema::Compatible; 7642 } 7643 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7644 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7645 7646 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7647 // make an exception for id<P> 7648 !LHSType->isObjCQualifiedIdType()) 7649 return Sema::CompatiblePointerDiscardsQualifiers; 7650 7651 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7652 return Sema::Compatible; 7653 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7654 return Sema::IncompatibleObjCQualifiedId; 7655 return Sema::IncompatiblePointer; 7656 } 7657 7658 Sema::AssignConvertType 7659 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7660 QualType LHSType, QualType RHSType) { 7661 // Fake up an opaque expression. We don't actually care about what 7662 // cast operations are required, so if CheckAssignmentConstraints 7663 // adds casts to this they'll be wasted, but fortunately that doesn't 7664 // usually happen on valid code. 7665 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7666 ExprResult RHSPtr = &RHSExpr; 7667 CastKind K; 7668 7669 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7670 } 7671 7672 /// This helper function returns true if QT is a vector type that has element 7673 /// type ElementType. 7674 static bool isVector(QualType QT, QualType ElementType) { 7675 if (const VectorType *VT = QT->getAs<VectorType>()) 7676 return VT->getElementType() == ElementType; 7677 return false; 7678 } 7679 7680 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7681 /// has code to accommodate several GCC extensions when type checking 7682 /// pointers. Here are some objectionable examples that GCC considers warnings: 7683 /// 7684 /// int a, *pint; 7685 /// short *pshort; 7686 /// struct foo *pfoo; 7687 /// 7688 /// pint = pshort; // warning: assignment from incompatible pointer type 7689 /// a = pint; // warning: assignment makes integer from pointer without a cast 7690 /// pint = a; // warning: assignment makes pointer from integer without a cast 7691 /// pint = pfoo; // warning: assignment from incompatible pointer type 7692 /// 7693 /// As a result, the code for dealing with pointers is more complex than the 7694 /// C99 spec dictates. 7695 /// 7696 /// Sets 'Kind' for any result kind except Incompatible. 7697 Sema::AssignConvertType 7698 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7699 CastKind &Kind, bool ConvertRHS) { 7700 QualType RHSType = RHS.get()->getType(); 7701 QualType OrigLHSType = LHSType; 7702 7703 // Get canonical types. We're not formatting these types, just comparing 7704 // them. 7705 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7706 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7707 7708 // Common case: no conversion required. 7709 if (LHSType == RHSType) { 7710 Kind = CK_NoOp; 7711 return Compatible; 7712 } 7713 7714 // If we have an atomic type, try a non-atomic assignment, then just add an 7715 // atomic qualification step. 7716 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7717 Sema::AssignConvertType result = 7718 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7719 if (result != Compatible) 7720 return result; 7721 if (Kind != CK_NoOp && ConvertRHS) 7722 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7723 Kind = CK_NonAtomicToAtomic; 7724 return Compatible; 7725 } 7726 7727 // If the left-hand side is a reference type, then we are in a 7728 // (rare!) case where we've allowed the use of references in C, 7729 // e.g., as a parameter type in a built-in function. In this case, 7730 // just make sure that the type referenced is compatible with the 7731 // right-hand side type. The caller is responsible for adjusting 7732 // LHSType so that the resulting expression does not have reference 7733 // type. 7734 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7735 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7736 Kind = CK_LValueBitCast; 7737 return Compatible; 7738 } 7739 return Incompatible; 7740 } 7741 7742 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7743 // to the same ExtVector type. 7744 if (LHSType->isExtVectorType()) { 7745 if (RHSType->isExtVectorType()) 7746 return Incompatible; 7747 if (RHSType->isArithmeticType()) { 7748 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7749 if (ConvertRHS) 7750 RHS = prepareVectorSplat(LHSType, RHS.get()); 7751 Kind = CK_VectorSplat; 7752 return Compatible; 7753 } 7754 } 7755 7756 // Conversions to or from vector type. 7757 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7758 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7759 // Allow assignments of an AltiVec vector type to an equivalent GCC 7760 // vector type and vice versa 7761 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7762 Kind = CK_BitCast; 7763 return Compatible; 7764 } 7765 7766 // If we are allowing lax vector conversions, and LHS and RHS are both 7767 // vectors, the total size only needs to be the same. This is a bitcast; 7768 // no bits are changed but the result type is different. 7769 if (isLaxVectorConversion(RHSType, LHSType)) { 7770 Kind = CK_BitCast; 7771 return IncompatibleVectors; 7772 } 7773 } 7774 7775 // When the RHS comes from another lax conversion (e.g. binops between 7776 // scalars and vectors) the result is canonicalized as a vector. When the 7777 // LHS is also a vector, the lax is allowed by the condition above. Handle 7778 // the case where LHS is a scalar. 7779 if (LHSType->isScalarType()) { 7780 const VectorType *VecType = RHSType->getAs<VectorType>(); 7781 if (VecType && VecType->getNumElements() == 1 && 7782 isLaxVectorConversion(RHSType, LHSType)) { 7783 ExprResult *VecExpr = &RHS; 7784 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7785 Kind = CK_BitCast; 7786 return Compatible; 7787 } 7788 } 7789 7790 return Incompatible; 7791 } 7792 7793 // Diagnose attempts to convert between __float128 and long double where 7794 // such conversions currently can't be handled. 7795 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7796 return Incompatible; 7797 7798 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7799 // discards the imaginary part. 7800 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7801 !LHSType->getAs<ComplexType>()) 7802 return Incompatible; 7803 7804 // Arithmetic conversions. 7805 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7806 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7807 if (ConvertRHS) 7808 Kind = PrepareScalarCast(RHS, LHSType); 7809 return Compatible; 7810 } 7811 7812 // Conversions to normal pointers. 7813 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7814 // U* -> T* 7815 if (isa<PointerType>(RHSType)) { 7816 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7817 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7818 if (AddrSpaceL != AddrSpaceR) 7819 Kind = CK_AddressSpaceConversion; 7820 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 7821 Kind = CK_NoOp; 7822 else 7823 Kind = CK_BitCast; 7824 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7825 } 7826 7827 // int -> T* 7828 if (RHSType->isIntegerType()) { 7829 Kind = CK_IntegralToPointer; // FIXME: null? 7830 return IntToPointer; 7831 } 7832 7833 // C pointers are not compatible with ObjC object pointers, 7834 // with two exceptions: 7835 if (isa<ObjCObjectPointerType>(RHSType)) { 7836 // - conversions to void* 7837 if (LHSPointer->getPointeeType()->isVoidType()) { 7838 Kind = CK_BitCast; 7839 return Compatible; 7840 } 7841 7842 // - conversions from 'Class' to the redefinition type 7843 if (RHSType->isObjCClassType() && 7844 Context.hasSameType(LHSType, 7845 Context.getObjCClassRedefinitionType())) { 7846 Kind = CK_BitCast; 7847 return Compatible; 7848 } 7849 7850 Kind = CK_BitCast; 7851 return IncompatiblePointer; 7852 } 7853 7854 // U^ -> void* 7855 if (RHSType->getAs<BlockPointerType>()) { 7856 if (LHSPointer->getPointeeType()->isVoidType()) { 7857 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7858 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7859 ->getPointeeType() 7860 .getAddressSpace(); 7861 Kind = 7862 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7863 return Compatible; 7864 } 7865 } 7866 7867 return Incompatible; 7868 } 7869 7870 // Conversions to block pointers. 7871 if (isa<BlockPointerType>(LHSType)) { 7872 // U^ -> T^ 7873 if (RHSType->isBlockPointerType()) { 7874 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7875 ->getPointeeType() 7876 .getAddressSpace(); 7877 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7878 ->getPointeeType() 7879 .getAddressSpace(); 7880 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7881 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7882 } 7883 7884 // int or null -> T^ 7885 if (RHSType->isIntegerType()) { 7886 Kind = CK_IntegralToPointer; // FIXME: null 7887 return IntToBlockPointer; 7888 } 7889 7890 // id -> T^ 7891 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 7892 Kind = CK_AnyPointerToBlockPointerCast; 7893 return Compatible; 7894 } 7895 7896 // void* -> T^ 7897 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7898 if (RHSPT->getPointeeType()->isVoidType()) { 7899 Kind = CK_AnyPointerToBlockPointerCast; 7900 return Compatible; 7901 } 7902 7903 return Incompatible; 7904 } 7905 7906 // Conversions to Objective-C pointers. 7907 if (isa<ObjCObjectPointerType>(LHSType)) { 7908 // A* -> B* 7909 if (RHSType->isObjCObjectPointerType()) { 7910 Kind = CK_BitCast; 7911 Sema::AssignConvertType result = 7912 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7913 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7914 result == Compatible && 7915 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7916 result = IncompatibleObjCWeakRef; 7917 return result; 7918 } 7919 7920 // int or null -> A* 7921 if (RHSType->isIntegerType()) { 7922 Kind = CK_IntegralToPointer; // FIXME: null 7923 return IntToPointer; 7924 } 7925 7926 // In general, C pointers are not compatible with ObjC object pointers, 7927 // with two exceptions: 7928 if (isa<PointerType>(RHSType)) { 7929 Kind = CK_CPointerToObjCPointerCast; 7930 7931 // - conversions from 'void*' 7932 if (RHSType->isVoidPointerType()) { 7933 return Compatible; 7934 } 7935 7936 // - conversions to 'Class' from its redefinition type 7937 if (LHSType->isObjCClassType() && 7938 Context.hasSameType(RHSType, 7939 Context.getObjCClassRedefinitionType())) { 7940 return Compatible; 7941 } 7942 7943 return IncompatiblePointer; 7944 } 7945 7946 // Only under strict condition T^ is compatible with an Objective-C pointer. 7947 if (RHSType->isBlockPointerType() && 7948 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7949 if (ConvertRHS) 7950 maybeExtendBlockObject(RHS); 7951 Kind = CK_BlockPointerToObjCPointerCast; 7952 return Compatible; 7953 } 7954 7955 return Incompatible; 7956 } 7957 7958 // Conversions from pointers that are not covered by the above. 7959 if (isa<PointerType>(RHSType)) { 7960 // T* -> _Bool 7961 if (LHSType == Context.BoolTy) { 7962 Kind = CK_PointerToBoolean; 7963 return Compatible; 7964 } 7965 7966 // T* -> int 7967 if (LHSType->isIntegerType()) { 7968 Kind = CK_PointerToIntegral; 7969 return PointerToInt; 7970 } 7971 7972 return Incompatible; 7973 } 7974 7975 // Conversions from Objective-C pointers that are not covered by the above. 7976 if (isa<ObjCObjectPointerType>(RHSType)) { 7977 // T* -> _Bool 7978 if (LHSType == Context.BoolTy) { 7979 Kind = CK_PointerToBoolean; 7980 return Compatible; 7981 } 7982 7983 // T* -> int 7984 if (LHSType->isIntegerType()) { 7985 Kind = CK_PointerToIntegral; 7986 return PointerToInt; 7987 } 7988 7989 return Incompatible; 7990 } 7991 7992 // struct A -> struct B 7993 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7994 if (Context.typesAreCompatible(LHSType, RHSType)) { 7995 Kind = CK_NoOp; 7996 return Compatible; 7997 } 7998 } 7999 8000 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8001 Kind = CK_IntToOCLSampler; 8002 return Compatible; 8003 } 8004 8005 return Incompatible; 8006 } 8007 8008 /// Constructs a transparent union from an expression that is 8009 /// used to initialize the transparent union. 8010 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8011 ExprResult &EResult, QualType UnionType, 8012 FieldDecl *Field) { 8013 // Build an initializer list that designates the appropriate member 8014 // of the transparent union. 8015 Expr *E = EResult.get(); 8016 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8017 E, SourceLocation()); 8018 Initializer->setType(UnionType); 8019 Initializer->setInitializedFieldInUnion(Field); 8020 8021 // Build a compound literal constructing a value of the transparent 8022 // union type from this initializer list. 8023 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8024 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8025 VK_RValue, Initializer, false); 8026 } 8027 8028 Sema::AssignConvertType 8029 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8030 ExprResult &RHS) { 8031 QualType RHSType = RHS.get()->getType(); 8032 8033 // If the ArgType is a Union type, we want to handle a potential 8034 // transparent_union GCC extension. 8035 const RecordType *UT = ArgType->getAsUnionType(); 8036 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8037 return Incompatible; 8038 8039 // The field to initialize within the transparent union. 8040 RecordDecl *UD = UT->getDecl(); 8041 FieldDecl *InitField = nullptr; 8042 // It's compatible if the expression matches any of the fields. 8043 for (auto *it : UD->fields()) { 8044 if (it->getType()->isPointerType()) { 8045 // If the transparent union contains a pointer type, we allow: 8046 // 1) void pointer 8047 // 2) null pointer constant 8048 if (RHSType->isPointerType()) 8049 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8050 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8051 InitField = it; 8052 break; 8053 } 8054 8055 if (RHS.get()->isNullPointerConstant(Context, 8056 Expr::NPC_ValueDependentIsNull)) { 8057 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8058 CK_NullToPointer); 8059 InitField = it; 8060 break; 8061 } 8062 } 8063 8064 CastKind Kind; 8065 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8066 == Compatible) { 8067 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8068 InitField = it; 8069 break; 8070 } 8071 } 8072 8073 if (!InitField) 8074 return Incompatible; 8075 8076 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8077 return Compatible; 8078 } 8079 8080 Sema::AssignConvertType 8081 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8082 bool Diagnose, 8083 bool DiagnoseCFAudited, 8084 bool ConvertRHS) { 8085 // We need to be able to tell the caller whether we diagnosed a problem, if 8086 // they ask us to issue diagnostics. 8087 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8088 8089 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8090 // we can't avoid *all* modifications at the moment, so we need some somewhere 8091 // to put the updated value. 8092 ExprResult LocalRHS = CallerRHS; 8093 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8094 8095 if (getLangOpts().CPlusPlus) { 8096 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8097 // C++ 5.17p3: If the left operand is not of class type, the 8098 // expression is implicitly converted (C++ 4) to the 8099 // cv-unqualified type of the left operand. 8100 QualType RHSType = RHS.get()->getType(); 8101 if (Diagnose) { 8102 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8103 AA_Assigning); 8104 } else { 8105 ImplicitConversionSequence ICS = 8106 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8107 /*SuppressUserConversions=*/false, 8108 /*AllowExplicit=*/false, 8109 /*InOverloadResolution=*/false, 8110 /*CStyle=*/false, 8111 /*AllowObjCWritebackConversion=*/false); 8112 if (ICS.isFailure()) 8113 return Incompatible; 8114 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8115 ICS, AA_Assigning); 8116 } 8117 if (RHS.isInvalid()) 8118 return Incompatible; 8119 Sema::AssignConvertType result = Compatible; 8120 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8121 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8122 result = IncompatibleObjCWeakRef; 8123 return result; 8124 } 8125 8126 // FIXME: Currently, we fall through and treat C++ classes like C 8127 // structures. 8128 // FIXME: We also fall through for atomics; not sure what should 8129 // happen there, though. 8130 } else if (RHS.get()->getType() == Context.OverloadTy) { 8131 // As a set of extensions to C, we support overloading on functions. These 8132 // functions need to be resolved here. 8133 DeclAccessPair DAP; 8134 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8135 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8136 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8137 else 8138 return Incompatible; 8139 } 8140 8141 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8142 // a null pointer constant. 8143 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8144 LHSType->isBlockPointerType()) && 8145 RHS.get()->isNullPointerConstant(Context, 8146 Expr::NPC_ValueDependentIsNull)) { 8147 if (Diagnose || ConvertRHS) { 8148 CastKind Kind; 8149 CXXCastPath Path; 8150 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8151 /*IgnoreBaseAccess=*/false, Diagnose); 8152 if (ConvertRHS) 8153 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8154 } 8155 return Compatible; 8156 } 8157 8158 // OpenCL queue_t type assignment. 8159 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8160 Context, Expr::NPC_ValueDependentIsNull)) { 8161 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8162 return Compatible; 8163 } 8164 8165 // This check seems unnatural, however it is necessary to ensure the proper 8166 // conversion of functions/arrays. If the conversion were done for all 8167 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8168 // expressions that suppress this implicit conversion (&, sizeof). 8169 // 8170 // Suppress this for references: C++ 8.5.3p5. 8171 if (!LHSType->isReferenceType()) { 8172 // FIXME: We potentially allocate here even if ConvertRHS is false. 8173 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8174 if (RHS.isInvalid()) 8175 return Incompatible; 8176 } 8177 CastKind Kind; 8178 Sema::AssignConvertType result = 8179 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8180 8181 // C99 6.5.16.1p2: The value of the right operand is converted to the 8182 // type of the assignment expression. 8183 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8184 // so that we can use references in built-in functions even in C. 8185 // The getNonReferenceType() call makes sure that the resulting expression 8186 // does not have reference type. 8187 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8188 QualType Ty = LHSType.getNonLValueExprType(Context); 8189 Expr *E = RHS.get(); 8190 8191 // Check for various Objective-C errors. If we are not reporting 8192 // diagnostics and just checking for errors, e.g., during overload 8193 // resolution, return Incompatible to indicate the failure. 8194 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8195 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8196 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8197 if (!Diagnose) 8198 return Incompatible; 8199 } 8200 if (getLangOpts().ObjC && 8201 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8202 E->getType(), E, Diagnose) || 8203 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8204 if (!Diagnose) 8205 return Incompatible; 8206 // Replace the expression with a corrected version and continue so we 8207 // can find further errors. 8208 RHS = E; 8209 return Compatible; 8210 } 8211 8212 if (ConvertRHS) 8213 RHS = ImpCastExprToType(E, Ty, Kind); 8214 } 8215 return result; 8216 } 8217 8218 namespace { 8219 /// The original operand to an operator, prior to the application of the usual 8220 /// arithmetic conversions and converting the arguments of a builtin operator 8221 /// candidate. 8222 struct OriginalOperand { 8223 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8224 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8225 Op = MTE->GetTemporaryExpr(); 8226 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8227 Op = BTE->getSubExpr(); 8228 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8229 Orig = ICE->getSubExprAsWritten(); 8230 Conversion = ICE->getConversionFunction(); 8231 } 8232 } 8233 8234 QualType getType() const { return Orig->getType(); } 8235 8236 Expr *Orig; 8237 NamedDecl *Conversion; 8238 }; 8239 } 8240 8241 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8242 ExprResult &RHS) { 8243 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8244 8245 Diag(Loc, diag::err_typecheck_invalid_operands) 8246 << OrigLHS.getType() << OrigRHS.getType() 8247 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8248 8249 // If a user-defined conversion was applied to either of the operands prior 8250 // to applying the built-in operator rules, tell the user about it. 8251 if (OrigLHS.Conversion) { 8252 Diag(OrigLHS.Conversion->getLocation(), 8253 diag::note_typecheck_invalid_operands_converted) 8254 << 0 << LHS.get()->getType(); 8255 } 8256 if (OrigRHS.Conversion) { 8257 Diag(OrigRHS.Conversion->getLocation(), 8258 diag::note_typecheck_invalid_operands_converted) 8259 << 1 << RHS.get()->getType(); 8260 } 8261 8262 return QualType(); 8263 } 8264 8265 // Diagnose cases where a scalar was implicitly converted to a vector and 8266 // diagnose the underlying types. Otherwise, diagnose the error 8267 // as invalid vector logical operands for non-C++ cases. 8268 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8269 ExprResult &RHS) { 8270 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8271 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8272 8273 bool LHSNatVec = LHSType->isVectorType(); 8274 bool RHSNatVec = RHSType->isVectorType(); 8275 8276 if (!(LHSNatVec && RHSNatVec)) { 8277 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8278 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8279 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8280 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8281 << Vector->getSourceRange(); 8282 return QualType(); 8283 } 8284 8285 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8286 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8287 << RHS.get()->getSourceRange(); 8288 8289 return QualType(); 8290 } 8291 8292 /// Try to convert a value of non-vector type to a vector type by converting 8293 /// the type to the element type of the vector and then performing a splat. 8294 /// If the language is OpenCL, we only use conversions that promote scalar 8295 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8296 /// for float->int. 8297 /// 8298 /// OpenCL V2.0 6.2.6.p2: 8299 /// An error shall occur if any scalar operand type has greater rank 8300 /// than the type of the vector element. 8301 /// 8302 /// \param scalar - if non-null, actually perform the conversions 8303 /// \return true if the operation fails (but without diagnosing the failure) 8304 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8305 QualType scalarTy, 8306 QualType vectorEltTy, 8307 QualType vectorTy, 8308 unsigned &DiagID) { 8309 // The conversion to apply to the scalar before splatting it, 8310 // if necessary. 8311 CastKind scalarCast = CK_NoOp; 8312 8313 if (vectorEltTy->isIntegralType(S.Context)) { 8314 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8315 (scalarTy->isIntegerType() && 8316 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8317 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8318 return true; 8319 } 8320 if (!scalarTy->isIntegralType(S.Context)) 8321 return true; 8322 scalarCast = CK_IntegralCast; 8323 } else if (vectorEltTy->isRealFloatingType()) { 8324 if (scalarTy->isRealFloatingType()) { 8325 if (S.getLangOpts().OpenCL && 8326 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8327 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8328 return true; 8329 } 8330 scalarCast = CK_FloatingCast; 8331 } 8332 else if (scalarTy->isIntegralType(S.Context)) 8333 scalarCast = CK_IntegralToFloating; 8334 else 8335 return true; 8336 } else { 8337 return true; 8338 } 8339 8340 // Adjust scalar if desired. 8341 if (scalar) { 8342 if (scalarCast != CK_NoOp) 8343 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8344 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8345 } 8346 return false; 8347 } 8348 8349 /// Convert vector E to a vector with the same number of elements but different 8350 /// element type. 8351 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8352 const auto *VecTy = E->getType()->getAs<VectorType>(); 8353 assert(VecTy && "Expression E must be a vector"); 8354 QualType NewVecTy = S.Context.getVectorType(ElementType, 8355 VecTy->getNumElements(), 8356 VecTy->getVectorKind()); 8357 8358 // Look through the implicit cast. Return the subexpression if its type is 8359 // NewVecTy. 8360 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8361 if (ICE->getSubExpr()->getType() == NewVecTy) 8362 return ICE->getSubExpr(); 8363 8364 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8365 return S.ImpCastExprToType(E, NewVecTy, Cast); 8366 } 8367 8368 /// Test if a (constant) integer Int can be casted to another integer type 8369 /// IntTy without losing precision. 8370 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8371 QualType OtherIntTy) { 8372 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8373 8374 // Reject cases where the value of the Int is unknown as that would 8375 // possibly cause truncation, but accept cases where the scalar can be 8376 // demoted without loss of precision. 8377 llvm::APSInt Result; 8378 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8379 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8380 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8381 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8382 8383 if (CstInt) { 8384 // If the scalar is constant and is of a higher order and has more active 8385 // bits that the vector element type, reject it. 8386 unsigned NumBits = IntSigned 8387 ? (Result.isNegative() ? Result.getMinSignedBits() 8388 : Result.getActiveBits()) 8389 : Result.getActiveBits(); 8390 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8391 return true; 8392 8393 // If the signedness of the scalar type and the vector element type 8394 // differs and the number of bits is greater than that of the vector 8395 // element reject it. 8396 return (IntSigned != OtherIntSigned && 8397 NumBits > S.Context.getIntWidth(OtherIntTy)); 8398 } 8399 8400 // Reject cases where the value of the scalar is not constant and it's 8401 // order is greater than that of the vector element type. 8402 return (Order < 0); 8403 } 8404 8405 /// Test if a (constant) integer Int can be casted to floating point type 8406 /// FloatTy without losing precision. 8407 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8408 QualType FloatTy) { 8409 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8410 8411 // Determine if the integer constant can be expressed as a floating point 8412 // number of the appropriate type. 8413 llvm::APSInt Result; 8414 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8415 uint64_t Bits = 0; 8416 if (CstInt) { 8417 // Reject constants that would be truncated if they were converted to 8418 // the floating point type. Test by simple to/from conversion. 8419 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8420 // could be avoided if there was a convertFromAPInt method 8421 // which could signal back if implicit truncation occurred. 8422 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8423 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8424 llvm::APFloat::rmTowardZero); 8425 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8426 !IntTy->hasSignedIntegerRepresentation()); 8427 bool Ignored = false; 8428 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8429 &Ignored); 8430 if (Result != ConvertBack) 8431 return true; 8432 } else { 8433 // Reject types that cannot be fully encoded into the mantissa of 8434 // the float. 8435 Bits = S.Context.getTypeSize(IntTy); 8436 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8437 S.Context.getFloatTypeSemantics(FloatTy)); 8438 if (Bits > FloatPrec) 8439 return true; 8440 } 8441 8442 return false; 8443 } 8444 8445 /// Attempt to convert and splat Scalar into a vector whose types matches 8446 /// Vector following GCC conversion rules. The rule is that implicit 8447 /// conversion can occur when Scalar can be casted to match Vector's element 8448 /// type without causing truncation of Scalar. 8449 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8450 ExprResult *Vector) { 8451 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8452 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8453 const VectorType *VT = VectorTy->getAs<VectorType>(); 8454 8455 assert(!isa<ExtVectorType>(VT) && 8456 "ExtVectorTypes should not be handled here!"); 8457 8458 QualType VectorEltTy = VT->getElementType(); 8459 8460 // Reject cases where the vector element type or the scalar element type are 8461 // not integral or floating point types. 8462 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8463 return true; 8464 8465 // The conversion to apply to the scalar before splatting it, 8466 // if necessary. 8467 CastKind ScalarCast = CK_NoOp; 8468 8469 // Accept cases where the vector elements are integers and the scalar is 8470 // an integer. 8471 // FIXME: Notionally if the scalar was a floating point value with a precise 8472 // integral representation, we could cast it to an appropriate integer 8473 // type and then perform the rest of the checks here. GCC will perform 8474 // this conversion in some cases as determined by the input language. 8475 // We should accept it on a language independent basis. 8476 if (VectorEltTy->isIntegralType(S.Context) && 8477 ScalarTy->isIntegralType(S.Context) && 8478 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8479 8480 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8481 return true; 8482 8483 ScalarCast = CK_IntegralCast; 8484 } else if (VectorEltTy->isRealFloatingType()) { 8485 if (ScalarTy->isRealFloatingType()) { 8486 8487 // Reject cases where the scalar type is not a constant and has a higher 8488 // Order than the vector element type. 8489 llvm::APFloat Result(0.0); 8490 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8491 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8492 if (!CstScalar && Order < 0) 8493 return true; 8494 8495 // If the scalar cannot be safely casted to the vector element type, 8496 // reject it. 8497 if (CstScalar) { 8498 bool Truncated = false; 8499 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8500 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8501 if (Truncated) 8502 return true; 8503 } 8504 8505 ScalarCast = CK_FloatingCast; 8506 } else if (ScalarTy->isIntegralType(S.Context)) { 8507 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8508 return true; 8509 8510 ScalarCast = CK_IntegralToFloating; 8511 } else 8512 return true; 8513 } 8514 8515 // Adjust scalar if desired. 8516 if (Scalar) { 8517 if (ScalarCast != CK_NoOp) 8518 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8519 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8520 } 8521 return false; 8522 } 8523 8524 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8525 SourceLocation Loc, bool IsCompAssign, 8526 bool AllowBothBool, 8527 bool AllowBoolConversions) { 8528 if (!IsCompAssign) { 8529 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8530 if (LHS.isInvalid()) 8531 return QualType(); 8532 } 8533 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8534 if (RHS.isInvalid()) 8535 return QualType(); 8536 8537 // For conversion purposes, we ignore any qualifiers. 8538 // For example, "const float" and "float" are equivalent. 8539 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8540 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8541 8542 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8543 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8544 assert(LHSVecType || RHSVecType); 8545 8546 // AltiVec-style "vector bool op vector bool" combinations are allowed 8547 // for some operators but not others. 8548 if (!AllowBothBool && 8549 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8550 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8551 return InvalidOperands(Loc, LHS, RHS); 8552 8553 // If the vector types are identical, return. 8554 if (Context.hasSameType(LHSType, RHSType)) 8555 return LHSType; 8556 8557 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8558 if (LHSVecType && RHSVecType && 8559 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8560 if (isa<ExtVectorType>(LHSVecType)) { 8561 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8562 return LHSType; 8563 } 8564 8565 if (!IsCompAssign) 8566 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8567 return RHSType; 8568 } 8569 8570 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8571 // can be mixed, with the result being the non-bool type. The non-bool 8572 // operand must have integer element type. 8573 if (AllowBoolConversions && LHSVecType && RHSVecType && 8574 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8575 (Context.getTypeSize(LHSVecType->getElementType()) == 8576 Context.getTypeSize(RHSVecType->getElementType()))) { 8577 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8578 LHSVecType->getElementType()->isIntegerType() && 8579 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8580 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8581 return LHSType; 8582 } 8583 if (!IsCompAssign && 8584 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8585 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8586 RHSVecType->getElementType()->isIntegerType()) { 8587 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8588 return RHSType; 8589 } 8590 } 8591 8592 // If there's a vector type and a scalar, try to convert the scalar to 8593 // the vector element type and splat. 8594 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8595 if (!RHSVecType) { 8596 if (isa<ExtVectorType>(LHSVecType)) { 8597 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8598 LHSVecType->getElementType(), LHSType, 8599 DiagID)) 8600 return LHSType; 8601 } else { 8602 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8603 return LHSType; 8604 } 8605 } 8606 if (!LHSVecType) { 8607 if (isa<ExtVectorType>(RHSVecType)) { 8608 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8609 LHSType, RHSVecType->getElementType(), 8610 RHSType, DiagID)) 8611 return RHSType; 8612 } else { 8613 if (LHS.get()->getValueKind() == VK_LValue || 8614 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8615 return RHSType; 8616 } 8617 } 8618 8619 // FIXME: The code below also handles conversion between vectors and 8620 // non-scalars, we should break this down into fine grained specific checks 8621 // and emit proper diagnostics. 8622 QualType VecType = LHSVecType ? LHSType : RHSType; 8623 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8624 QualType OtherType = LHSVecType ? RHSType : LHSType; 8625 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8626 if (isLaxVectorConversion(OtherType, VecType)) { 8627 // If we're allowing lax vector conversions, only the total (data) size 8628 // needs to be the same. For non compound assignment, if one of the types is 8629 // scalar, the result is always the vector type. 8630 if (!IsCompAssign) { 8631 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8632 return VecType; 8633 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8634 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8635 // type. Note that this is already done by non-compound assignments in 8636 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8637 // <1 x T> -> T. The result is also a vector type. 8638 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8639 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8640 ExprResult *RHSExpr = &RHS; 8641 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8642 return VecType; 8643 } 8644 } 8645 8646 // Okay, the expression is invalid. 8647 8648 // If there's a non-vector, non-real operand, diagnose that. 8649 if ((!RHSVecType && !RHSType->isRealType()) || 8650 (!LHSVecType && !LHSType->isRealType())) { 8651 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8652 << LHSType << RHSType 8653 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8654 return QualType(); 8655 } 8656 8657 // OpenCL V1.1 6.2.6.p1: 8658 // If the operands are of more than one vector type, then an error shall 8659 // occur. Implicit conversions between vector types are not permitted, per 8660 // section 6.2.1. 8661 if (getLangOpts().OpenCL && 8662 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8663 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8664 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8665 << RHSType; 8666 return QualType(); 8667 } 8668 8669 8670 // If there is a vector type that is not a ExtVector and a scalar, we reach 8671 // this point if scalar could not be converted to the vector's element type 8672 // without truncation. 8673 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8674 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8675 QualType Scalar = LHSVecType ? RHSType : LHSType; 8676 QualType Vector = LHSVecType ? LHSType : RHSType; 8677 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8678 Diag(Loc, 8679 diag::err_typecheck_vector_not_convertable_implict_truncation) 8680 << ScalarOrVector << Scalar << Vector; 8681 8682 return QualType(); 8683 } 8684 8685 // Otherwise, use the generic diagnostic. 8686 Diag(Loc, DiagID) 8687 << LHSType << RHSType 8688 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8689 return QualType(); 8690 } 8691 8692 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8693 // expression. These are mainly cases where the null pointer is used as an 8694 // integer instead of a pointer. 8695 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8696 SourceLocation Loc, bool IsCompare) { 8697 // The canonical way to check for a GNU null is with isNullPointerConstant, 8698 // but we use a bit of a hack here for speed; this is a relatively 8699 // hot path, and isNullPointerConstant is slow. 8700 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8701 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8702 8703 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8704 8705 // Avoid analyzing cases where the result will either be invalid (and 8706 // diagnosed as such) or entirely valid and not something to warn about. 8707 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8708 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8709 return; 8710 8711 // Comparison operations would not make sense with a null pointer no matter 8712 // what the other expression is. 8713 if (!IsCompare) { 8714 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8715 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8716 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8717 return; 8718 } 8719 8720 // The rest of the operations only make sense with a null pointer 8721 // if the other expression is a pointer. 8722 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8723 NonNullType->canDecayToPointerType()) 8724 return; 8725 8726 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8727 << LHSNull /* LHS is NULL */ << NonNullType 8728 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8729 } 8730 8731 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, 8732 SourceLocation Loc) { 8733 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 8734 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 8735 if (!LUE || !RUE) 8736 return; 8737 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 8738 RUE->getKind() != UETT_SizeOf) 8739 return; 8740 8741 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); 8742 QualType RHSTy; 8743 8744 if (RUE->isArgumentType()) 8745 RHSTy = RUE->getArgumentType(); 8746 else 8747 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 8748 8749 if (!LHSTy->isPointerType() || RHSTy->isPointerType()) 8750 return; 8751 if (LHSTy->getPointeeType() != RHSTy) 8752 return; 8753 8754 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 8755 } 8756 8757 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8758 ExprResult &RHS, 8759 SourceLocation Loc, bool IsDiv) { 8760 // Check for division/remainder by zero. 8761 llvm::APSInt RHSValue; 8762 if (!RHS.get()->isValueDependent() && 8763 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8764 S.DiagRuntimeBehavior(Loc, RHS.get(), 8765 S.PDiag(diag::warn_remainder_division_by_zero) 8766 << IsDiv << RHS.get()->getSourceRange()); 8767 } 8768 8769 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8770 SourceLocation Loc, 8771 bool IsCompAssign, bool IsDiv) { 8772 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8773 8774 if (LHS.get()->getType()->isVectorType() || 8775 RHS.get()->getType()->isVectorType()) 8776 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8777 /*AllowBothBool*/getLangOpts().AltiVec, 8778 /*AllowBoolConversions*/false); 8779 8780 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8781 if (LHS.isInvalid() || RHS.isInvalid()) 8782 return QualType(); 8783 8784 8785 if (compType.isNull() || !compType->isArithmeticType()) 8786 return InvalidOperands(Loc, LHS, RHS); 8787 if (IsDiv) { 8788 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8789 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); 8790 } 8791 return compType; 8792 } 8793 8794 QualType Sema::CheckRemainderOperands( 8795 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8796 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8797 8798 if (LHS.get()->getType()->isVectorType() || 8799 RHS.get()->getType()->isVectorType()) { 8800 if (LHS.get()->getType()->hasIntegerRepresentation() && 8801 RHS.get()->getType()->hasIntegerRepresentation()) 8802 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8803 /*AllowBothBool*/getLangOpts().AltiVec, 8804 /*AllowBoolConversions*/false); 8805 return InvalidOperands(Loc, LHS, RHS); 8806 } 8807 8808 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8809 if (LHS.isInvalid() || RHS.isInvalid()) 8810 return QualType(); 8811 8812 if (compType.isNull() || !compType->isIntegerType()) 8813 return InvalidOperands(Loc, LHS, RHS); 8814 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8815 return compType; 8816 } 8817 8818 /// Diagnose invalid arithmetic on two void pointers. 8819 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8820 Expr *LHSExpr, Expr *RHSExpr) { 8821 S.Diag(Loc, S.getLangOpts().CPlusPlus 8822 ? diag::err_typecheck_pointer_arith_void_type 8823 : diag::ext_gnu_void_ptr) 8824 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8825 << RHSExpr->getSourceRange(); 8826 } 8827 8828 /// Diagnose invalid arithmetic on a void pointer. 8829 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8830 Expr *Pointer) { 8831 S.Diag(Loc, S.getLangOpts().CPlusPlus 8832 ? diag::err_typecheck_pointer_arith_void_type 8833 : diag::ext_gnu_void_ptr) 8834 << 0 /* one pointer */ << Pointer->getSourceRange(); 8835 } 8836 8837 /// Diagnose invalid arithmetic on a null pointer. 8838 /// 8839 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8840 /// idiom, which we recognize as a GNU extension. 8841 /// 8842 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8843 Expr *Pointer, bool IsGNUIdiom) { 8844 if (IsGNUIdiom) 8845 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8846 << Pointer->getSourceRange(); 8847 else 8848 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8849 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8850 } 8851 8852 /// Diagnose invalid arithmetic on two function pointers. 8853 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8854 Expr *LHS, Expr *RHS) { 8855 assert(LHS->getType()->isAnyPointerType()); 8856 assert(RHS->getType()->isAnyPointerType()); 8857 S.Diag(Loc, S.getLangOpts().CPlusPlus 8858 ? diag::err_typecheck_pointer_arith_function_type 8859 : diag::ext_gnu_ptr_func_arith) 8860 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8861 // We only show the second type if it differs from the first. 8862 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8863 RHS->getType()) 8864 << RHS->getType()->getPointeeType() 8865 << LHS->getSourceRange() << RHS->getSourceRange(); 8866 } 8867 8868 /// Diagnose invalid arithmetic on a function pointer. 8869 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8870 Expr *Pointer) { 8871 assert(Pointer->getType()->isAnyPointerType()); 8872 S.Diag(Loc, S.getLangOpts().CPlusPlus 8873 ? diag::err_typecheck_pointer_arith_function_type 8874 : diag::ext_gnu_ptr_func_arith) 8875 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8876 << 0 /* one pointer, so only one type */ 8877 << Pointer->getSourceRange(); 8878 } 8879 8880 /// Emit error if Operand is incomplete pointer type 8881 /// 8882 /// \returns True if pointer has incomplete type 8883 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8884 Expr *Operand) { 8885 QualType ResType = Operand->getType(); 8886 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8887 ResType = ResAtomicType->getValueType(); 8888 8889 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8890 QualType PointeeTy = ResType->getPointeeType(); 8891 return S.RequireCompleteType(Loc, PointeeTy, 8892 diag::err_typecheck_arithmetic_incomplete_type, 8893 PointeeTy, Operand->getSourceRange()); 8894 } 8895 8896 /// Check the validity of an arithmetic pointer operand. 8897 /// 8898 /// If the operand has pointer type, this code will check for pointer types 8899 /// which are invalid in arithmetic operations. These will be diagnosed 8900 /// appropriately, including whether or not the use is supported as an 8901 /// extension. 8902 /// 8903 /// \returns True when the operand is valid to use (even if as an extension). 8904 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8905 Expr *Operand) { 8906 QualType ResType = Operand->getType(); 8907 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8908 ResType = ResAtomicType->getValueType(); 8909 8910 if (!ResType->isAnyPointerType()) return true; 8911 8912 QualType PointeeTy = ResType->getPointeeType(); 8913 if (PointeeTy->isVoidType()) { 8914 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8915 return !S.getLangOpts().CPlusPlus; 8916 } 8917 if (PointeeTy->isFunctionType()) { 8918 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8919 return !S.getLangOpts().CPlusPlus; 8920 } 8921 8922 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8923 8924 return true; 8925 } 8926 8927 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8928 /// operands. 8929 /// 8930 /// This routine will diagnose any invalid arithmetic on pointer operands much 8931 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8932 /// for emitting a single diagnostic even for operations where both LHS and RHS 8933 /// are (potentially problematic) pointers. 8934 /// 8935 /// \returns True when the operand is valid to use (even if as an extension). 8936 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8937 Expr *LHSExpr, Expr *RHSExpr) { 8938 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8939 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8940 if (!isLHSPointer && !isRHSPointer) return true; 8941 8942 QualType LHSPointeeTy, RHSPointeeTy; 8943 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8944 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8945 8946 // if both are pointers check if operation is valid wrt address spaces 8947 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8948 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8949 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8950 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8951 S.Diag(Loc, 8952 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8953 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8954 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8955 return false; 8956 } 8957 } 8958 8959 // Check for arithmetic on pointers to incomplete types. 8960 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8961 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8962 if (isLHSVoidPtr || isRHSVoidPtr) { 8963 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8964 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8965 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8966 8967 return !S.getLangOpts().CPlusPlus; 8968 } 8969 8970 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8971 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8972 if (isLHSFuncPtr || isRHSFuncPtr) { 8973 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8974 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8975 RHSExpr); 8976 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8977 8978 return !S.getLangOpts().CPlusPlus; 8979 } 8980 8981 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8982 return false; 8983 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8984 return false; 8985 8986 return true; 8987 } 8988 8989 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8990 /// literal. 8991 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8992 Expr *LHSExpr, Expr *RHSExpr) { 8993 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8994 Expr* IndexExpr = RHSExpr; 8995 if (!StrExpr) { 8996 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8997 IndexExpr = LHSExpr; 8998 } 8999 9000 bool IsStringPlusInt = StrExpr && 9001 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9002 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9003 return; 9004 9005 llvm::APSInt index; 9006 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 9007 unsigned StrLenWithNull = StrExpr->getLength() + 1; 9008 if (index.isNonNegative() && 9009 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 9010 index.isUnsigned())) 9011 return; 9012 } 9013 9014 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9015 Self.Diag(OpLoc, diag::warn_string_plus_int) 9016 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9017 9018 // Only print a fixit for "str" + int, not for int + "str". 9019 if (IndexExpr == RHSExpr) { 9020 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9021 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9022 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9023 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9024 << FixItHint::CreateInsertion(EndLoc, "]"); 9025 } else 9026 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9027 } 9028 9029 /// Emit a warning when adding a char literal to a string. 9030 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9031 Expr *LHSExpr, Expr *RHSExpr) { 9032 const Expr *StringRefExpr = LHSExpr; 9033 const CharacterLiteral *CharExpr = 9034 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9035 9036 if (!CharExpr) { 9037 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9038 StringRefExpr = RHSExpr; 9039 } 9040 9041 if (!CharExpr || !StringRefExpr) 9042 return; 9043 9044 const QualType StringType = StringRefExpr->getType(); 9045 9046 // Return if not a PointerType. 9047 if (!StringType->isAnyPointerType()) 9048 return; 9049 9050 // Return if not a CharacterType. 9051 if (!StringType->getPointeeType()->isAnyCharacterType()) 9052 return; 9053 9054 ASTContext &Ctx = Self.getASTContext(); 9055 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9056 9057 const QualType CharType = CharExpr->getType(); 9058 if (!CharType->isAnyCharacterType() && 9059 CharType->isIntegerType() && 9060 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9061 Self.Diag(OpLoc, diag::warn_string_plus_char) 9062 << DiagRange << Ctx.CharTy; 9063 } else { 9064 Self.Diag(OpLoc, diag::warn_string_plus_char) 9065 << DiagRange << CharExpr->getType(); 9066 } 9067 9068 // Only print a fixit for str + char, not for char + str. 9069 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9070 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9071 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9072 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9073 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9074 << FixItHint::CreateInsertion(EndLoc, "]"); 9075 } else { 9076 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9077 } 9078 } 9079 9080 /// Emit error when two pointers are incompatible. 9081 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9082 Expr *LHSExpr, Expr *RHSExpr) { 9083 assert(LHSExpr->getType()->isAnyPointerType()); 9084 assert(RHSExpr->getType()->isAnyPointerType()); 9085 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9086 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9087 << RHSExpr->getSourceRange(); 9088 } 9089 9090 // C99 6.5.6 9091 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9092 SourceLocation Loc, BinaryOperatorKind Opc, 9093 QualType* CompLHSTy) { 9094 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9095 9096 if (LHS.get()->getType()->isVectorType() || 9097 RHS.get()->getType()->isVectorType()) { 9098 QualType compType = CheckVectorOperands( 9099 LHS, RHS, Loc, CompLHSTy, 9100 /*AllowBothBool*/getLangOpts().AltiVec, 9101 /*AllowBoolConversions*/getLangOpts().ZVector); 9102 if (CompLHSTy) *CompLHSTy = compType; 9103 return compType; 9104 } 9105 9106 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9107 if (LHS.isInvalid() || RHS.isInvalid()) 9108 return QualType(); 9109 9110 // Diagnose "string literal" '+' int and string '+' "char literal". 9111 if (Opc == BO_Add) { 9112 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9113 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9114 } 9115 9116 // handle the common case first (both operands are arithmetic). 9117 if (!compType.isNull() && compType->isArithmeticType()) { 9118 if (CompLHSTy) *CompLHSTy = compType; 9119 return compType; 9120 } 9121 9122 // Type-checking. Ultimately the pointer's going to be in PExp; 9123 // note that we bias towards the LHS being the pointer. 9124 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9125 9126 bool isObjCPointer; 9127 if (PExp->getType()->isPointerType()) { 9128 isObjCPointer = false; 9129 } else if (PExp->getType()->isObjCObjectPointerType()) { 9130 isObjCPointer = true; 9131 } else { 9132 std::swap(PExp, IExp); 9133 if (PExp->getType()->isPointerType()) { 9134 isObjCPointer = false; 9135 } else if (PExp->getType()->isObjCObjectPointerType()) { 9136 isObjCPointer = true; 9137 } else { 9138 return InvalidOperands(Loc, LHS, RHS); 9139 } 9140 } 9141 assert(PExp->getType()->isAnyPointerType()); 9142 9143 if (!IExp->getType()->isIntegerType()) 9144 return InvalidOperands(Loc, LHS, RHS); 9145 9146 // Adding to a null pointer results in undefined behavior. 9147 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9148 Context, Expr::NPC_ValueDependentIsNotNull)) { 9149 // In C++ adding zero to a null pointer is defined. 9150 llvm::APSInt KnownVal; 9151 if (!getLangOpts().CPlusPlus || 9152 (!IExp->isValueDependent() && 9153 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9154 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9155 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9156 Context, BO_Add, PExp, IExp); 9157 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9158 } 9159 } 9160 9161 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9162 return QualType(); 9163 9164 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9165 return QualType(); 9166 9167 // Check array bounds for pointer arithemtic 9168 CheckArrayAccess(PExp, IExp); 9169 9170 if (CompLHSTy) { 9171 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9172 if (LHSTy.isNull()) { 9173 LHSTy = LHS.get()->getType(); 9174 if (LHSTy->isPromotableIntegerType()) 9175 LHSTy = Context.getPromotedIntegerType(LHSTy); 9176 } 9177 *CompLHSTy = LHSTy; 9178 } 9179 9180 return PExp->getType(); 9181 } 9182 9183 // C99 6.5.6 9184 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9185 SourceLocation Loc, 9186 QualType* CompLHSTy) { 9187 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9188 9189 if (LHS.get()->getType()->isVectorType() || 9190 RHS.get()->getType()->isVectorType()) { 9191 QualType compType = CheckVectorOperands( 9192 LHS, RHS, Loc, CompLHSTy, 9193 /*AllowBothBool*/getLangOpts().AltiVec, 9194 /*AllowBoolConversions*/getLangOpts().ZVector); 9195 if (CompLHSTy) *CompLHSTy = compType; 9196 return compType; 9197 } 9198 9199 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9200 if (LHS.isInvalid() || RHS.isInvalid()) 9201 return QualType(); 9202 9203 // Enforce type constraints: C99 6.5.6p3. 9204 9205 // Handle the common case first (both operands are arithmetic). 9206 if (!compType.isNull() && compType->isArithmeticType()) { 9207 if (CompLHSTy) *CompLHSTy = compType; 9208 return compType; 9209 } 9210 9211 // Either ptr - int or ptr - ptr. 9212 if (LHS.get()->getType()->isAnyPointerType()) { 9213 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9214 9215 // Diagnose bad cases where we step over interface counts. 9216 if (LHS.get()->getType()->isObjCObjectPointerType() && 9217 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9218 return QualType(); 9219 9220 // The result type of a pointer-int computation is the pointer type. 9221 if (RHS.get()->getType()->isIntegerType()) { 9222 // Subtracting from a null pointer should produce a warning. 9223 // The last argument to the diagnose call says this doesn't match the 9224 // GNU int-to-pointer idiom. 9225 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9226 Expr::NPC_ValueDependentIsNotNull)) { 9227 // In C++ adding zero to a null pointer is defined. 9228 llvm::APSInt KnownVal; 9229 if (!getLangOpts().CPlusPlus || 9230 (!RHS.get()->isValueDependent() && 9231 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9232 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9233 } 9234 } 9235 9236 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9237 return QualType(); 9238 9239 // Check array bounds for pointer arithemtic 9240 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9241 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9242 9243 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9244 return LHS.get()->getType(); 9245 } 9246 9247 // Handle pointer-pointer subtractions. 9248 if (const PointerType *RHSPTy 9249 = RHS.get()->getType()->getAs<PointerType>()) { 9250 QualType rpointee = RHSPTy->getPointeeType(); 9251 9252 if (getLangOpts().CPlusPlus) { 9253 // Pointee types must be the same: C++ [expr.add] 9254 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9255 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9256 } 9257 } else { 9258 // Pointee types must be compatible C99 6.5.6p3 9259 if (!Context.typesAreCompatible( 9260 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9261 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9262 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9263 return QualType(); 9264 } 9265 } 9266 9267 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9268 LHS.get(), RHS.get())) 9269 return QualType(); 9270 9271 // FIXME: Add warnings for nullptr - ptr. 9272 9273 // The pointee type may have zero size. As an extension, a structure or 9274 // union may have zero size or an array may have zero length. In this 9275 // case subtraction does not make sense. 9276 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9277 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9278 if (ElementSize.isZero()) { 9279 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9280 << rpointee.getUnqualifiedType() 9281 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9282 } 9283 } 9284 9285 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9286 return Context.getPointerDiffType(); 9287 } 9288 } 9289 9290 return InvalidOperands(Loc, LHS, RHS); 9291 } 9292 9293 static bool isScopedEnumerationType(QualType T) { 9294 if (const EnumType *ET = T->getAs<EnumType>()) 9295 return ET->getDecl()->isScoped(); 9296 return false; 9297 } 9298 9299 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9300 SourceLocation Loc, BinaryOperatorKind Opc, 9301 QualType LHSType) { 9302 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9303 // so skip remaining warnings as we don't want to modify values within Sema. 9304 if (S.getLangOpts().OpenCL) 9305 return; 9306 9307 llvm::APSInt Right; 9308 // Check right/shifter operand 9309 if (RHS.get()->isValueDependent() || 9310 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9311 return; 9312 9313 if (Right.isNegative()) { 9314 S.DiagRuntimeBehavior(Loc, RHS.get(), 9315 S.PDiag(diag::warn_shift_negative) 9316 << RHS.get()->getSourceRange()); 9317 return; 9318 } 9319 llvm::APInt LeftBits(Right.getBitWidth(), 9320 S.Context.getTypeSize(LHS.get()->getType())); 9321 if (Right.uge(LeftBits)) { 9322 S.DiagRuntimeBehavior(Loc, RHS.get(), 9323 S.PDiag(diag::warn_shift_gt_typewidth) 9324 << RHS.get()->getSourceRange()); 9325 return; 9326 } 9327 if (Opc != BO_Shl) 9328 return; 9329 9330 // When left shifting an ICE which is signed, we can check for overflow which 9331 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9332 // integers have defined behavior modulo one more than the maximum value 9333 // representable in the result type, so never warn for those. 9334 llvm::APSInt Left; 9335 if (LHS.get()->isValueDependent() || 9336 LHSType->hasUnsignedIntegerRepresentation() || 9337 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9338 return; 9339 9340 // If LHS does not have a signed type and non-negative value 9341 // then, the behavior is undefined. Warn about it. 9342 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9343 S.DiagRuntimeBehavior(Loc, LHS.get(), 9344 S.PDiag(diag::warn_shift_lhs_negative) 9345 << LHS.get()->getSourceRange()); 9346 return; 9347 } 9348 9349 llvm::APInt ResultBits = 9350 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9351 if (LeftBits.uge(ResultBits)) 9352 return; 9353 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9354 Result = Result.shl(Right); 9355 9356 // Print the bit representation of the signed integer as an unsigned 9357 // hexadecimal number. 9358 SmallString<40> HexResult; 9359 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9360 9361 // If we are only missing a sign bit, this is less likely to result in actual 9362 // bugs -- if the result is cast back to an unsigned type, it will have the 9363 // expected value. Thus we place this behind a different warning that can be 9364 // turned off separately if needed. 9365 if (LeftBits == ResultBits - 1) { 9366 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9367 << HexResult << LHSType 9368 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9369 return; 9370 } 9371 9372 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9373 << HexResult.str() << Result.getMinSignedBits() << LHSType 9374 << Left.getBitWidth() << LHS.get()->getSourceRange() 9375 << RHS.get()->getSourceRange(); 9376 } 9377 9378 /// Return the resulting type when a vector is shifted 9379 /// by a scalar or vector shift amount. 9380 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9381 SourceLocation Loc, bool IsCompAssign) { 9382 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9383 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9384 !LHS.get()->getType()->isVectorType()) { 9385 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9386 << RHS.get()->getType() << LHS.get()->getType() 9387 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9388 return QualType(); 9389 } 9390 9391 if (!IsCompAssign) { 9392 LHS = S.UsualUnaryConversions(LHS.get()); 9393 if (LHS.isInvalid()) return QualType(); 9394 } 9395 9396 RHS = S.UsualUnaryConversions(RHS.get()); 9397 if (RHS.isInvalid()) return QualType(); 9398 9399 QualType LHSType = LHS.get()->getType(); 9400 // Note that LHS might be a scalar because the routine calls not only in 9401 // OpenCL case. 9402 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9403 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9404 9405 // Note that RHS might not be a vector. 9406 QualType RHSType = RHS.get()->getType(); 9407 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9408 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9409 9410 // The operands need to be integers. 9411 if (!LHSEleType->isIntegerType()) { 9412 S.Diag(Loc, diag::err_typecheck_expect_int) 9413 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9414 return QualType(); 9415 } 9416 9417 if (!RHSEleType->isIntegerType()) { 9418 S.Diag(Loc, diag::err_typecheck_expect_int) 9419 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9420 return QualType(); 9421 } 9422 9423 if (!LHSVecTy) { 9424 assert(RHSVecTy); 9425 if (IsCompAssign) 9426 return RHSType; 9427 if (LHSEleType != RHSEleType) { 9428 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9429 LHSEleType = RHSEleType; 9430 } 9431 QualType VecTy = 9432 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9433 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9434 LHSType = VecTy; 9435 } else if (RHSVecTy) { 9436 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9437 // are applied component-wise. So if RHS is a vector, then ensure 9438 // that the number of elements is the same as LHS... 9439 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9440 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9441 << LHS.get()->getType() << RHS.get()->getType() 9442 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9443 return QualType(); 9444 } 9445 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9446 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9447 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9448 if (LHSBT != RHSBT && 9449 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9450 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9451 << LHS.get()->getType() << RHS.get()->getType() 9452 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9453 } 9454 } 9455 } else { 9456 // ...else expand RHS to match the number of elements in LHS. 9457 QualType VecTy = 9458 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9459 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9460 } 9461 9462 return LHSType; 9463 } 9464 9465 // C99 6.5.7 9466 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9467 SourceLocation Loc, BinaryOperatorKind Opc, 9468 bool IsCompAssign) { 9469 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9470 9471 // Vector shifts promote their scalar inputs to vector type. 9472 if (LHS.get()->getType()->isVectorType() || 9473 RHS.get()->getType()->isVectorType()) { 9474 if (LangOpts.ZVector) { 9475 // The shift operators for the z vector extensions work basically 9476 // like general shifts, except that neither the LHS nor the RHS is 9477 // allowed to be a "vector bool". 9478 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9479 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9480 return InvalidOperands(Loc, LHS, RHS); 9481 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9482 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9483 return InvalidOperands(Loc, LHS, RHS); 9484 } 9485 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9486 } 9487 9488 // Shifts don't perform usual arithmetic conversions, they just do integer 9489 // promotions on each operand. C99 6.5.7p3 9490 9491 // For the LHS, do usual unary conversions, but then reset them away 9492 // if this is a compound assignment. 9493 ExprResult OldLHS = LHS; 9494 LHS = UsualUnaryConversions(LHS.get()); 9495 if (LHS.isInvalid()) 9496 return QualType(); 9497 QualType LHSType = LHS.get()->getType(); 9498 if (IsCompAssign) LHS = OldLHS; 9499 9500 // The RHS is simpler. 9501 RHS = UsualUnaryConversions(RHS.get()); 9502 if (RHS.isInvalid()) 9503 return QualType(); 9504 QualType RHSType = RHS.get()->getType(); 9505 9506 // C99 6.5.7p2: Each of the operands shall have integer type. 9507 if (!LHSType->hasIntegerRepresentation() || 9508 !RHSType->hasIntegerRepresentation()) 9509 return InvalidOperands(Loc, LHS, RHS); 9510 9511 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9512 // hasIntegerRepresentation() above instead of this. 9513 if (isScopedEnumerationType(LHSType) || 9514 isScopedEnumerationType(RHSType)) { 9515 return InvalidOperands(Loc, LHS, RHS); 9516 } 9517 // Sanity-check shift operands 9518 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9519 9520 // "The type of the result is that of the promoted left operand." 9521 return LHSType; 9522 } 9523 9524 /// If two different enums are compared, raise a warning. 9525 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9526 Expr *RHS) { 9527 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9528 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9529 9530 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9531 if (!LHSEnumType) 9532 return; 9533 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9534 if (!RHSEnumType) 9535 return; 9536 9537 // Ignore anonymous enums. 9538 if (!LHSEnumType->getDecl()->getIdentifier() && 9539 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9540 return; 9541 if (!RHSEnumType->getDecl()->getIdentifier() && 9542 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9543 return; 9544 9545 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9546 return; 9547 9548 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9549 << LHSStrippedType << RHSStrippedType 9550 << LHS->getSourceRange() << RHS->getSourceRange(); 9551 } 9552 9553 /// Diagnose bad pointer comparisons. 9554 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9555 ExprResult &LHS, ExprResult &RHS, 9556 bool IsError) { 9557 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9558 : diag::ext_typecheck_comparison_of_distinct_pointers) 9559 << LHS.get()->getType() << RHS.get()->getType() 9560 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9561 } 9562 9563 /// Returns false if the pointers are converted to a composite type, 9564 /// true otherwise. 9565 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9566 ExprResult &LHS, ExprResult &RHS) { 9567 // C++ [expr.rel]p2: 9568 // [...] Pointer conversions (4.10) and qualification 9569 // conversions (4.4) are performed on pointer operands (or on 9570 // a pointer operand and a null pointer constant) to bring 9571 // them to their composite pointer type. [...] 9572 // 9573 // C++ [expr.eq]p1 uses the same notion for (in)equality 9574 // comparisons of pointers. 9575 9576 QualType LHSType = LHS.get()->getType(); 9577 QualType RHSType = RHS.get()->getType(); 9578 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9579 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9580 9581 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9582 if (T.isNull()) { 9583 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9584 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9585 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9586 else 9587 S.InvalidOperands(Loc, LHS, RHS); 9588 return true; 9589 } 9590 9591 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9592 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9593 return false; 9594 } 9595 9596 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9597 ExprResult &LHS, 9598 ExprResult &RHS, 9599 bool IsError) { 9600 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9601 : diag::ext_typecheck_comparison_of_fptr_to_void) 9602 << LHS.get()->getType() << RHS.get()->getType() 9603 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9604 } 9605 9606 static bool isObjCObjectLiteral(ExprResult &E) { 9607 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9608 case Stmt::ObjCArrayLiteralClass: 9609 case Stmt::ObjCDictionaryLiteralClass: 9610 case Stmt::ObjCStringLiteralClass: 9611 case Stmt::ObjCBoxedExprClass: 9612 return true; 9613 default: 9614 // Note that ObjCBoolLiteral is NOT an object literal! 9615 return false; 9616 } 9617 } 9618 9619 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9620 const ObjCObjectPointerType *Type = 9621 LHS->getType()->getAs<ObjCObjectPointerType>(); 9622 9623 // If this is not actually an Objective-C object, bail out. 9624 if (!Type) 9625 return false; 9626 9627 // Get the LHS object's interface type. 9628 QualType InterfaceType = Type->getPointeeType(); 9629 9630 // If the RHS isn't an Objective-C object, bail out. 9631 if (!RHS->getType()->isObjCObjectPointerType()) 9632 return false; 9633 9634 // Try to find the -isEqual: method. 9635 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9636 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9637 InterfaceType, 9638 /*instance=*/true); 9639 if (!Method) { 9640 if (Type->isObjCIdType()) { 9641 // For 'id', just check the global pool. 9642 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9643 /*receiverId=*/true); 9644 } else { 9645 // Check protocols. 9646 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9647 /*instance=*/true); 9648 } 9649 } 9650 9651 if (!Method) 9652 return false; 9653 9654 QualType T = Method->parameters()[0]->getType(); 9655 if (!T->isObjCObjectPointerType()) 9656 return false; 9657 9658 QualType R = Method->getReturnType(); 9659 if (!R->isScalarType()) 9660 return false; 9661 9662 return true; 9663 } 9664 9665 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9666 FromE = FromE->IgnoreParenImpCasts(); 9667 switch (FromE->getStmtClass()) { 9668 default: 9669 break; 9670 case Stmt::ObjCStringLiteralClass: 9671 // "string literal" 9672 return LK_String; 9673 case Stmt::ObjCArrayLiteralClass: 9674 // "array literal" 9675 return LK_Array; 9676 case Stmt::ObjCDictionaryLiteralClass: 9677 // "dictionary literal" 9678 return LK_Dictionary; 9679 case Stmt::BlockExprClass: 9680 return LK_Block; 9681 case Stmt::ObjCBoxedExprClass: { 9682 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9683 switch (Inner->getStmtClass()) { 9684 case Stmt::IntegerLiteralClass: 9685 case Stmt::FloatingLiteralClass: 9686 case Stmt::CharacterLiteralClass: 9687 case Stmt::ObjCBoolLiteralExprClass: 9688 case Stmt::CXXBoolLiteralExprClass: 9689 // "numeric literal" 9690 return LK_Numeric; 9691 case Stmt::ImplicitCastExprClass: { 9692 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9693 // Boolean literals can be represented by implicit casts. 9694 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9695 return LK_Numeric; 9696 break; 9697 } 9698 default: 9699 break; 9700 } 9701 return LK_Boxed; 9702 } 9703 } 9704 return LK_None; 9705 } 9706 9707 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9708 ExprResult &LHS, ExprResult &RHS, 9709 BinaryOperator::Opcode Opc){ 9710 Expr *Literal; 9711 Expr *Other; 9712 if (isObjCObjectLiteral(LHS)) { 9713 Literal = LHS.get(); 9714 Other = RHS.get(); 9715 } else { 9716 Literal = RHS.get(); 9717 Other = LHS.get(); 9718 } 9719 9720 // Don't warn on comparisons against nil. 9721 Other = Other->IgnoreParenCasts(); 9722 if (Other->isNullPointerConstant(S.getASTContext(), 9723 Expr::NPC_ValueDependentIsNotNull)) 9724 return; 9725 9726 // This should be kept in sync with warn_objc_literal_comparison. 9727 // LK_String should always be after the other literals, since it has its own 9728 // warning flag. 9729 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9730 assert(LiteralKind != Sema::LK_Block); 9731 if (LiteralKind == Sema::LK_None) { 9732 llvm_unreachable("Unknown Objective-C object literal kind"); 9733 } 9734 9735 if (LiteralKind == Sema::LK_String) 9736 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9737 << Literal->getSourceRange(); 9738 else 9739 S.Diag(Loc, diag::warn_objc_literal_comparison) 9740 << LiteralKind << Literal->getSourceRange(); 9741 9742 if (BinaryOperator::isEqualityOp(Opc) && 9743 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9744 SourceLocation Start = LHS.get()->getBeginLoc(); 9745 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9746 CharSourceRange OpRange = 9747 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9748 9749 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9750 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9751 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9752 << FixItHint::CreateInsertion(End, "]"); 9753 } 9754 } 9755 9756 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9757 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9758 ExprResult &RHS, SourceLocation Loc, 9759 BinaryOperatorKind Opc) { 9760 // Check that left hand side is !something. 9761 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9762 if (!UO || UO->getOpcode() != UO_LNot) return; 9763 9764 // Only check if the right hand side is non-bool arithmetic type. 9765 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9766 9767 // Make sure that the something in !something is not bool. 9768 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9769 if (SubExpr->isKnownToHaveBooleanValue()) return; 9770 9771 // Emit warning. 9772 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9773 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9774 << Loc << IsBitwiseOp; 9775 9776 // First note suggest !(x < y) 9777 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9778 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9779 FirstClose = S.getLocForEndOfToken(FirstClose); 9780 if (FirstClose.isInvalid()) 9781 FirstOpen = SourceLocation(); 9782 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9783 << IsBitwiseOp 9784 << FixItHint::CreateInsertion(FirstOpen, "(") 9785 << FixItHint::CreateInsertion(FirstClose, ")"); 9786 9787 // Second note suggests (!x) < y 9788 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9789 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9790 SecondClose = S.getLocForEndOfToken(SecondClose); 9791 if (SecondClose.isInvalid()) 9792 SecondOpen = SourceLocation(); 9793 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9794 << FixItHint::CreateInsertion(SecondOpen, "(") 9795 << FixItHint::CreateInsertion(SecondClose, ")"); 9796 } 9797 9798 // Get the decl for a simple expression: a reference to a variable, 9799 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9800 static ValueDecl *getCompareDecl(Expr *E) { 9801 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9802 return DR->getDecl(); 9803 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9804 if (Ivar->isFreeIvar()) 9805 return Ivar->getDecl(); 9806 } 9807 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9808 if (Mem->isImplicitAccess()) 9809 return Mem->getMemberDecl(); 9810 } 9811 return nullptr; 9812 } 9813 9814 /// Diagnose some forms of syntactically-obvious tautological comparison. 9815 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9816 Expr *LHS, Expr *RHS, 9817 BinaryOperatorKind Opc) { 9818 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9819 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9820 9821 QualType LHSType = LHS->getType(); 9822 QualType RHSType = RHS->getType(); 9823 if (LHSType->hasFloatingRepresentation() || 9824 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9825 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9826 S.inTemplateInstantiation()) 9827 return; 9828 9829 // Comparisons between two array types are ill-formed for operator<=>, so 9830 // we shouldn't emit any additional warnings about it. 9831 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9832 return; 9833 9834 // For non-floating point types, check for self-comparisons of the form 9835 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9836 // often indicate logic errors in the program. 9837 // 9838 // NOTE: Don't warn about comparison expressions resulting from macro 9839 // expansion. Also don't warn about comparisons which are only self 9840 // comparisons within a template instantiation. The warnings should catch 9841 // obvious cases in the definition of the template anyways. The idea is to 9842 // warn when the typed comparison operator will always evaluate to the same 9843 // result. 9844 ValueDecl *DL = getCompareDecl(LHSStripped); 9845 ValueDecl *DR = getCompareDecl(RHSStripped); 9846 if (DL && DR && declaresSameEntity(DL, DR)) { 9847 StringRef Result; 9848 switch (Opc) { 9849 case BO_EQ: case BO_LE: case BO_GE: 9850 Result = "true"; 9851 break; 9852 case BO_NE: case BO_LT: case BO_GT: 9853 Result = "false"; 9854 break; 9855 case BO_Cmp: 9856 Result = "'std::strong_ordering::equal'"; 9857 break; 9858 default: 9859 break; 9860 } 9861 S.DiagRuntimeBehavior(Loc, nullptr, 9862 S.PDiag(diag::warn_comparison_always) 9863 << 0 /*self-comparison*/ << !Result.empty() 9864 << Result); 9865 } else if (DL && DR && 9866 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9867 !DL->isWeak() && !DR->isWeak()) { 9868 // What is it always going to evaluate to? 9869 StringRef Result; 9870 switch(Opc) { 9871 case BO_EQ: // e.g. array1 == array2 9872 Result = "false"; 9873 break; 9874 case BO_NE: // e.g. array1 != array2 9875 Result = "true"; 9876 break; 9877 default: // e.g. array1 <= array2 9878 // The best we can say is 'a constant' 9879 break; 9880 } 9881 S.DiagRuntimeBehavior(Loc, nullptr, 9882 S.PDiag(diag::warn_comparison_always) 9883 << 1 /*array comparison*/ 9884 << !Result.empty() << Result); 9885 } 9886 9887 if (isa<CastExpr>(LHSStripped)) 9888 LHSStripped = LHSStripped->IgnoreParenCasts(); 9889 if (isa<CastExpr>(RHSStripped)) 9890 RHSStripped = RHSStripped->IgnoreParenCasts(); 9891 9892 // Warn about comparisons against a string constant (unless the other 9893 // operand is null); the user probably wants strcmp. 9894 Expr *LiteralString = nullptr; 9895 Expr *LiteralStringStripped = nullptr; 9896 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9897 !RHSStripped->isNullPointerConstant(S.Context, 9898 Expr::NPC_ValueDependentIsNull)) { 9899 LiteralString = LHS; 9900 LiteralStringStripped = LHSStripped; 9901 } else if ((isa<StringLiteral>(RHSStripped) || 9902 isa<ObjCEncodeExpr>(RHSStripped)) && 9903 !LHSStripped->isNullPointerConstant(S.Context, 9904 Expr::NPC_ValueDependentIsNull)) { 9905 LiteralString = RHS; 9906 LiteralStringStripped = RHSStripped; 9907 } 9908 9909 if (LiteralString) { 9910 S.DiagRuntimeBehavior(Loc, nullptr, 9911 S.PDiag(diag::warn_stringcompare) 9912 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9913 << LiteralString->getSourceRange()); 9914 } 9915 } 9916 9917 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9918 switch (CK) { 9919 default: { 9920 #ifndef NDEBUG 9921 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9922 << "\n"; 9923 #endif 9924 llvm_unreachable("unhandled cast kind"); 9925 } 9926 case CK_UserDefinedConversion: 9927 return ICK_Identity; 9928 case CK_LValueToRValue: 9929 return ICK_Lvalue_To_Rvalue; 9930 case CK_ArrayToPointerDecay: 9931 return ICK_Array_To_Pointer; 9932 case CK_FunctionToPointerDecay: 9933 return ICK_Function_To_Pointer; 9934 case CK_IntegralCast: 9935 return ICK_Integral_Conversion; 9936 case CK_FloatingCast: 9937 return ICK_Floating_Conversion; 9938 case CK_IntegralToFloating: 9939 case CK_FloatingToIntegral: 9940 return ICK_Floating_Integral; 9941 case CK_IntegralComplexCast: 9942 case CK_FloatingComplexCast: 9943 case CK_FloatingComplexToIntegralComplex: 9944 case CK_IntegralComplexToFloatingComplex: 9945 return ICK_Complex_Conversion; 9946 case CK_FloatingComplexToReal: 9947 case CK_FloatingRealToComplex: 9948 case CK_IntegralComplexToReal: 9949 case CK_IntegralRealToComplex: 9950 return ICK_Complex_Real; 9951 } 9952 } 9953 9954 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9955 QualType FromType, 9956 SourceLocation Loc) { 9957 // Check for a narrowing implicit conversion. 9958 StandardConversionSequence SCS; 9959 SCS.setAsIdentityConversion(); 9960 SCS.setToType(0, FromType); 9961 SCS.setToType(1, ToType); 9962 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9963 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9964 9965 APValue PreNarrowingValue; 9966 QualType PreNarrowingType; 9967 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9968 PreNarrowingType, 9969 /*IgnoreFloatToIntegralConversion*/ true)) { 9970 case NK_Dependent_Narrowing: 9971 // Implicit conversion to a narrower type, but the expression is 9972 // value-dependent so we can't tell whether it's actually narrowing. 9973 case NK_Not_Narrowing: 9974 return false; 9975 9976 case NK_Constant_Narrowing: 9977 // Implicit conversion to a narrower type, and the value is not a constant 9978 // expression. 9979 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9980 << /*Constant*/ 1 9981 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9982 return true; 9983 9984 case NK_Variable_Narrowing: 9985 // Implicit conversion to a narrower type, and the value is not a constant 9986 // expression. 9987 case NK_Type_Narrowing: 9988 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9989 << /*Constant*/ 0 << FromType << ToType; 9990 // TODO: It's not a constant expression, but what if the user intended it 9991 // to be? Can we produce notes to help them figure out why it isn't? 9992 return true; 9993 } 9994 llvm_unreachable("unhandled case in switch"); 9995 } 9996 9997 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9998 ExprResult &LHS, 9999 ExprResult &RHS, 10000 SourceLocation Loc) { 10001 using CCT = ComparisonCategoryType; 10002 10003 QualType LHSType = LHS.get()->getType(); 10004 QualType RHSType = RHS.get()->getType(); 10005 // Dig out the original argument type and expression before implicit casts 10006 // were applied. These are the types/expressions we need to check the 10007 // [expr.spaceship] requirements against. 10008 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10009 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10010 QualType LHSStrippedType = LHSStripped.get()->getType(); 10011 QualType RHSStrippedType = RHSStripped.get()->getType(); 10012 10013 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10014 // other is not, the program is ill-formed. 10015 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10016 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10017 return QualType(); 10018 } 10019 10020 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10021 RHSStrippedType->isEnumeralType(); 10022 if (NumEnumArgs == 1) { 10023 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10024 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10025 if (OtherTy->hasFloatingRepresentation()) { 10026 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10027 return QualType(); 10028 } 10029 } 10030 if (NumEnumArgs == 2) { 10031 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10032 // type E, the operator yields the result of converting the operands 10033 // to the underlying type of E and applying <=> to the converted operands. 10034 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10035 S.InvalidOperands(Loc, LHS, RHS); 10036 return QualType(); 10037 } 10038 QualType IntType = 10039 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10040 assert(IntType->isArithmeticType()); 10041 10042 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10043 // promote the boolean type, and all other promotable integer types, to 10044 // avoid this. 10045 if (IntType->isPromotableIntegerType()) 10046 IntType = S.Context.getPromotedIntegerType(IntType); 10047 10048 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10049 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10050 LHSType = RHSType = IntType; 10051 } 10052 10053 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10054 // usual arithmetic conversions are applied to the operands. 10055 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10056 if (LHS.isInvalid() || RHS.isInvalid()) 10057 return QualType(); 10058 if (Type.isNull()) 10059 return S.InvalidOperands(Loc, LHS, RHS); 10060 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10061 10062 bool HasNarrowing = checkThreeWayNarrowingConversion( 10063 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10064 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10065 RHS.get()->getBeginLoc()); 10066 if (HasNarrowing) 10067 return QualType(); 10068 10069 assert(!Type.isNull() && "composite type for <=> has not been set"); 10070 10071 auto TypeKind = [&]() { 10072 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10073 if (CT->getElementType()->hasFloatingRepresentation()) 10074 return CCT::WeakEquality; 10075 return CCT::StrongEquality; 10076 } 10077 if (Type->isIntegralOrEnumerationType()) 10078 return CCT::StrongOrdering; 10079 if (Type->hasFloatingRepresentation()) 10080 return CCT::PartialOrdering; 10081 llvm_unreachable("other types are unimplemented"); 10082 }(); 10083 10084 return S.CheckComparisonCategoryType(TypeKind, Loc); 10085 } 10086 10087 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10088 ExprResult &RHS, 10089 SourceLocation Loc, 10090 BinaryOperatorKind Opc) { 10091 if (Opc == BO_Cmp) 10092 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10093 10094 // C99 6.5.8p3 / C99 6.5.9p4 10095 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10096 if (LHS.isInvalid() || RHS.isInvalid()) 10097 return QualType(); 10098 if (Type.isNull()) 10099 return S.InvalidOperands(Loc, LHS, RHS); 10100 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10101 10102 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10103 10104 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10105 return S.InvalidOperands(Loc, LHS, RHS); 10106 10107 // Check for comparisons of floating point operands using != and ==. 10108 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10109 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10110 10111 // The result of comparisons is 'bool' in C++, 'int' in C. 10112 return S.Context.getLogicalOperationType(); 10113 } 10114 10115 // C99 6.5.8, C++ [expr.rel] 10116 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10117 SourceLocation Loc, 10118 BinaryOperatorKind Opc) { 10119 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10120 bool IsThreeWay = Opc == BO_Cmp; 10121 auto IsAnyPointerType = [](ExprResult E) { 10122 QualType Ty = E.get()->getType(); 10123 return Ty->isPointerType() || Ty->isMemberPointerType(); 10124 }; 10125 10126 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10127 // type, array-to-pointer, ..., conversions are performed on both operands to 10128 // bring them to their composite type. 10129 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10130 // any type-related checks. 10131 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10132 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10133 if (LHS.isInvalid()) 10134 return QualType(); 10135 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10136 if (RHS.isInvalid()) 10137 return QualType(); 10138 } else { 10139 LHS = DefaultLvalueConversion(LHS.get()); 10140 if (LHS.isInvalid()) 10141 return QualType(); 10142 RHS = DefaultLvalueConversion(RHS.get()); 10143 if (RHS.isInvalid()) 10144 return QualType(); 10145 } 10146 10147 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10148 10149 // Handle vector comparisons separately. 10150 if (LHS.get()->getType()->isVectorType() || 10151 RHS.get()->getType()->isVectorType()) 10152 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10153 10154 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10155 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10156 10157 QualType LHSType = LHS.get()->getType(); 10158 QualType RHSType = RHS.get()->getType(); 10159 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10160 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10161 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10162 10163 const Expr::NullPointerConstantKind LHSNullKind = 10164 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10165 const Expr::NullPointerConstantKind RHSNullKind = 10166 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10167 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10168 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10169 10170 auto computeResultTy = [&]() { 10171 if (Opc != BO_Cmp) 10172 return Context.getLogicalOperationType(); 10173 assert(getLangOpts().CPlusPlus); 10174 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10175 10176 QualType CompositeTy = LHS.get()->getType(); 10177 assert(!CompositeTy->isReferenceType()); 10178 10179 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10180 return CheckComparisonCategoryType(Kind, Loc); 10181 }; 10182 10183 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10184 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10185 // result is of type std::strong_equality 10186 if (CompositeTy->isFunctionPointerType() || 10187 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10188 // FIXME: consider making the function pointer case produce 10189 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10190 // and direction polls 10191 return buildResultTy(ComparisonCategoryType::StrongEquality); 10192 10193 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10194 // pointer type, p <=> q is of type std::strong_ordering. 10195 if (CompositeTy->isPointerType()) { 10196 // P0946R0: Comparisons between a null pointer constant and an object 10197 // pointer result in std::strong_equality 10198 if (LHSIsNull != RHSIsNull) 10199 return buildResultTy(ComparisonCategoryType::StrongEquality); 10200 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10201 } 10202 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10203 // TODO: Extend support for operator<=> to ObjC types. 10204 return InvalidOperands(Loc, LHS, RHS); 10205 }; 10206 10207 10208 if (!IsRelational && LHSIsNull != RHSIsNull) { 10209 bool IsEquality = Opc == BO_EQ; 10210 if (RHSIsNull) 10211 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10212 RHS.get()->getSourceRange()); 10213 else 10214 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10215 LHS.get()->getSourceRange()); 10216 } 10217 10218 if ((LHSType->isIntegerType() && !LHSIsNull) || 10219 (RHSType->isIntegerType() && !RHSIsNull)) { 10220 // Skip normal pointer conversion checks in this case; we have better 10221 // diagnostics for this below. 10222 } else if (getLangOpts().CPlusPlus) { 10223 // Equality comparison of a function pointer to a void pointer is invalid, 10224 // but we allow it as an extension. 10225 // FIXME: If we really want to allow this, should it be part of composite 10226 // pointer type computation so it works in conditionals too? 10227 if (!IsRelational && 10228 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10229 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10230 // This is a gcc extension compatibility comparison. 10231 // In a SFINAE context, we treat this as a hard error to maintain 10232 // conformance with the C++ standard. 10233 diagnoseFunctionPointerToVoidComparison( 10234 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10235 10236 if (isSFINAEContext()) 10237 return QualType(); 10238 10239 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10240 return computeResultTy(); 10241 } 10242 10243 // C++ [expr.eq]p2: 10244 // If at least one operand is a pointer [...] bring them to their 10245 // composite pointer type. 10246 // C++ [expr.spaceship]p6 10247 // If at least one of the operands is of pointer type, [...] bring them 10248 // to their composite pointer type. 10249 // C++ [expr.rel]p2: 10250 // If both operands are pointers, [...] bring them to their composite 10251 // pointer type. 10252 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10253 (IsRelational ? 2 : 1) && 10254 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10255 RHSType->isObjCObjectPointerType()))) { 10256 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10257 return QualType(); 10258 return computeResultTy(); 10259 } 10260 } else if (LHSType->isPointerType() && 10261 RHSType->isPointerType()) { // C99 6.5.8p2 10262 // All of the following pointer-related warnings are GCC extensions, except 10263 // when handling null pointer constants. 10264 QualType LCanPointeeTy = 10265 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10266 QualType RCanPointeeTy = 10267 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10268 10269 // C99 6.5.9p2 and C99 6.5.8p2 10270 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10271 RCanPointeeTy.getUnqualifiedType())) { 10272 // Valid unless a relational comparison of function pointers 10273 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10274 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10275 << LHSType << RHSType << LHS.get()->getSourceRange() 10276 << RHS.get()->getSourceRange(); 10277 } 10278 } else if (!IsRelational && 10279 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10280 // Valid unless comparison between non-null pointer and function pointer 10281 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10282 && !LHSIsNull && !RHSIsNull) 10283 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10284 /*isError*/false); 10285 } else { 10286 // Invalid 10287 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10288 } 10289 if (LCanPointeeTy != RCanPointeeTy) { 10290 // Treat NULL constant as a special case in OpenCL. 10291 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10292 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10293 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10294 Diag(Loc, 10295 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10296 << LHSType << RHSType << 0 /* comparison */ 10297 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10298 } 10299 } 10300 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10301 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10302 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10303 : CK_BitCast; 10304 if (LHSIsNull && !RHSIsNull) 10305 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10306 else 10307 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10308 } 10309 return computeResultTy(); 10310 } 10311 10312 if (getLangOpts().CPlusPlus) { 10313 // C++ [expr.eq]p4: 10314 // Two operands of type std::nullptr_t or one operand of type 10315 // std::nullptr_t and the other a null pointer constant compare equal. 10316 if (!IsRelational && LHSIsNull && RHSIsNull) { 10317 if (LHSType->isNullPtrType()) { 10318 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10319 return computeResultTy(); 10320 } 10321 if (RHSType->isNullPtrType()) { 10322 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10323 return computeResultTy(); 10324 } 10325 } 10326 10327 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10328 // These aren't covered by the composite pointer type rules. 10329 if (!IsRelational && RHSType->isNullPtrType() && 10330 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10331 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10332 return computeResultTy(); 10333 } 10334 if (!IsRelational && LHSType->isNullPtrType() && 10335 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10336 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10337 return computeResultTy(); 10338 } 10339 10340 if (IsRelational && 10341 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10342 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10343 // HACK: Relational comparison of nullptr_t against a pointer type is 10344 // invalid per DR583, but we allow it within std::less<> and friends, 10345 // since otherwise common uses of it break. 10346 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10347 // friends to have std::nullptr_t overload candidates. 10348 DeclContext *DC = CurContext; 10349 if (isa<FunctionDecl>(DC)) 10350 DC = DC->getParent(); 10351 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10352 if (CTSD->isInStdNamespace() && 10353 llvm::StringSwitch<bool>(CTSD->getName()) 10354 .Cases("less", "less_equal", "greater", "greater_equal", true) 10355 .Default(false)) { 10356 if (RHSType->isNullPtrType()) 10357 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10358 else 10359 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10360 return computeResultTy(); 10361 } 10362 } 10363 } 10364 10365 // C++ [expr.eq]p2: 10366 // If at least one operand is a pointer to member, [...] bring them to 10367 // their composite pointer type. 10368 if (!IsRelational && 10369 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10370 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10371 return QualType(); 10372 else 10373 return computeResultTy(); 10374 } 10375 } 10376 10377 // Handle block pointer types. 10378 if (!IsRelational && LHSType->isBlockPointerType() && 10379 RHSType->isBlockPointerType()) { 10380 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10381 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10382 10383 if (!LHSIsNull && !RHSIsNull && 10384 !Context.typesAreCompatible(lpointee, rpointee)) { 10385 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10386 << LHSType << RHSType << LHS.get()->getSourceRange() 10387 << RHS.get()->getSourceRange(); 10388 } 10389 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10390 return computeResultTy(); 10391 } 10392 10393 // Allow block pointers to be compared with null pointer constants. 10394 if (!IsRelational 10395 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10396 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10397 if (!LHSIsNull && !RHSIsNull) { 10398 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10399 ->getPointeeType()->isVoidType()) 10400 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10401 ->getPointeeType()->isVoidType()))) 10402 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10403 << LHSType << RHSType << LHS.get()->getSourceRange() 10404 << RHS.get()->getSourceRange(); 10405 } 10406 if (LHSIsNull && !RHSIsNull) 10407 LHS = ImpCastExprToType(LHS.get(), RHSType, 10408 RHSType->isPointerType() ? CK_BitCast 10409 : CK_AnyPointerToBlockPointerCast); 10410 else 10411 RHS = ImpCastExprToType(RHS.get(), LHSType, 10412 LHSType->isPointerType() ? CK_BitCast 10413 : CK_AnyPointerToBlockPointerCast); 10414 return computeResultTy(); 10415 } 10416 10417 if (LHSType->isObjCObjectPointerType() || 10418 RHSType->isObjCObjectPointerType()) { 10419 const PointerType *LPT = LHSType->getAs<PointerType>(); 10420 const PointerType *RPT = RHSType->getAs<PointerType>(); 10421 if (LPT || RPT) { 10422 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10423 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10424 10425 if (!LPtrToVoid && !RPtrToVoid && 10426 !Context.typesAreCompatible(LHSType, RHSType)) { 10427 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10428 /*isError*/false); 10429 } 10430 if (LHSIsNull && !RHSIsNull) { 10431 Expr *E = LHS.get(); 10432 if (getLangOpts().ObjCAutoRefCount) 10433 CheckObjCConversion(SourceRange(), RHSType, E, 10434 CCK_ImplicitConversion); 10435 LHS = ImpCastExprToType(E, RHSType, 10436 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10437 } 10438 else { 10439 Expr *E = RHS.get(); 10440 if (getLangOpts().ObjCAutoRefCount) 10441 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10442 /*Diagnose=*/true, 10443 /*DiagnoseCFAudited=*/false, Opc); 10444 RHS = ImpCastExprToType(E, LHSType, 10445 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10446 } 10447 return computeResultTy(); 10448 } 10449 if (LHSType->isObjCObjectPointerType() && 10450 RHSType->isObjCObjectPointerType()) { 10451 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10452 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10453 /*isError*/false); 10454 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10455 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10456 10457 if (LHSIsNull && !RHSIsNull) 10458 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10459 else 10460 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10461 return computeResultTy(); 10462 } 10463 10464 if (!IsRelational && LHSType->isBlockPointerType() && 10465 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10466 LHS = ImpCastExprToType(LHS.get(), RHSType, 10467 CK_BlockPointerToObjCPointerCast); 10468 return computeResultTy(); 10469 } else if (!IsRelational && 10470 LHSType->isBlockCompatibleObjCPointerType(Context) && 10471 RHSType->isBlockPointerType()) { 10472 RHS = ImpCastExprToType(RHS.get(), LHSType, 10473 CK_BlockPointerToObjCPointerCast); 10474 return computeResultTy(); 10475 } 10476 } 10477 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10478 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10479 unsigned DiagID = 0; 10480 bool isError = false; 10481 if (LangOpts.DebuggerSupport) { 10482 // Under a debugger, allow the comparison of pointers to integers, 10483 // since users tend to want to compare addresses. 10484 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10485 (RHSIsNull && RHSType->isIntegerType())) { 10486 if (IsRelational) { 10487 isError = getLangOpts().CPlusPlus; 10488 DiagID = 10489 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10490 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10491 } 10492 } else if (getLangOpts().CPlusPlus) { 10493 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10494 isError = true; 10495 } else if (IsRelational) 10496 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10497 else 10498 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10499 10500 if (DiagID) { 10501 Diag(Loc, DiagID) 10502 << LHSType << RHSType << LHS.get()->getSourceRange() 10503 << RHS.get()->getSourceRange(); 10504 if (isError) 10505 return QualType(); 10506 } 10507 10508 if (LHSType->isIntegerType()) 10509 LHS = ImpCastExprToType(LHS.get(), RHSType, 10510 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10511 else 10512 RHS = ImpCastExprToType(RHS.get(), LHSType, 10513 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10514 return computeResultTy(); 10515 } 10516 10517 // Handle block pointers. 10518 if (!IsRelational && RHSIsNull 10519 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10520 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10521 return computeResultTy(); 10522 } 10523 if (!IsRelational && LHSIsNull 10524 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10525 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10526 return computeResultTy(); 10527 } 10528 10529 if (getLangOpts().OpenCLVersion >= 200) { 10530 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10531 return computeResultTy(); 10532 } 10533 10534 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10535 return computeResultTy(); 10536 } 10537 10538 if (LHSIsNull && RHSType->isQueueT()) { 10539 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10540 return computeResultTy(); 10541 } 10542 10543 if (LHSType->isQueueT() && RHSIsNull) { 10544 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10545 return computeResultTy(); 10546 } 10547 } 10548 10549 return InvalidOperands(Loc, LHS, RHS); 10550 } 10551 10552 // Return a signed ext_vector_type that is of identical size and number of 10553 // elements. For floating point vectors, return an integer type of identical 10554 // size and number of elements. In the non ext_vector_type case, search from 10555 // the largest type to the smallest type to avoid cases where long long == long, 10556 // where long gets picked over long long. 10557 QualType Sema::GetSignedVectorType(QualType V) { 10558 const VectorType *VTy = V->getAs<VectorType>(); 10559 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10560 10561 if (isa<ExtVectorType>(VTy)) { 10562 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10563 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10564 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10565 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10566 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10567 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10568 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10569 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10570 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10571 "Unhandled vector element size in vector compare"); 10572 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10573 } 10574 10575 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10576 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10577 VectorType::GenericVector); 10578 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10579 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10580 VectorType::GenericVector); 10581 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10582 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10583 VectorType::GenericVector); 10584 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10585 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10586 VectorType::GenericVector); 10587 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10588 "Unhandled vector element size in vector compare"); 10589 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10590 VectorType::GenericVector); 10591 } 10592 10593 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10594 /// operates on extended vector types. Instead of producing an IntTy result, 10595 /// like a scalar comparison, a vector comparison produces a vector of integer 10596 /// types. 10597 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10598 SourceLocation Loc, 10599 BinaryOperatorKind Opc) { 10600 // Check to make sure we're operating on vectors of the same type and width, 10601 // Allowing one side to be a scalar of element type. 10602 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10603 /*AllowBothBool*/true, 10604 /*AllowBoolConversions*/getLangOpts().ZVector); 10605 if (vType.isNull()) 10606 return vType; 10607 10608 QualType LHSType = LHS.get()->getType(); 10609 10610 // If AltiVec, the comparison results in a numeric type, i.e. 10611 // bool for C++, int for C 10612 if (getLangOpts().AltiVec && 10613 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10614 return Context.getLogicalOperationType(); 10615 10616 // For non-floating point types, check for self-comparisons of the form 10617 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10618 // often indicate logic errors in the program. 10619 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10620 10621 // Check for comparisons of floating point operands using != and ==. 10622 if (BinaryOperator::isEqualityOp(Opc) && 10623 LHSType->hasFloatingRepresentation()) { 10624 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10625 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10626 } 10627 10628 // Return a signed type for the vector. 10629 return GetSignedVectorType(vType); 10630 } 10631 10632 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10633 SourceLocation Loc) { 10634 // Ensure that either both operands are of the same vector type, or 10635 // one operand is of a vector type and the other is of its element type. 10636 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10637 /*AllowBothBool*/true, 10638 /*AllowBoolConversions*/false); 10639 if (vType.isNull()) 10640 return InvalidOperands(Loc, LHS, RHS); 10641 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10642 vType->hasFloatingRepresentation()) 10643 return InvalidOperands(Loc, LHS, RHS); 10644 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10645 // usage of the logical operators && and || with vectors in C. This 10646 // check could be notionally dropped. 10647 if (!getLangOpts().CPlusPlus && 10648 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10649 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10650 10651 return GetSignedVectorType(LHS.get()->getType()); 10652 } 10653 10654 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10655 SourceLocation Loc, 10656 BinaryOperatorKind Opc) { 10657 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10658 10659 bool IsCompAssign = 10660 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10661 10662 if (LHS.get()->getType()->isVectorType() || 10663 RHS.get()->getType()->isVectorType()) { 10664 if (LHS.get()->getType()->hasIntegerRepresentation() && 10665 RHS.get()->getType()->hasIntegerRepresentation()) 10666 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10667 /*AllowBothBool*/true, 10668 /*AllowBoolConversions*/getLangOpts().ZVector); 10669 return InvalidOperands(Loc, LHS, RHS); 10670 } 10671 10672 if (Opc == BO_And) 10673 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10674 10675 ExprResult LHSResult = LHS, RHSResult = RHS; 10676 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10677 IsCompAssign); 10678 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10679 return QualType(); 10680 LHS = LHSResult.get(); 10681 RHS = RHSResult.get(); 10682 10683 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10684 return compType; 10685 return InvalidOperands(Loc, LHS, RHS); 10686 } 10687 10688 // C99 6.5.[13,14] 10689 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10690 SourceLocation Loc, 10691 BinaryOperatorKind Opc) { 10692 // Check vector operands differently. 10693 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10694 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10695 10696 // Diagnose cases where the user write a logical and/or but probably meant a 10697 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10698 // is a constant. 10699 if (LHS.get()->getType()->isIntegerType() && 10700 !LHS.get()->getType()->isBooleanType() && 10701 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10702 // Don't warn in macros or template instantiations. 10703 !Loc.isMacroID() && !inTemplateInstantiation()) { 10704 // If the RHS can be constant folded, and if it constant folds to something 10705 // that isn't 0 or 1 (which indicate a potential logical operation that 10706 // happened to fold to true/false) then warn. 10707 // Parens on the RHS are ignored. 10708 llvm::APSInt Result; 10709 if (RHS.get()->EvaluateAsInt(Result, Context)) 10710 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10711 !RHS.get()->getExprLoc().isMacroID()) || 10712 (Result != 0 && Result != 1)) { 10713 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10714 << RHS.get()->getSourceRange() 10715 << (Opc == BO_LAnd ? "&&" : "||"); 10716 // Suggest replacing the logical operator with the bitwise version 10717 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10718 << (Opc == BO_LAnd ? "&" : "|") 10719 << FixItHint::CreateReplacement(SourceRange( 10720 Loc, getLocForEndOfToken(Loc)), 10721 Opc == BO_LAnd ? "&" : "|"); 10722 if (Opc == BO_LAnd) 10723 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10724 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10725 << FixItHint::CreateRemoval( 10726 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10727 RHS.get()->getEndLoc())); 10728 } 10729 } 10730 10731 if (!Context.getLangOpts().CPlusPlus) { 10732 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10733 // not operate on the built-in scalar and vector float types. 10734 if (Context.getLangOpts().OpenCL && 10735 Context.getLangOpts().OpenCLVersion < 120) { 10736 if (LHS.get()->getType()->isFloatingType() || 10737 RHS.get()->getType()->isFloatingType()) 10738 return InvalidOperands(Loc, LHS, RHS); 10739 } 10740 10741 LHS = UsualUnaryConversions(LHS.get()); 10742 if (LHS.isInvalid()) 10743 return QualType(); 10744 10745 RHS = UsualUnaryConversions(RHS.get()); 10746 if (RHS.isInvalid()) 10747 return QualType(); 10748 10749 if (!LHS.get()->getType()->isScalarType() || 10750 !RHS.get()->getType()->isScalarType()) 10751 return InvalidOperands(Loc, LHS, RHS); 10752 10753 return Context.IntTy; 10754 } 10755 10756 // The following is safe because we only use this method for 10757 // non-overloadable operands. 10758 10759 // C++ [expr.log.and]p1 10760 // C++ [expr.log.or]p1 10761 // The operands are both contextually converted to type bool. 10762 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10763 if (LHSRes.isInvalid()) 10764 return InvalidOperands(Loc, LHS, RHS); 10765 LHS = LHSRes; 10766 10767 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10768 if (RHSRes.isInvalid()) 10769 return InvalidOperands(Loc, LHS, RHS); 10770 RHS = RHSRes; 10771 10772 // C++ [expr.log.and]p2 10773 // C++ [expr.log.or]p2 10774 // The result is a bool. 10775 return Context.BoolTy; 10776 } 10777 10778 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10779 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10780 if (!ME) return false; 10781 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10782 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10783 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10784 if (!Base) return false; 10785 return Base->getMethodDecl() != nullptr; 10786 } 10787 10788 /// Is the given expression (which must be 'const') a reference to a 10789 /// variable which was originally non-const, but which has become 10790 /// 'const' due to being captured within a block? 10791 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10792 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10793 assert(E->isLValue() && E->getType().isConstQualified()); 10794 E = E->IgnoreParens(); 10795 10796 // Must be a reference to a declaration from an enclosing scope. 10797 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10798 if (!DRE) return NCCK_None; 10799 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10800 10801 // The declaration must be a variable which is not declared 'const'. 10802 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10803 if (!var) return NCCK_None; 10804 if (var->getType().isConstQualified()) return NCCK_None; 10805 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10806 10807 // Decide whether the first capture was for a block or a lambda. 10808 DeclContext *DC = S.CurContext, *Prev = nullptr; 10809 // Decide whether the first capture was for a block or a lambda. 10810 while (DC) { 10811 // For init-capture, it is possible that the variable belongs to the 10812 // template pattern of the current context. 10813 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10814 if (var->isInitCapture() && 10815 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10816 break; 10817 if (DC == var->getDeclContext()) 10818 break; 10819 Prev = DC; 10820 DC = DC->getParent(); 10821 } 10822 // Unless we have an init-capture, we've gone one step too far. 10823 if (!var->isInitCapture()) 10824 DC = Prev; 10825 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10826 } 10827 10828 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10829 Ty = Ty.getNonReferenceType(); 10830 if (IsDereference && Ty->isPointerType()) 10831 Ty = Ty->getPointeeType(); 10832 return !Ty.isConstQualified(); 10833 } 10834 10835 // Update err_typecheck_assign_const and note_typecheck_assign_const 10836 // when this enum is changed. 10837 enum { 10838 ConstFunction, 10839 ConstVariable, 10840 ConstMember, 10841 ConstMethod, 10842 NestedConstMember, 10843 ConstUnknown, // Keep as last element 10844 }; 10845 10846 /// Emit the "read-only variable not assignable" error and print notes to give 10847 /// more information about why the variable is not assignable, such as pointing 10848 /// to the declaration of a const variable, showing that a method is const, or 10849 /// that the function is returning a const reference. 10850 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10851 SourceLocation Loc) { 10852 SourceRange ExprRange = E->getSourceRange(); 10853 10854 // Only emit one error on the first const found. All other consts will emit 10855 // a note to the error. 10856 bool DiagnosticEmitted = false; 10857 10858 // Track if the current expression is the result of a dereference, and if the 10859 // next checked expression is the result of a dereference. 10860 bool IsDereference = false; 10861 bool NextIsDereference = false; 10862 10863 // Loop to process MemberExpr chains. 10864 while (true) { 10865 IsDereference = NextIsDereference; 10866 10867 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10868 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10869 NextIsDereference = ME->isArrow(); 10870 const ValueDecl *VD = ME->getMemberDecl(); 10871 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10872 // Mutable fields can be modified even if the class is const. 10873 if (Field->isMutable()) { 10874 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10875 break; 10876 } 10877 10878 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10879 if (!DiagnosticEmitted) { 10880 S.Diag(Loc, diag::err_typecheck_assign_const) 10881 << ExprRange << ConstMember << false /*static*/ << Field 10882 << Field->getType(); 10883 DiagnosticEmitted = true; 10884 } 10885 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10886 << ConstMember << false /*static*/ << Field << Field->getType() 10887 << Field->getSourceRange(); 10888 } 10889 E = ME->getBase(); 10890 continue; 10891 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10892 if (VDecl->getType().isConstQualified()) { 10893 if (!DiagnosticEmitted) { 10894 S.Diag(Loc, diag::err_typecheck_assign_const) 10895 << ExprRange << ConstMember << true /*static*/ << VDecl 10896 << VDecl->getType(); 10897 DiagnosticEmitted = true; 10898 } 10899 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10900 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10901 << VDecl->getSourceRange(); 10902 } 10903 // Static fields do not inherit constness from parents. 10904 break; 10905 } 10906 break; // End MemberExpr 10907 } else if (const ArraySubscriptExpr *ASE = 10908 dyn_cast<ArraySubscriptExpr>(E)) { 10909 E = ASE->getBase()->IgnoreParenImpCasts(); 10910 continue; 10911 } else if (const ExtVectorElementExpr *EVE = 10912 dyn_cast<ExtVectorElementExpr>(E)) { 10913 E = EVE->getBase()->IgnoreParenImpCasts(); 10914 continue; 10915 } 10916 break; 10917 } 10918 10919 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10920 // Function calls 10921 const FunctionDecl *FD = CE->getDirectCallee(); 10922 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10923 if (!DiagnosticEmitted) { 10924 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10925 << ConstFunction << FD; 10926 DiagnosticEmitted = true; 10927 } 10928 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10929 diag::note_typecheck_assign_const) 10930 << ConstFunction << FD << FD->getReturnType() 10931 << FD->getReturnTypeSourceRange(); 10932 } 10933 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10934 // Point to variable declaration. 10935 if (const ValueDecl *VD = DRE->getDecl()) { 10936 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10937 if (!DiagnosticEmitted) { 10938 S.Diag(Loc, diag::err_typecheck_assign_const) 10939 << ExprRange << ConstVariable << VD << VD->getType(); 10940 DiagnosticEmitted = true; 10941 } 10942 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10943 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10944 } 10945 } 10946 } else if (isa<CXXThisExpr>(E)) { 10947 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10948 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10949 if (MD->isConst()) { 10950 if (!DiagnosticEmitted) { 10951 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10952 << ConstMethod << MD; 10953 DiagnosticEmitted = true; 10954 } 10955 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10956 << ConstMethod << MD << MD->getSourceRange(); 10957 } 10958 } 10959 } 10960 } 10961 10962 if (DiagnosticEmitted) 10963 return; 10964 10965 // Can't determine a more specific message, so display the generic error. 10966 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10967 } 10968 10969 enum OriginalExprKind { 10970 OEK_Variable, 10971 OEK_Member, 10972 OEK_LValue 10973 }; 10974 10975 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10976 const RecordType *Ty, 10977 SourceLocation Loc, SourceRange Range, 10978 OriginalExprKind OEK, 10979 bool &DiagnosticEmitted, 10980 bool IsNested = false) { 10981 // We walk the record hierarchy breadth-first to ensure that we print 10982 // diagnostics in field nesting order. 10983 // First, check every field for constness. 10984 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10985 if (Field->getType().isConstQualified()) { 10986 if (!DiagnosticEmitted) { 10987 S.Diag(Loc, diag::err_typecheck_assign_const) 10988 << Range << NestedConstMember << OEK << VD 10989 << IsNested << Field; 10990 DiagnosticEmitted = true; 10991 } 10992 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10993 << NestedConstMember << IsNested << Field 10994 << Field->getType() << Field->getSourceRange(); 10995 } 10996 } 10997 // Then, recurse. 10998 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10999 QualType FTy = Field->getType(); 11000 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 11001 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 11002 OEK, DiagnosticEmitted, true); 11003 } 11004 } 11005 11006 /// Emit an error for the case where a record we are trying to assign to has a 11007 /// const-qualified field somewhere in its hierarchy. 11008 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11009 SourceLocation Loc) { 11010 QualType Ty = E->getType(); 11011 assert(Ty->isRecordType() && "lvalue was not record?"); 11012 SourceRange Range = E->getSourceRange(); 11013 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11014 bool DiagEmitted = false; 11015 11016 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11017 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11018 Range, OEK_Member, DiagEmitted); 11019 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11020 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11021 Range, OEK_Variable, DiagEmitted); 11022 else 11023 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11024 Range, OEK_LValue, DiagEmitted); 11025 if (!DiagEmitted) 11026 DiagnoseConstAssignment(S, E, Loc); 11027 } 11028 11029 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11030 /// emit an error and return true. If so, return false. 11031 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11032 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11033 11034 S.CheckShadowingDeclModification(E, Loc); 11035 11036 SourceLocation OrigLoc = Loc; 11037 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11038 &Loc); 11039 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11040 IsLV = Expr::MLV_InvalidMessageExpression; 11041 if (IsLV == Expr::MLV_Valid) 11042 return false; 11043 11044 unsigned DiagID = 0; 11045 bool NeedType = false; 11046 switch (IsLV) { // C99 6.5.16p2 11047 case Expr::MLV_ConstQualified: 11048 // Use a specialized diagnostic when we're assigning to an object 11049 // from an enclosing function or block. 11050 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11051 if (NCCK == NCCK_Block) 11052 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11053 else 11054 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11055 break; 11056 } 11057 11058 // In ARC, use some specialized diagnostics for occasions where we 11059 // infer 'const'. These are always pseudo-strong variables. 11060 if (S.getLangOpts().ObjCAutoRefCount) { 11061 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11062 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11063 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11064 11065 // Use the normal diagnostic if it's pseudo-__strong but the 11066 // user actually wrote 'const'. 11067 if (var->isARCPseudoStrong() && 11068 (!var->getTypeSourceInfo() || 11069 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11070 // There are two pseudo-strong cases: 11071 // - self 11072 ObjCMethodDecl *method = S.getCurMethodDecl(); 11073 if (method && var == method->getSelfDecl()) 11074 DiagID = method->isClassMethod() 11075 ? diag::err_typecheck_arc_assign_self_class_method 11076 : diag::err_typecheck_arc_assign_self; 11077 11078 // - fast enumeration variables 11079 else 11080 DiagID = diag::err_typecheck_arr_assign_enumeration; 11081 11082 SourceRange Assign; 11083 if (Loc != OrigLoc) 11084 Assign = SourceRange(OrigLoc, OrigLoc); 11085 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11086 // We need to preserve the AST regardless, so migration tool 11087 // can do its job. 11088 return false; 11089 } 11090 } 11091 } 11092 11093 // If none of the special cases above are triggered, then this is a 11094 // simple const assignment. 11095 if (DiagID == 0) { 11096 DiagnoseConstAssignment(S, E, Loc); 11097 return true; 11098 } 11099 11100 break; 11101 case Expr::MLV_ConstAddrSpace: 11102 DiagnoseConstAssignment(S, E, Loc); 11103 return true; 11104 case Expr::MLV_ConstQualifiedField: 11105 DiagnoseRecursiveConstFields(S, E, Loc); 11106 return true; 11107 case Expr::MLV_ArrayType: 11108 case Expr::MLV_ArrayTemporary: 11109 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11110 NeedType = true; 11111 break; 11112 case Expr::MLV_NotObjectType: 11113 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11114 NeedType = true; 11115 break; 11116 case Expr::MLV_LValueCast: 11117 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11118 break; 11119 case Expr::MLV_Valid: 11120 llvm_unreachable("did not take early return for MLV_Valid"); 11121 case Expr::MLV_InvalidExpression: 11122 case Expr::MLV_MemberFunction: 11123 case Expr::MLV_ClassTemporary: 11124 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11125 break; 11126 case Expr::MLV_IncompleteType: 11127 case Expr::MLV_IncompleteVoidType: 11128 return S.RequireCompleteType(Loc, E->getType(), 11129 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11130 case Expr::MLV_DuplicateVectorComponents: 11131 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11132 break; 11133 case Expr::MLV_NoSetterProperty: 11134 llvm_unreachable("readonly properties should be processed differently"); 11135 case Expr::MLV_InvalidMessageExpression: 11136 DiagID = diag::err_readonly_message_assignment; 11137 break; 11138 case Expr::MLV_SubObjCPropertySetting: 11139 DiagID = diag::err_no_subobject_property_setting; 11140 break; 11141 } 11142 11143 SourceRange Assign; 11144 if (Loc != OrigLoc) 11145 Assign = SourceRange(OrigLoc, OrigLoc); 11146 if (NeedType) 11147 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11148 else 11149 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11150 return true; 11151 } 11152 11153 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11154 SourceLocation Loc, 11155 Sema &Sema) { 11156 if (Sema.inTemplateInstantiation()) 11157 return; 11158 if (Sema.isUnevaluatedContext()) 11159 return; 11160 if (Loc.isInvalid() || Loc.isMacroID()) 11161 return; 11162 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11163 return; 11164 11165 // C / C++ fields 11166 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11167 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11168 if (ML && MR) { 11169 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11170 return; 11171 const ValueDecl *LHSDecl = 11172 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11173 const ValueDecl *RHSDecl = 11174 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11175 if (LHSDecl != RHSDecl) 11176 return; 11177 if (LHSDecl->getType().isVolatileQualified()) 11178 return; 11179 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11180 if (RefTy->getPointeeType().isVolatileQualified()) 11181 return; 11182 11183 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11184 } 11185 11186 // Objective-C instance variables 11187 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11188 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11189 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11190 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11191 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11192 if (RL && RR && RL->getDecl() == RR->getDecl()) 11193 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11194 } 11195 } 11196 11197 // C99 6.5.16.1 11198 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11199 SourceLocation Loc, 11200 QualType CompoundType) { 11201 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11202 11203 // Verify that LHS is a modifiable lvalue, and emit error if not. 11204 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11205 return QualType(); 11206 11207 QualType LHSType = LHSExpr->getType(); 11208 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11209 CompoundType; 11210 // OpenCL v1.2 s6.1.1.1 p2: 11211 // The half data type can only be used to declare a pointer to a buffer that 11212 // contains half values 11213 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11214 LHSType->isHalfType()) { 11215 Diag(Loc, diag::err_opencl_half_load_store) << 1 11216 << LHSType.getUnqualifiedType(); 11217 return QualType(); 11218 } 11219 11220 AssignConvertType ConvTy; 11221 if (CompoundType.isNull()) { 11222 Expr *RHSCheck = RHS.get(); 11223 11224 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11225 11226 QualType LHSTy(LHSType); 11227 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11228 if (RHS.isInvalid()) 11229 return QualType(); 11230 // Special case of NSObject attributes on c-style pointer types. 11231 if (ConvTy == IncompatiblePointer && 11232 ((Context.isObjCNSObjectType(LHSType) && 11233 RHSType->isObjCObjectPointerType()) || 11234 (Context.isObjCNSObjectType(RHSType) && 11235 LHSType->isObjCObjectPointerType()))) 11236 ConvTy = Compatible; 11237 11238 if (ConvTy == Compatible && 11239 LHSType->isObjCObjectType()) 11240 Diag(Loc, diag::err_objc_object_assignment) 11241 << LHSType; 11242 11243 // If the RHS is a unary plus or minus, check to see if they = and + are 11244 // right next to each other. If so, the user may have typo'd "x =+ 4" 11245 // instead of "x += 4". 11246 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11247 RHSCheck = ICE->getSubExpr(); 11248 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11249 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11250 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11251 // Only if the two operators are exactly adjacent. 11252 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11253 // And there is a space or other character before the subexpr of the 11254 // unary +/-. We don't want to warn on "x=-1". 11255 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11256 UO->getSubExpr()->getBeginLoc().isFileID()) { 11257 Diag(Loc, diag::warn_not_compound_assign) 11258 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11259 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11260 } 11261 } 11262 11263 if (ConvTy == Compatible) { 11264 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11265 // Warn about retain cycles where a block captures the LHS, but 11266 // not if the LHS is a simple variable into which the block is 11267 // being stored...unless that variable can be captured by reference! 11268 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11269 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11270 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11271 checkRetainCycles(LHSExpr, RHS.get()); 11272 } 11273 11274 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11275 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11276 // It is safe to assign a weak reference into a strong variable. 11277 // Although this code can still have problems: 11278 // id x = self.weakProp; 11279 // id y = self.weakProp; 11280 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11281 // paths through the function. This should be revisited if 11282 // -Wrepeated-use-of-weak is made flow-sensitive. 11283 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11284 // variable, which will be valid for the current autorelease scope. 11285 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11286 RHS.get()->getBeginLoc())) 11287 getCurFunction()->markSafeWeakUse(RHS.get()); 11288 11289 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11290 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11291 } 11292 } 11293 } else { 11294 // Compound assignment "x += y" 11295 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11296 } 11297 11298 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11299 RHS.get(), AA_Assigning)) 11300 return QualType(); 11301 11302 CheckForNullPointerDereference(*this, LHSExpr); 11303 11304 // C99 6.5.16p3: The type of an assignment expression is the type of the 11305 // left operand unless the left operand has qualified type, in which case 11306 // it is the unqualified version of the type of the left operand. 11307 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11308 // is converted to the type of the assignment expression (above). 11309 // C++ 5.17p1: the type of the assignment expression is that of its left 11310 // operand. 11311 return (getLangOpts().CPlusPlus 11312 ? LHSType : LHSType.getUnqualifiedType()); 11313 } 11314 11315 // Only ignore explicit casts to void. 11316 static bool IgnoreCommaOperand(const Expr *E) { 11317 E = E->IgnoreParens(); 11318 11319 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11320 if (CE->getCastKind() == CK_ToVoid) { 11321 return true; 11322 } 11323 11324 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11325 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11326 CE->getSubExpr()->getType()->isDependentType()) { 11327 return true; 11328 } 11329 } 11330 11331 return false; 11332 } 11333 11334 // Look for instances where it is likely the comma operator is confused with 11335 // another operator. There is a whitelist of acceptable expressions for the 11336 // left hand side of the comma operator, otherwise emit a warning. 11337 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11338 // No warnings in macros 11339 if (Loc.isMacroID()) 11340 return; 11341 11342 // Don't warn in template instantiations. 11343 if (inTemplateInstantiation()) 11344 return; 11345 11346 // Scope isn't fine-grained enough to whitelist the specific cases, so 11347 // instead, skip more than needed, then call back into here with the 11348 // CommaVisitor in SemaStmt.cpp. 11349 // The whitelisted locations are the initialization and increment portions 11350 // of a for loop. The additional checks are on the condition of 11351 // if statements, do/while loops, and for loops. 11352 // Differences in scope flags for C89 mode requires the extra logic. 11353 const unsigned ForIncrementFlags = 11354 getLangOpts().C99 || getLangOpts().CPlusPlus 11355 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11356 : Scope::ContinueScope | Scope::BreakScope; 11357 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11358 const unsigned ScopeFlags = getCurScope()->getFlags(); 11359 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11360 (ScopeFlags & ForInitFlags) == ForInitFlags) 11361 return; 11362 11363 // If there are multiple comma operators used together, get the RHS of the 11364 // of the comma operator as the LHS. 11365 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11366 if (BO->getOpcode() != BO_Comma) 11367 break; 11368 LHS = BO->getRHS(); 11369 } 11370 11371 // Only allow some expressions on LHS to not warn. 11372 if (IgnoreCommaOperand(LHS)) 11373 return; 11374 11375 Diag(Loc, diag::warn_comma_operator); 11376 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11377 << LHS->getSourceRange() 11378 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11379 LangOpts.CPlusPlus ? "static_cast<void>(" 11380 : "(void)(") 11381 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11382 ")"); 11383 } 11384 11385 // C99 6.5.17 11386 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11387 SourceLocation Loc) { 11388 LHS = S.CheckPlaceholderExpr(LHS.get()); 11389 RHS = S.CheckPlaceholderExpr(RHS.get()); 11390 if (LHS.isInvalid() || RHS.isInvalid()) 11391 return QualType(); 11392 11393 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11394 // operands, but not unary promotions. 11395 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11396 11397 // So we treat the LHS as a ignored value, and in C++ we allow the 11398 // containing site to determine what should be done with the RHS. 11399 LHS = S.IgnoredValueConversions(LHS.get()); 11400 if (LHS.isInvalid()) 11401 return QualType(); 11402 11403 S.DiagnoseUnusedExprResult(LHS.get()); 11404 11405 if (!S.getLangOpts().CPlusPlus) { 11406 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11407 if (RHS.isInvalid()) 11408 return QualType(); 11409 if (!RHS.get()->getType()->isVoidType()) 11410 S.RequireCompleteType(Loc, RHS.get()->getType(), 11411 diag::err_incomplete_type); 11412 } 11413 11414 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11415 S.DiagnoseCommaOperator(LHS.get(), Loc); 11416 11417 return RHS.get()->getType(); 11418 } 11419 11420 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11421 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11422 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11423 ExprValueKind &VK, 11424 ExprObjectKind &OK, 11425 SourceLocation OpLoc, 11426 bool IsInc, bool IsPrefix) { 11427 if (Op->isTypeDependent()) 11428 return S.Context.DependentTy; 11429 11430 QualType ResType = Op->getType(); 11431 // Atomic types can be used for increment / decrement where the non-atomic 11432 // versions can, so ignore the _Atomic() specifier for the purpose of 11433 // checking. 11434 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11435 ResType = ResAtomicType->getValueType(); 11436 11437 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11438 11439 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11440 // Decrement of bool is not allowed. 11441 if (!IsInc) { 11442 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11443 return QualType(); 11444 } 11445 // Increment of bool sets it to true, but is deprecated. 11446 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11447 : diag::warn_increment_bool) 11448 << Op->getSourceRange(); 11449 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11450 // Error on enum increments and decrements in C++ mode 11451 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11452 return QualType(); 11453 } else if (ResType->isRealType()) { 11454 // OK! 11455 } else if (ResType->isPointerType()) { 11456 // C99 6.5.2.4p2, 6.5.6p2 11457 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11458 return QualType(); 11459 } else if (ResType->isObjCObjectPointerType()) { 11460 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11461 // Otherwise, we just need a complete type. 11462 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11463 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11464 return QualType(); 11465 } else if (ResType->isAnyComplexType()) { 11466 // C99 does not support ++/-- on complex types, we allow as an extension. 11467 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11468 << ResType << Op->getSourceRange(); 11469 } else if (ResType->isPlaceholderType()) { 11470 ExprResult PR = S.CheckPlaceholderExpr(Op); 11471 if (PR.isInvalid()) return QualType(); 11472 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11473 IsInc, IsPrefix); 11474 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11475 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11476 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11477 (ResType->getAs<VectorType>()->getVectorKind() != 11478 VectorType::AltiVecBool)) { 11479 // The z vector extensions allow ++ and -- for non-bool vectors. 11480 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11481 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11482 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11483 } else { 11484 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11485 << ResType << int(IsInc) << Op->getSourceRange(); 11486 return QualType(); 11487 } 11488 // At this point, we know we have a real, complex or pointer type. 11489 // Now make sure the operand is a modifiable lvalue. 11490 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11491 return QualType(); 11492 // In C++, a prefix increment is the same type as the operand. Otherwise 11493 // (in C or with postfix), the increment is the unqualified type of the 11494 // operand. 11495 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11496 VK = VK_LValue; 11497 OK = Op->getObjectKind(); 11498 return ResType; 11499 } else { 11500 VK = VK_RValue; 11501 return ResType.getUnqualifiedType(); 11502 } 11503 } 11504 11505 11506 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11507 /// This routine allows us to typecheck complex/recursive expressions 11508 /// where the declaration is needed for type checking. We only need to 11509 /// handle cases when the expression references a function designator 11510 /// or is an lvalue. Here are some examples: 11511 /// - &(x) => x 11512 /// - &*****f => f for f a function designator. 11513 /// - &s.xx => s 11514 /// - &s.zz[1].yy -> s, if zz is an array 11515 /// - *(x + 1) -> x, if x is an array 11516 /// - &"123"[2] -> 0 11517 /// - & __real__ x -> x 11518 static ValueDecl *getPrimaryDecl(Expr *E) { 11519 switch (E->getStmtClass()) { 11520 case Stmt::DeclRefExprClass: 11521 return cast<DeclRefExpr>(E)->getDecl(); 11522 case Stmt::MemberExprClass: 11523 // If this is an arrow operator, the address is an offset from 11524 // the base's value, so the object the base refers to is 11525 // irrelevant. 11526 if (cast<MemberExpr>(E)->isArrow()) 11527 return nullptr; 11528 // Otherwise, the expression refers to a part of the base 11529 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11530 case Stmt::ArraySubscriptExprClass: { 11531 // FIXME: This code shouldn't be necessary! We should catch the implicit 11532 // promotion of register arrays earlier. 11533 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11534 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11535 if (ICE->getSubExpr()->getType()->isArrayType()) 11536 return getPrimaryDecl(ICE->getSubExpr()); 11537 } 11538 return nullptr; 11539 } 11540 case Stmt::UnaryOperatorClass: { 11541 UnaryOperator *UO = cast<UnaryOperator>(E); 11542 11543 switch(UO->getOpcode()) { 11544 case UO_Real: 11545 case UO_Imag: 11546 case UO_Extension: 11547 return getPrimaryDecl(UO->getSubExpr()); 11548 default: 11549 return nullptr; 11550 } 11551 } 11552 case Stmt::ParenExprClass: 11553 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11554 case Stmt::ImplicitCastExprClass: 11555 // If the result of an implicit cast is an l-value, we care about 11556 // the sub-expression; otherwise, the result here doesn't matter. 11557 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11558 default: 11559 return nullptr; 11560 } 11561 } 11562 11563 namespace { 11564 enum { 11565 AO_Bit_Field = 0, 11566 AO_Vector_Element = 1, 11567 AO_Property_Expansion = 2, 11568 AO_Register_Variable = 3, 11569 AO_No_Error = 4 11570 }; 11571 } 11572 /// Diagnose invalid operand for address of operations. 11573 /// 11574 /// \param Type The type of operand which cannot have its address taken. 11575 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11576 Expr *E, unsigned Type) { 11577 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11578 } 11579 11580 /// CheckAddressOfOperand - The operand of & must be either a function 11581 /// designator or an lvalue designating an object. If it is an lvalue, the 11582 /// object cannot be declared with storage class register or be a bit field. 11583 /// Note: The usual conversions are *not* applied to the operand of the & 11584 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11585 /// In C++, the operand might be an overloaded function name, in which case 11586 /// we allow the '&' but retain the overloaded-function type. 11587 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11588 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11589 if (PTy->getKind() == BuiltinType::Overload) { 11590 Expr *E = OrigOp.get()->IgnoreParens(); 11591 if (!isa<OverloadExpr>(E)) { 11592 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11593 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11594 << OrigOp.get()->getSourceRange(); 11595 return QualType(); 11596 } 11597 11598 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11599 if (isa<UnresolvedMemberExpr>(Ovl)) 11600 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11601 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11602 << OrigOp.get()->getSourceRange(); 11603 return QualType(); 11604 } 11605 11606 return Context.OverloadTy; 11607 } 11608 11609 if (PTy->getKind() == BuiltinType::UnknownAny) 11610 return Context.UnknownAnyTy; 11611 11612 if (PTy->getKind() == BuiltinType::BoundMember) { 11613 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11614 << OrigOp.get()->getSourceRange(); 11615 return QualType(); 11616 } 11617 11618 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11619 if (OrigOp.isInvalid()) return QualType(); 11620 } 11621 11622 if (OrigOp.get()->isTypeDependent()) 11623 return Context.DependentTy; 11624 11625 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11626 11627 // Make sure to ignore parentheses in subsequent checks 11628 Expr *op = OrigOp.get()->IgnoreParens(); 11629 11630 // In OpenCL captures for blocks called as lambda functions 11631 // are located in the private address space. Blocks used in 11632 // enqueue_kernel can be located in a different address space 11633 // depending on a vendor implementation. Thus preventing 11634 // taking an address of the capture to avoid invalid AS casts. 11635 if (LangOpts.OpenCL) { 11636 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11637 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11638 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11639 return QualType(); 11640 } 11641 } 11642 11643 if (getLangOpts().C99) { 11644 // Implement C99-only parts of addressof rules. 11645 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11646 if (uOp->getOpcode() == UO_Deref) 11647 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11648 // (assuming the deref expression is valid). 11649 return uOp->getSubExpr()->getType(); 11650 } 11651 // Technically, there should be a check for array subscript 11652 // expressions here, but the result of one is always an lvalue anyway. 11653 } 11654 ValueDecl *dcl = getPrimaryDecl(op); 11655 11656 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11657 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11658 op->getBeginLoc())) 11659 return QualType(); 11660 11661 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11662 unsigned AddressOfError = AO_No_Error; 11663 11664 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11665 bool sfinae = (bool)isSFINAEContext(); 11666 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11667 : diag::ext_typecheck_addrof_temporary) 11668 << op->getType() << op->getSourceRange(); 11669 if (sfinae) 11670 return QualType(); 11671 // Materialize the temporary as an lvalue so that we can take its address. 11672 OrigOp = op = 11673 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11674 } else if (isa<ObjCSelectorExpr>(op)) { 11675 return Context.getPointerType(op->getType()); 11676 } else if (lval == Expr::LV_MemberFunction) { 11677 // If it's an instance method, make a member pointer. 11678 // The expression must have exactly the form &A::foo. 11679 11680 // If the underlying expression isn't a decl ref, give up. 11681 if (!isa<DeclRefExpr>(op)) { 11682 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11683 << OrigOp.get()->getSourceRange(); 11684 return QualType(); 11685 } 11686 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11687 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11688 11689 // The id-expression was parenthesized. 11690 if (OrigOp.get() != DRE) { 11691 Diag(OpLoc, diag::err_parens_pointer_member_function) 11692 << OrigOp.get()->getSourceRange(); 11693 11694 // The method was named without a qualifier. 11695 } else if (!DRE->getQualifier()) { 11696 if (MD->getParent()->getName().empty()) 11697 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11698 << op->getSourceRange(); 11699 else { 11700 SmallString<32> Str; 11701 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11702 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11703 << op->getSourceRange() 11704 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11705 } 11706 } 11707 11708 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11709 if (isa<CXXDestructorDecl>(MD)) 11710 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11711 11712 QualType MPTy = Context.getMemberPointerType( 11713 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11714 // Under the MS ABI, lock down the inheritance model now. 11715 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11716 (void)isCompleteType(OpLoc, MPTy); 11717 return MPTy; 11718 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11719 // C99 6.5.3.2p1 11720 // The operand must be either an l-value or a function designator 11721 if (!op->getType()->isFunctionType()) { 11722 // Use a special diagnostic for loads from property references. 11723 if (isa<PseudoObjectExpr>(op)) { 11724 AddressOfError = AO_Property_Expansion; 11725 } else { 11726 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11727 << op->getType() << op->getSourceRange(); 11728 return QualType(); 11729 } 11730 } 11731 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11732 // The operand cannot be a bit-field 11733 AddressOfError = AO_Bit_Field; 11734 } else if (op->getObjectKind() == OK_VectorComponent) { 11735 // The operand cannot be an element of a vector 11736 AddressOfError = AO_Vector_Element; 11737 } else if (dcl) { // C99 6.5.3.2p1 11738 // We have an lvalue with a decl. Make sure the decl is not declared 11739 // with the register storage-class specifier. 11740 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11741 // in C++ it is not error to take address of a register 11742 // variable (c++03 7.1.1P3) 11743 if (vd->getStorageClass() == SC_Register && 11744 !getLangOpts().CPlusPlus) { 11745 AddressOfError = AO_Register_Variable; 11746 } 11747 } else if (isa<MSPropertyDecl>(dcl)) { 11748 AddressOfError = AO_Property_Expansion; 11749 } else if (isa<FunctionTemplateDecl>(dcl)) { 11750 return Context.OverloadTy; 11751 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11752 // Okay: we can take the address of a field. 11753 // Could be a pointer to member, though, if there is an explicit 11754 // scope qualifier for the class. 11755 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11756 DeclContext *Ctx = dcl->getDeclContext(); 11757 if (Ctx && Ctx->isRecord()) { 11758 if (dcl->getType()->isReferenceType()) { 11759 Diag(OpLoc, 11760 diag::err_cannot_form_pointer_to_member_of_reference_type) 11761 << dcl->getDeclName() << dcl->getType(); 11762 return QualType(); 11763 } 11764 11765 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11766 Ctx = Ctx->getParent(); 11767 11768 QualType MPTy = Context.getMemberPointerType( 11769 op->getType(), 11770 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11771 // Under the MS ABI, lock down the inheritance model now. 11772 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11773 (void)isCompleteType(OpLoc, MPTy); 11774 return MPTy; 11775 } 11776 } 11777 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11778 !isa<BindingDecl>(dcl)) 11779 llvm_unreachable("Unknown/unexpected decl type"); 11780 } 11781 11782 if (AddressOfError != AO_No_Error) { 11783 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11784 return QualType(); 11785 } 11786 11787 if (lval == Expr::LV_IncompleteVoidType) { 11788 // Taking the address of a void variable is technically illegal, but we 11789 // allow it in cases which are otherwise valid. 11790 // Example: "extern void x; void* y = &x;". 11791 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11792 } 11793 11794 // If the operand has type "type", the result has type "pointer to type". 11795 if (op->getType()->isObjCObjectType()) 11796 return Context.getObjCObjectPointerType(op->getType()); 11797 11798 CheckAddressOfPackedMember(op); 11799 11800 return Context.getPointerType(op->getType()); 11801 } 11802 11803 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11804 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11805 if (!DRE) 11806 return; 11807 const Decl *D = DRE->getDecl(); 11808 if (!D) 11809 return; 11810 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11811 if (!Param) 11812 return; 11813 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11814 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11815 return; 11816 if (FunctionScopeInfo *FD = S.getCurFunction()) 11817 if (!FD->ModifiedNonNullParams.count(Param)) 11818 FD->ModifiedNonNullParams.insert(Param); 11819 } 11820 11821 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11822 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11823 SourceLocation OpLoc) { 11824 if (Op->isTypeDependent()) 11825 return S.Context.DependentTy; 11826 11827 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11828 if (ConvResult.isInvalid()) 11829 return QualType(); 11830 Op = ConvResult.get(); 11831 QualType OpTy = Op->getType(); 11832 QualType Result; 11833 11834 if (isa<CXXReinterpretCastExpr>(Op)) { 11835 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11836 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11837 Op->getSourceRange()); 11838 } 11839 11840 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11841 { 11842 Result = PT->getPointeeType(); 11843 } 11844 else if (const ObjCObjectPointerType *OPT = 11845 OpTy->getAs<ObjCObjectPointerType>()) 11846 Result = OPT->getPointeeType(); 11847 else { 11848 ExprResult PR = S.CheckPlaceholderExpr(Op); 11849 if (PR.isInvalid()) return QualType(); 11850 if (PR.get() != Op) 11851 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11852 } 11853 11854 if (Result.isNull()) { 11855 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11856 << OpTy << Op->getSourceRange(); 11857 return QualType(); 11858 } 11859 11860 // Note that per both C89 and C99, indirection is always legal, even if Result 11861 // is an incomplete type or void. It would be possible to warn about 11862 // dereferencing a void pointer, but it's completely well-defined, and such a 11863 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11864 // for pointers to 'void' but is fine for any other pointer type: 11865 // 11866 // C++ [expr.unary.op]p1: 11867 // [...] the expression to which [the unary * operator] is applied shall 11868 // be a pointer to an object type, or a pointer to a function type 11869 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11870 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11871 << OpTy << Op->getSourceRange(); 11872 11873 // Dereferences are usually l-values... 11874 VK = VK_LValue; 11875 11876 // ...except that certain expressions are never l-values in C. 11877 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11878 VK = VK_RValue; 11879 11880 return Result; 11881 } 11882 11883 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11884 BinaryOperatorKind Opc; 11885 switch (Kind) { 11886 default: llvm_unreachable("Unknown binop!"); 11887 case tok::periodstar: Opc = BO_PtrMemD; break; 11888 case tok::arrowstar: Opc = BO_PtrMemI; break; 11889 case tok::star: Opc = BO_Mul; break; 11890 case tok::slash: Opc = BO_Div; break; 11891 case tok::percent: Opc = BO_Rem; break; 11892 case tok::plus: Opc = BO_Add; break; 11893 case tok::minus: Opc = BO_Sub; break; 11894 case tok::lessless: Opc = BO_Shl; break; 11895 case tok::greatergreater: Opc = BO_Shr; break; 11896 case tok::lessequal: Opc = BO_LE; break; 11897 case tok::less: Opc = BO_LT; break; 11898 case tok::greaterequal: Opc = BO_GE; break; 11899 case tok::greater: Opc = BO_GT; break; 11900 case tok::exclaimequal: Opc = BO_NE; break; 11901 case tok::equalequal: Opc = BO_EQ; break; 11902 case tok::spaceship: Opc = BO_Cmp; break; 11903 case tok::amp: Opc = BO_And; break; 11904 case tok::caret: Opc = BO_Xor; break; 11905 case tok::pipe: Opc = BO_Or; break; 11906 case tok::ampamp: Opc = BO_LAnd; break; 11907 case tok::pipepipe: Opc = BO_LOr; break; 11908 case tok::equal: Opc = BO_Assign; break; 11909 case tok::starequal: Opc = BO_MulAssign; break; 11910 case tok::slashequal: Opc = BO_DivAssign; break; 11911 case tok::percentequal: Opc = BO_RemAssign; break; 11912 case tok::plusequal: Opc = BO_AddAssign; break; 11913 case tok::minusequal: Opc = BO_SubAssign; break; 11914 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11915 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11916 case tok::ampequal: Opc = BO_AndAssign; break; 11917 case tok::caretequal: Opc = BO_XorAssign; break; 11918 case tok::pipeequal: Opc = BO_OrAssign; break; 11919 case tok::comma: Opc = BO_Comma; break; 11920 } 11921 return Opc; 11922 } 11923 11924 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11925 tok::TokenKind Kind) { 11926 UnaryOperatorKind Opc; 11927 switch (Kind) { 11928 default: llvm_unreachable("Unknown unary op!"); 11929 case tok::plusplus: Opc = UO_PreInc; break; 11930 case tok::minusminus: Opc = UO_PreDec; break; 11931 case tok::amp: Opc = UO_AddrOf; break; 11932 case tok::star: Opc = UO_Deref; break; 11933 case tok::plus: Opc = UO_Plus; break; 11934 case tok::minus: Opc = UO_Minus; break; 11935 case tok::tilde: Opc = UO_Not; break; 11936 case tok::exclaim: Opc = UO_LNot; break; 11937 case tok::kw___real: Opc = UO_Real; break; 11938 case tok::kw___imag: Opc = UO_Imag; break; 11939 case tok::kw___extension__: Opc = UO_Extension; break; 11940 } 11941 return Opc; 11942 } 11943 11944 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11945 /// This warning suppressed in the event of macro expansions. 11946 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11947 SourceLocation OpLoc, bool IsBuiltin) { 11948 if (S.inTemplateInstantiation()) 11949 return; 11950 if (S.isUnevaluatedContext()) 11951 return; 11952 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11953 return; 11954 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11955 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11956 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11957 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11958 if (!LHSDeclRef || !RHSDeclRef || 11959 LHSDeclRef->getLocation().isMacroID() || 11960 RHSDeclRef->getLocation().isMacroID()) 11961 return; 11962 const ValueDecl *LHSDecl = 11963 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11964 const ValueDecl *RHSDecl = 11965 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11966 if (LHSDecl != RHSDecl) 11967 return; 11968 if (LHSDecl->getType().isVolatileQualified()) 11969 return; 11970 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11971 if (RefTy->getPointeeType().isVolatileQualified()) 11972 return; 11973 11974 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11975 : diag::warn_self_assignment_overloaded) 11976 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11977 << RHSExpr->getSourceRange(); 11978 } 11979 11980 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11981 /// is usually indicative of introspection within the Objective-C pointer. 11982 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11983 SourceLocation OpLoc) { 11984 if (!S.getLangOpts().ObjC) 11985 return; 11986 11987 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11988 const Expr *LHS = L.get(); 11989 const Expr *RHS = R.get(); 11990 11991 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11992 ObjCPointerExpr = LHS; 11993 OtherExpr = RHS; 11994 } 11995 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11996 ObjCPointerExpr = RHS; 11997 OtherExpr = LHS; 11998 } 11999 12000 // This warning is deliberately made very specific to reduce false 12001 // positives with logic that uses '&' for hashing. This logic mainly 12002 // looks for code trying to introspect into tagged pointers, which 12003 // code should generally never do. 12004 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12005 unsigned Diag = diag::warn_objc_pointer_masking; 12006 // Determine if we are introspecting the result of performSelectorXXX. 12007 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12008 // Special case messages to -performSelector and friends, which 12009 // can return non-pointer values boxed in a pointer value. 12010 // Some clients may wish to silence warnings in this subcase. 12011 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12012 Selector S = ME->getSelector(); 12013 StringRef SelArg0 = S.getNameForSlot(0); 12014 if (SelArg0.startswith("performSelector")) 12015 Diag = diag::warn_objc_pointer_masking_performSelector; 12016 } 12017 12018 S.Diag(OpLoc, Diag) 12019 << ObjCPointerExpr->getSourceRange(); 12020 } 12021 } 12022 12023 static NamedDecl *getDeclFromExpr(Expr *E) { 12024 if (!E) 12025 return nullptr; 12026 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12027 return DRE->getDecl(); 12028 if (auto *ME = dyn_cast<MemberExpr>(E)) 12029 return ME->getMemberDecl(); 12030 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12031 return IRE->getDecl(); 12032 return nullptr; 12033 } 12034 12035 // This helper function promotes a binary operator's operands (which are of a 12036 // half vector type) to a vector of floats and then truncates the result to 12037 // a vector of either half or short. 12038 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12039 BinaryOperatorKind Opc, QualType ResultTy, 12040 ExprValueKind VK, ExprObjectKind OK, 12041 bool IsCompAssign, SourceLocation OpLoc, 12042 FPOptions FPFeatures) { 12043 auto &Context = S.getASTContext(); 12044 assert((isVector(ResultTy, Context.HalfTy) || 12045 isVector(ResultTy, Context.ShortTy)) && 12046 "Result must be a vector of half or short"); 12047 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12048 isVector(RHS.get()->getType(), Context.HalfTy) && 12049 "both operands expected to be a half vector"); 12050 12051 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12052 QualType BinOpResTy = RHS.get()->getType(); 12053 12054 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12055 // change BinOpResTy to a vector of ints. 12056 if (isVector(ResultTy, Context.ShortTy)) 12057 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12058 12059 if (IsCompAssign) 12060 return new (Context) CompoundAssignOperator( 12061 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12062 OpLoc, FPFeatures); 12063 12064 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12065 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12066 VK, OK, OpLoc, FPFeatures); 12067 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12068 } 12069 12070 static std::pair<ExprResult, ExprResult> 12071 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12072 Expr *RHSExpr) { 12073 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12074 if (!S.getLangOpts().CPlusPlus) { 12075 // C cannot handle TypoExpr nodes on either side of a binop because it 12076 // doesn't handle dependent types properly, so make sure any TypoExprs have 12077 // been dealt with before checking the operands. 12078 LHS = S.CorrectDelayedTyposInExpr(LHS); 12079 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12080 if (Opc != BO_Assign) 12081 return ExprResult(E); 12082 // Avoid correcting the RHS to the same Expr as the LHS. 12083 Decl *D = getDeclFromExpr(E); 12084 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12085 }); 12086 } 12087 return std::make_pair(LHS, RHS); 12088 } 12089 12090 /// Returns true if conversion between vectors of halfs and vectors of floats 12091 /// is needed. 12092 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12093 QualType SrcType) { 12094 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12095 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12096 isVector(SrcType, Ctx.HalfTy); 12097 } 12098 12099 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12100 /// operator @p Opc at location @c TokLoc. This routine only supports 12101 /// built-in operations; ActOnBinOp handles overloaded operators. 12102 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12103 BinaryOperatorKind Opc, 12104 Expr *LHSExpr, Expr *RHSExpr) { 12105 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12106 // The syntax only allows initializer lists on the RHS of assignment, 12107 // so we don't need to worry about accepting invalid code for 12108 // non-assignment operators. 12109 // C++11 5.17p9: 12110 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12111 // of x = {} is x = T(). 12112 InitializationKind Kind = InitializationKind::CreateDirectList( 12113 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12114 InitializedEntity Entity = 12115 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12116 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12117 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12118 if (Init.isInvalid()) 12119 return Init; 12120 RHSExpr = Init.get(); 12121 } 12122 12123 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12124 QualType ResultTy; // Result type of the binary operator. 12125 // The following two variables are used for compound assignment operators 12126 QualType CompLHSTy; // Type of LHS after promotions for computation 12127 QualType CompResultTy; // Type of computation result 12128 ExprValueKind VK = VK_RValue; 12129 ExprObjectKind OK = OK_Ordinary; 12130 bool ConvertHalfVec = false; 12131 12132 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12133 if (!LHS.isUsable() || !RHS.isUsable()) 12134 return ExprError(); 12135 12136 if (getLangOpts().OpenCL) { 12137 QualType LHSTy = LHSExpr->getType(); 12138 QualType RHSTy = RHSExpr->getType(); 12139 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12140 // the ATOMIC_VAR_INIT macro. 12141 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12142 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12143 if (BO_Assign == Opc) 12144 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12145 else 12146 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12147 return ExprError(); 12148 } 12149 12150 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12151 // only with a builtin functions and therefore should be disallowed here. 12152 if (LHSTy->isImageType() || RHSTy->isImageType() || 12153 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12154 LHSTy->isPipeType() || RHSTy->isPipeType() || 12155 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12156 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12157 return ExprError(); 12158 } 12159 } 12160 12161 switch (Opc) { 12162 case BO_Assign: 12163 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12164 if (getLangOpts().CPlusPlus && 12165 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12166 VK = LHS.get()->getValueKind(); 12167 OK = LHS.get()->getObjectKind(); 12168 } 12169 if (!ResultTy.isNull()) { 12170 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12171 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12172 } 12173 RecordModifiableNonNullParam(*this, LHS.get()); 12174 break; 12175 case BO_PtrMemD: 12176 case BO_PtrMemI: 12177 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12178 Opc == BO_PtrMemI); 12179 break; 12180 case BO_Mul: 12181 case BO_Div: 12182 ConvertHalfVec = true; 12183 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12184 Opc == BO_Div); 12185 break; 12186 case BO_Rem: 12187 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12188 break; 12189 case BO_Add: 12190 ConvertHalfVec = true; 12191 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12192 break; 12193 case BO_Sub: 12194 ConvertHalfVec = true; 12195 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12196 break; 12197 case BO_Shl: 12198 case BO_Shr: 12199 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12200 break; 12201 case BO_LE: 12202 case BO_LT: 12203 case BO_GE: 12204 case BO_GT: 12205 ConvertHalfVec = true; 12206 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12207 break; 12208 case BO_EQ: 12209 case BO_NE: 12210 ConvertHalfVec = true; 12211 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12212 break; 12213 case BO_Cmp: 12214 ConvertHalfVec = true; 12215 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12216 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12217 break; 12218 case BO_And: 12219 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12220 LLVM_FALLTHROUGH; 12221 case BO_Xor: 12222 case BO_Or: 12223 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12224 break; 12225 case BO_LAnd: 12226 case BO_LOr: 12227 ConvertHalfVec = true; 12228 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12229 break; 12230 case BO_MulAssign: 12231 case BO_DivAssign: 12232 ConvertHalfVec = true; 12233 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12234 Opc == BO_DivAssign); 12235 CompLHSTy = CompResultTy; 12236 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12237 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12238 break; 12239 case BO_RemAssign: 12240 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12241 CompLHSTy = CompResultTy; 12242 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12243 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12244 break; 12245 case BO_AddAssign: 12246 ConvertHalfVec = true; 12247 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12248 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12249 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12250 break; 12251 case BO_SubAssign: 12252 ConvertHalfVec = true; 12253 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12254 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12255 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12256 break; 12257 case BO_ShlAssign: 12258 case BO_ShrAssign: 12259 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12260 CompLHSTy = CompResultTy; 12261 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12262 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12263 break; 12264 case BO_AndAssign: 12265 case BO_OrAssign: // fallthrough 12266 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12267 LLVM_FALLTHROUGH; 12268 case BO_XorAssign: 12269 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12270 CompLHSTy = CompResultTy; 12271 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12272 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12273 break; 12274 case BO_Comma: 12275 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12276 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12277 VK = RHS.get()->getValueKind(); 12278 OK = RHS.get()->getObjectKind(); 12279 } 12280 break; 12281 } 12282 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12283 return ExprError(); 12284 12285 // Some of the binary operations require promoting operands of half vector to 12286 // float vectors and truncating the result back to half vector. For now, we do 12287 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12288 // arm64). 12289 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12290 isVector(LHS.get()->getType(), Context.HalfTy) && 12291 "both sides are half vectors or neither sides are"); 12292 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12293 LHS.get()->getType()); 12294 12295 // Check for array bounds violations for both sides of the BinaryOperator 12296 CheckArrayAccess(LHS.get()); 12297 CheckArrayAccess(RHS.get()); 12298 12299 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12300 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12301 &Context.Idents.get("object_setClass"), 12302 SourceLocation(), LookupOrdinaryName); 12303 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12304 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12305 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12306 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12307 "object_setClass(") 12308 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12309 ",") 12310 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12311 } 12312 else 12313 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12314 } 12315 else if (const ObjCIvarRefExpr *OIRE = 12316 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12317 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12318 12319 // Opc is not a compound assignment if CompResultTy is null. 12320 if (CompResultTy.isNull()) { 12321 if (ConvertHalfVec) 12322 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12323 OpLoc, FPFeatures); 12324 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12325 OK, OpLoc, FPFeatures); 12326 } 12327 12328 // Handle compound assignments. 12329 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12330 OK_ObjCProperty) { 12331 VK = VK_LValue; 12332 OK = LHS.get()->getObjectKind(); 12333 } 12334 12335 if (ConvertHalfVec) 12336 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12337 OpLoc, FPFeatures); 12338 12339 return new (Context) CompoundAssignOperator( 12340 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12341 OpLoc, FPFeatures); 12342 } 12343 12344 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12345 /// operators are mixed in a way that suggests that the programmer forgot that 12346 /// comparison operators have higher precedence. The most typical example of 12347 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12348 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12349 SourceLocation OpLoc, Expr *LHSExpr, 12350 Expr *RHSExpr) { 12351 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12352 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12353 12354 // Check that one of the sides is a comparison operator and the other isn't. 12355 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12356 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12357 if (isLeftComp == isRightComp) 12358 return; 12359 12360 // Bitwise operations are sometimes used as eager logical ops. 12361 // Don't diagnose this. 12362 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12363 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12364 if (isLeftBitwise || isRightBitwise) 12365 return; 12366 12367 SourceRange DiagRange = isLeftComp 12368 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12369 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12370 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12371 SourceRange ParensRange = 12372 isLeftComp 12373 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12374 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12375 12376 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12377 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12378 SuggestParentheses(Self, OpLoc, 12379 Self.PDiag(diag::note_precedence_silence) << OpStr, 12380 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12381 SuggestParentheses(Self, OpLoc, 12382 Self.PDiag(diag::note_precedence_bitwise_first) 12383 << BinaryOperator::getOpcodeStr(Opc), 12384 ParensRange); 12385 } 12386 12387 /// It accepts a '&&' expr that is inside a '||' one. 12388 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12389 /// in parentheses. 12390 static void 12391 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12392 BinaryOperator *Bop) { 12393 assert(Bop->getOpcode() == BO_LAnd); 12394 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12395 << Bop->getSourceRange() << OpLoc; 12396 SuggestParentheses(Self, Bop->getOperatorLoc(), 12397 Self.PDiag(diag::note_precedence_silence) 12398 << Bop->getOpcodeStr(), 12399 Bop->getSourceRange()); 12400 } 12401 12402 /// Returns true if the given expression can be evaluated as a constant 12403 /// 'true'. 12404 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12405 bool Res; 12406 return !E->isValueDependent() && 12407 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12408 } 12409 12410 /// Returns true if the given expression can be evaluated as a constant 12411 /// 'false'. 12412 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12413 bool Res; 12414 return !E->isValueDependent() && 12415 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12416 } 12417 12418 /// Look for '&&' in the left hand of a '||' expr. 12419 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12420 Expr *LHSExpr, Expr *RHSExpr) { 12421 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12422 if (Bop->getOpcode() == BO_LAnd) { 12423 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12424 if (EvaluatesAsFalse(S, RHSExpr)) 12425 return; 12426 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12427 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12428 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12429 } else if (Bop->getOpcode() == BO_LOr) { 12430 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12431 // If it's "a || b && 1 || c" we didn't warn earlier for 12432 // "a || b && 1", but warn now. 12433 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12434 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12435 } 12436 } 12437 } 12438 } 12439 12440 /// Look for '&&' in the right hand of a '||' expr. 12441 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12442 Expr *LHSExpr, Expr *RHSExpr) { 12443 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12444 if (Bop->getOpcode() == BO_LAnd) { 12445 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12446 if (EvaluatesAsFalse(S, LHSExpr)) 12447 return; 12448 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12449 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12450 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12451 } 12452 } 12453 } 12454 12455 /// Look for bitwise op in the left or right hand of a bitwise op with 12456 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12457 /// the '&' expression in parentheses. 12458 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12459 SourceLocation OpLoc, Expr *SubExpr) { 12460 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12461 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12462 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12463 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12464 << Bop->getSourceRange() << OpLoc; 12465 SuggestParentheses(S, Bop->getOperatorLoc(), 12466 S.PDiag(diag::note_precedence_silence) 12467 << Bop->getOpcodeStr(), 12468 Bop->getSourceRange()); 12469 } 12470 } 12471 } 12472 12473 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12474 Expr *SubExpr, StringRef Shift) { 12475 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12476 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12477 StringRef Op = Bop->getOpcodeStr(); 12478 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12479 << Bop->getSourceRange() << OpLoc << Shift << Op; 12480 SuggestParentheses(S, Bop->getOperatorLoc(), 12481 S.PDiag(diag::note_precedence_silence) << Op, 12482 Bop->getSourceRange()); 12483 } 12484 } 12485 } 12486 12487 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12488 Expr *LHSExpr, Expr *RHSExpr) { 12489 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12490 if (!OCE) 12491 return; 12492 12493 FunctionDecl *FD = OCE->getDirectCallee(); 12494 if (!FD || !FD->isOverloadedOperator()) 12495 return; 12496 12497 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12498 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12499 return; 12500 12501 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12502 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12503 << (Kind == OO_LessLess); 12504 SuggestParentheses(S, OCE->getOperatorLoc(), 12505 S.PDiag(diag::note_precedence_silence) 12506 << (Kind == OO_LessLess ? "<<" : ">>"), 12507 OCE->getSourceRange()); 12508 SuggestParentheses( 12509 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12510 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12511 } 12512 12513 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12514 /// precedence. 12515 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12516 SourceLocation OpLoc, Expr *LHSExpr, 12517 Expr *RHSExpr){ 12518 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12519 if (BinaryOperator::isBitwiseOp(Opc)) 12520 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12521 12522 // Diagnose "arg1 & arg2 | arg3" 12523 if ((Opc == BO_Or || Opc == BO_Xor) && 12524 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12525 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12526 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12527 } 12528 12529 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12530 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12531 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12532 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12533 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12534 } 12535 12536 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12537 || Opc == BO_Shr) { 12538 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12539 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12540 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12541 } 12542 12543 // Warn on overloaded shift operators and comparisons, such as: 12544 // cout << 5 == 4; 12545 if (BinaryOperator::isComparisonOp(Opc)) 12546 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12547 } 12548 12549 // Binary Operators. 'Tok' is the token for the operator. 12550 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12551 tok::TokenKind Kind, 12552 Expr *LHSExpr, Expr *RHSExpr) { 12553 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12554 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12555 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12556 12557 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12558 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12559 12560 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12561 } 12562 12563 /// Build an overloaded binary operator expression in the given scope. 12564 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12565 BinaryOperatorKind Opc, 12566 Expr *LHS, Expr *RHS) { 12567 switch (Opc) { 12568 case BO_Assign: 12569 case BO_DivAssign: 12570 case BO_RemAssign: 12571 case BO_SubAssign: 12572 case BO_AndAssign: 12573 case BO_OrAssign: 12574 case BO_XorAssign: 12575 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12576 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12577 break; 12578 default: 12579 break; 12580 } 12581 12582 // Find all of the overloaded operators visible from this 12583 // point. We perform both an operator-name lookup from the local 12584 // scope and an argument-dependent lookup based on the types of 12585 // the arguments. 12586 UnresolvedSet<16> Functions; 12587 OverloadedOperatorKind OverOp 12588 = BinaryOperator::getOverloadedOperator(Opc); 12589 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12590 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12591 RHS->getType(), Functions); 12592 12593 // Build the (potentially-overloaded, potentially-dependent) 12594 // binary operation. 12595 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12596 } 12597 12598 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12599 BinaryOperatorKind Opc, 12600 Expr *LHSExpr, Expr *RHSExpr) { 12601 ExprResult LHS, RHS; 12602 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12603 if (!LHS.isUsable() || !RHS.isUsable()) 12604 return ExprError(); 12605 LHSExpr = LHS.get(); 12606 RHSExpr = RHS.get(); 12607 12608 // We want to end up calling one of checkPseudoObjectAssignment 12609 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12610 // both expressions are overloadable or either is type-dependent), 12611 // or CreateBuiltinBinOp (in any other case). We also want to get 12612 // any placeholder types out of the way. 12613 12614 // Handle pseudo-objects in the LHS. 12615 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12616 // Assignments with a pseudo-object l-value need special analysis. 12617 if (pty->getKind() == BuiltinType::PseudoObject && 12618 BinaryOperator::isAssignmentOp(Opc)) 12619 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12620 12621 // Don't resolve overloads if the other type is overloadable. 12622 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12623 // We can't actually test that if we still have a placeholder, 12624 // though. Fortunately, none of the exceptions we see in that 12625 // code below are valid when the LHS is an overload set. Note 12626 // that an overload set can be dependently-typed, but it never 12627 // instantiates to having an overloadable type. 12628 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12629 if (resolvedRHS.isInvalid()) return ExprError(); 12630 RHSExpr = resolvedRHS.get(); 12631 12632 if (RHSExpr->isTypeDependent() || 12633 RHSExpr->getType()->isOverloadableType()) 12634 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12635 } 12636 12637 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12638 // template, diagnose the missing 'template' keyword instead of diagnosing 12639 // an invalid use of a bound member function. 12640 // 12641 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12642 // to C++1z [over.over]/1.4, but we already checked for that case above. 12643 if (Opc == BO_LT && inTemplateInstantiation() && 12644 (pty->getKind() == BuiltinType::BoundMember || 12645 pty->getKind() == BuiltinType::Overload)) { 12646 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12647 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12648 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12649 return isa<FunctionTemplateDecl>(ND); 12650 })) { 12651 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12652 : OE->getNameLoc(), 12653 diag::err_template_kw_missing) 12654 << OE->getName().getAsString() << ""; 12655 return ExprError(); 12656 } 12657 } 12658 12659 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12660 if (LHS.isInvalid()) return ExprError(); 12661 LHSExpr = LHS.get(); 12662 } 12663 12664 // Handle pseudo-objects in the RHS. 12665 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12666 // An overload in the RHS can potentially be resolved by the type 12667 // being assigned to. 12668 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12669 if (getLangOpts().CPlusPlus && 12670 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12671 LHSExpr->getType()->isOverloadableType())) 12672 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12673 12674 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12675 } 12676 12677 // Don't resolve overloads if the other type is overloadable. 12678 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12679 LHSExpr->getType()->isOverloadableType()) 12680 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12681 12682 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12683 if (!resolvedRHS.isUsable()) return ExprError(); 12684 RHSExpr = resolvedRHS.get(); 12685 } 12686 12687 if (getLangOpts().CPlusPlus) { 12688 // If either expression is type-dependent, always build an 12689 // overloaded op. 12690 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12691 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12692 12693 // Otherwise, build an overloaded op if either expression has an 12694 // overloadable type. 12695 if (LHSExpr->getType()->isOverloadableType() || 12696 RHSExpr->getType()->isOverloadableType()) 12697 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12698 } 12699 12700 // Build a built-in binary operation. 12701 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12702 } 12703 12704 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12705 if (T.isNull() || T->isDependentType()) 12706 return false; 12707 12708 if (!T->isPromotableIntegerType()) 12709 return true; 12710 12711 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12712 } 12713 12714 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12715 UnaryOperatorKind Opc, 12716 Expr *InputExpr) { 12717 ExprResult Input = InputExpr; 12718 ExprValueKind VK = VK_RValue; 12719 ExprObjectKind OK = OK_Ordinary; 12720 QualType resultType; 12721 bool CanOverflow = false; 12722 12723 bool ConvertHalfVec = false; 12724 if (getLangOpts().OpenCL) { 12725 QualType Ty = InputExpr->getType(); 12726 // The only legal unary operation for atomics is '&'. 12727 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12728 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12729 // only with a builtin functions and therefore should be disallowed here. 12730 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12731 || Ty->isBlockPointerType())) { 12732 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12733 << InputExpr->getType() 12734 << Input.get()->getSourceRange()); 12735 } 12736 } 12737 switch (Opc) { 12738 case UO_PreInc: 12739 case UO_PreDec: 12740 case UO_PostInc: 12741 case UO_PostDec: 12742 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12743 OpLoc, 12744 Opc == UO_PreInc || 12745 Opc == UO_PostInc, 12746 Opc == UO_PreInc || 12747 Opc == UO_PreDec); 12748 CanOverflow = isOverflowingIntegerType(Context, resultType); 12749 break; 12750 case UO_AddrOf: 12751 resultType = CheckAddressOfOperand(Input, OpLoc); 12752 RecordModifiableNonNullParam(*this, InputExpr); 12753 break; 12754 case UO_Deref: { 12755 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12756 if (Input.isInvalid()) return ExprError(); 12757 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12758 break; 12759 } 12760 case UO_Plus: 12761 case UO_Minus: 12762 CanOverflow = Opc == UO_Minus && 12763 isOverflowingIntegerType(Context, Input.get()->getType()); 12764 Input = UsualUnaryConversions(Input.get()); 12765 if (Input.isInvalid()) return ExprError(); 12766 // Unary plus and minus require promoting an operand of half vector to a 12767 // float vector and truncating the result back to a half vector. For now, we 12768 // do this only when HalfArgsAndReturns is set (that is, when the target is 12769 // arm or arm64). 12770 ConvertHalfVec = 12771 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12772 12773 // If the operand is a half vector, promote it to a float vector. 12774 if (ConvertHalfVec) 12775 Input = convertVector(Input.get(), Context.FloatTy, *this); 12776 resultType = Input.get()->getType(); 12777 if (resultType->isDependentType()) 12778 break; 12779 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12780 break; 12781 else if (resultType->isVectorType() && 12782 // The z vector extensions don't allow + or - with bool vectors. 12783 (!Context.getLangOpts().ZVector || 12784 resultType->getAs<VectorType>()->getVectorKind() != 12785 VectorType::AltiVecBool)) 12786 break; 12787 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12788 Opc == UO_Plus && 12789 resultType->isPointerType()) 12790 break; 12791 12792 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12793 << resultType << Input.get()->getSourceRange()); 12794 12795 case UO_Not: // bitwise complement 12796 Input = UsualUnaryConversions(Input.get()); 12797 if (Input.isInvalid()) 12798 return ExprError(); 12799 resultType = Input.get()->getType(); 12800 12801 if (resultType->isDependentType()) 12802 break; 12803 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12804 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12805 // C99 does not support '~' for complex conjugation. 12806 Diag(OpLoc, diag::ext_integer_complement_complex) 12807 << resultType << Input.get()->getSourceRange(); 12808 else if (resultType->hasIntegerRepresentation()) 12809 break; 12810 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12811 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12812 // on vector float types. 12813 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12814 if (!T->isIntegerType()) 12815 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12816 << resultType << Input.get()->getSourceRange()); 12817 } else { 12818 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12819 << resultType << Input.get()->getSourceRange()); 12820 } 12821 break; 12822 12823 case UO_LNot: // logical negation 12824 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12825 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12826 if (Input.isInvalid()) return ExprError(); 12827 resultType = Input.get()->getType(); 12828 12829 // Though we still have to promote half FP to float... 12830 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12831 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12832 resultType = Context.FloatTy; 12833 } 12834 12835 if (resultType->isDependentType()) 12836 break; 12837 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12838 // C99 6.5.3.3p1: ok, fallthrough; 12839 if (Context.getLangOpts().CPlusPlus) { 12840 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12841 // operand contextually converted to bool. 12842 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12843 ScalarTypeToBooleanCastKind(resultType)); 12844 } else if (Context.getLangOpts().OpenCL && 12845 Context.getLangOpts().OpenCLVersion < 120) { 12846 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12847 // operate on scalar float types. 12848 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12849 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12850 << resultType << Input.get()->getSourceRange()); 12851 } 12852 } else if (resultType->isExtVectorType()) { 12853 if (Context.getLangOpts().OpenCL && 12854 Context.getLangOpts().OpenCLVersion < 120) { 12855 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12856 // operate on vector float types. 12857 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12858 if (!T->isIntegerType()) 12859 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12860 << resultType << Input.get()->getSourceRange()); 12861 } 12862 // Vector logical not returns the signed variant of the operand type. 12863 resultType = GetSignedVectorType(resultType); 12864 break; 12865 } else { 12866 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12867 // type in C++. We should allow that here too. 12868 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12869 << resultType << Input.get()->getSourceRange()); 12870 } 12871 12872 // LNot always has type int. C99 6.5.3.3p5. 12873 // In C++, it's bool. C++ 5.3.1p8 12874 resultType = Context.getLogicalOperationType(); 12875 break; 12876 case UO_Real: 12877 case UO_Imag: 12878 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12879 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12880 // complex l-values to ordinary l-values and all other values to r-values. 12881 if (Input.isInvalid()) return ExprError(); 12882 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12883 if (Input.get()->getValueKind() != VK_RValue && 12884 Input.get()->getObjectKind() == OK_Ordinary) 12885 VK = Input.get()->getValueKind(); 12886 } else if (!getLangOpts().CPlusPlus) { 12887 // In C, a volatile scalar is read by __imag. In C++, it is not. 12888 Input = DefaultLvalueConversion(Input.get()); 12889 } 12890 break; 12891 case UO_Extension: 12892 resultType = Input.get()->getType(); 12893 VK = Input.get()->getValueKind(); 12894 OK = Input.get()->getObjectKind(); 12895 break; 12896 case UO_Coawait: 12897 // It's unnecessary to represent the pass-through operator co_await in the 12898 // AST; just return the input expression instead. 12899 assert(!Input.get()->getType()->isDependentType() && 12900 "the co_await expression must be non-dependant before " 12901 "building operator co_await"); 12902 return Input; 12903 } 12904 if (resultType.isNull() || Input.isInvalid()) 12905 return ExprError(); 12906 12907 // Check for array bounds violations in the operand of the UnaryOperator, 12908 // except for the '*' and '&' operators that have to be handled specially 12909 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12910 // that are explicitly defined as valid by the standard). 12911 if (Opc != UO_AddrOf && Opc != UO_Deref) 12912 CheckArrayAccess(Input.get()); 12913 12914 auto *UO = new (Context) 12915 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12916 // Convert the result back to a half vector. 12917 if (ConvertHalfVec) 12918 return convertVector(UO, Context.HalfTy, *this); 12919 return UO; 12920 } 12921 12922 /// Determine whether the given expression is a qualified member 12923 /// access expression, of a form that could be turned into a pointer to member 12924 /// with the address-of operator. 12925 bool Sema::isQualifiedMemberAccess(Expr *E) { 12926 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12927 if (!DRE->getQualifier()) 12928 return false; 12929 12930 ValueDecl *VD = DRE->getDecl(); 12931 if (!VD->isCXXClassMember()) 12932 return false; 12933 12934 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12935 return true; 12936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12937 return Method->isInstance(); 12938 12939 return false; 12940 } 12941 12942 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12943 if (!ULE->getQualifier()) 12944 return false; 12945 12946 for (NamedDecl *D : ULE->decls()) { 12947 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12948 if (Method->isInstance()) 12949 return true; 12950 } else { 12951 // Overload set does not contain methods. 12952 break; 12953 } 12954 } 12955 12956 return false; 12957 } 12958 12959 return false; 12960 } 12961 12962 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12963 UnaryOperatorKind Opc, Expr *Input) { 12964 // First things first: handle placeholders so that the 12965 // overloaded-operator check considers the right type. 12966 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12967 // Increment and decrement of pseudo-object references. 12968 if (pty->getKind() == BuiltinType::PseudoObject && 12969 UnaryOperator::isIncrementDecrementOp(Opc)) 12970 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12971 12972 // extension is always a builtin operator. 12973 if (Opc == UO_Extension) 12974 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12975 12976 // & gets special logic for several kinds of placeholder. 12977 // The builtin code knows what to do. 12978 if (Opc == UO_AddrOf && 12979 (pty->getKind() == BuiltinType::Overload || 12980 pty->getKind() == BuiltinType::UnknownAny || 12981 pty->getKind() == BuiltinType::BoundMember)) 12982 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12983 12984 // Anything else needs to be handled now. 12985 ExprResult Result = CheckPlaceholderExpr(Input); 12986 if (Result.isInvalid()) return ExprError(); 12987 Input = Result.get(); 12988 } 12989 12990 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12991 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12992 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12993 // Find all of the overloaded operators visible from this 12994 // point. We perform both an operator-name lookup from the local 12995 // scope and an argument-dependent lookup based on the types of 12996 // the arguments. 12997 UnresolvedSet<16> Functions; 12998 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12999 if (S && OverOp != OO_None) 13000 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13001 Functions); 13002 13003 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13004 } 13005 13006 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13007 } 13008 13009 // Unary Operators. 'Tok' is the token for the operator. 13010 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13011 tok::TokenKind Op, Expr *Input) { 13012 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13013 } 13014 13015 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13016 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13017 LabelDecl *TheDecl) { 13018 TheDecl->markUsed(Context); 13019 // Create the AST node. The address of a label always has type 'void*'. 13020 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13021 Context.getPointerType(Context.VoidTy)); 13022 } 13023 13024 /// Given the last statement in a statement-expression, check whether 13025 /// the result is a producing expression (like a call to an 13026 /// ns_returns_retained function) and, if so, rebuild it to hoist the 13027 /// release out of the full-expression. Otherwise, return null. 13028 /// Cannot fail. 13029 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 13030 // Should always be wrapped with one of these. 13031 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 13032 if (!cleanups) return nullptr; 13033 13034 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 13035 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 13036 return nullptr; 13037 13038 // Splice out the cast. This shouldn't modify any interesting 13039 // features of the statement. 13040 Expr *producer = cast->getSubExpr(); 13041 assert(producer->getType() == cast->getType()); 13042 assert(producer->getValueKind() == cast->getValueKind()); 13043 cleanups->setSubExpr(producer); 13044 return cleanups; 13045 } 13046 13047 void Sema::ActOnStartStmtExpr() { 13048 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13049 } 13050 13051 void Sema::ActOnStmtExprError() { 13052 // Note that function is also called by TreeTransform when leaving a 13053 // StmtExpr scope without rebuilding anything. 13054 13055 DiscardCleanupsInEvaluationContext(); 13056 PopExpressionEvaluationContext(); 13057 } 13058 13059 ExprResult 13060 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13061 SourceLocation RPLoc) { // "({..})" 13062 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13063 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13064 13065 if (hasAnyUnrecoverableErrorsInThisFunction()) 13066 DiscardCleanupsInEvaluationContext(); 13067 assert(!Cleanup.exprNeedsCleanups() && 13068 "cleanups within StmtExpr not correctly bound!"); 13069 PopExpressionEvaluationContext(); 13070 13071 // FIXME: there are a variety of strange constraints to enforce here, for 13072 // example, it is not possible to goto into a stmt expression apparently. 13073 // More semantic analysis is needed. 13074 13075 // If there are sub-stmts in the compound stmt, take the type of the last one 13076 // as the type of the stmtexpr. 13077 QualType Ty = Context.VoidTy; 13078 bool StmtExprMayBindToTemp = false; 13079 if (!Compound->body_empty()) { 13080 Stmt *LastStmt = Compound->body_back(); 13081 LabelStmt *LastLabelStmt = nullptr; 13082 // If LastStmt is a label, skip down through into the body. 13083 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 13084 LastLabelStmt = Label; 13085 LastStmt = Label->getSubStmt(); 13086 } 13087 13088 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 13089 // Do function/array conversion on the last expression, but not 13090 // lvalue-to-rvalue. However, initialize an unqualified type. 13091 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 13092 if (LastExpr.isInvalid()) 13093 return ExprError(); 13094 Ty = LastExpr.get()->getType().getUnqualifiedType(); 13095 13096 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 13097 // In ARC, if the final expression ends in a consume, splice 13098 // the consume out and bind it later. In the alternate case 13099 // (when dealing with a retainable type), the result 13100 // initialization will create a produce. In both cases the 13101 // result will be +1, and we'll need to balance that out with 13102 // a bind. 13103 if (Expr *rebuiltLastStmt 13104 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 13105 LastExpr = rebuiltLastStmt; 13106 } else { 13107 LastExpr = PerformCopyInitialization( 13108 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 13109 SourceLocation(), LastExpr); 13110 } 13111 13112 if (LastExpr.isInvalid()) 13113 return ExprError(); 13114 if (LastExpr.get() != nullptr) { 13115 if (!LastLabelStmt) 13116 Compound->setLastStmt(LastExpr.get()); 13117 else 13118 LastLabelStmt->setSubStmt(LastExpr.get()); 13119 StmtExprMayBindToTemp = true; 13120 } 13121 } 13122 } 13123 } 13124 13125 // FIXME: Check that expression type is complete/non-abstract; statement 13126 // expressions are not lvalues. 13127 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13128 if (StmtExprMayBindToTemp) 13129 return MaybeBindToTemporary(ResStmtExpr); 13130 return ResStmtExpr; 13131 } 13132 13133 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13134 TypeSourceInfo *TInfo, 13135 ArrayRef<OffsetOfComponent> Components, 13136 SourceLocation RParenLoc) { 13137 QualType ArgTy = TInfo->getType(); 13138 bool Dependent = ArgTy->isDependentType(); 13139 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13140 13141 // We must have at least one component that refers to the type, and the first 13142 // one is known to be a field designator. Verify that the ArgTy represents 13143 // a struct/union/class. 13144 if (!Dependent && !ArgTy->isRecordType()) 13145 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13146 << ArgTy << TypeRange); 13147 13148 // Type must be complete per C99 7.17p3 because a declaring a variable 13149 // with an incomplete type would be ill-formed. 13150 if (!Dependent 13151 && RequireCompleteType(BuiltinLoc, ArgTy, 13152 diag::err_offsetof_incomplete_type, TypeRange)) 13153 return ExprError(); 13154 13155 bool DidWarnAboutNonPOD = false; 13156 QualType CurrentType = ArgTy; 13157 SmallVector<OffsetOfNode, 4> Comps; 13158 SmallVector<Expr*, 4> Exprs; 13159 for (const OffsetOfComponent &OC : Components) { 13160 if (OC.isBrackets) { 13161 // Offset of an array sub-field. TODO: Should we allow vector elements? 13162 if (!CurrentType->isDependentType()) { 13163 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13164 if(!AT) 13165 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13166 << CurrentType); 13167 CurrentType = AT->getElementType(); 13168 } else 13169 CurrentType = Context.DependentTy; 13170 13171 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13172 if (IdxRval.isInvalid()) 13173 return ExprError(); 13174 Expr *Idx = IdxRval.get(); 13175 13176 // The expression must be an integral expression. 13177 // FIXME: An integral constant expression? 13178 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13179 !Idx->getType()->isIntegerType()) 13180 return ExprError( 13181 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13182 << Idx->getSourceRange()); 13183 13184 // Record this array index. 13185 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13186 Exprs.push_back(Idx); 13187 continue; 13188 } 13189 13190 // Offset of a field. 13191 if (CurrentType->isDependentType()) { 13192 // We have the offset of a field, but we can't look into the dependent 13193 // type. Just record the identifier of the field. 13194 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13195 CurrentType = Context.DependentTy; 13196 continue; 13197 } 13198 13199 // We need to have a complete type to look into. 13200 if (RequireCompleteType(OC.LocStart, CurrentType, 13201 diag::err_offsetof_incomplete_type)) 13202 return ExprError(); 13203 13204 // Look for the designated field. 13205 const RecordType *RC = CurrentType->getAs<RecordType>(); 13206 if (!RC) 13207 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13208 << CurrentType); 13209 RecordDecl *RD = RC->getDecl(); 13210 13211 // C++ [lib.support.types]p5: 13212 // The macro offsetof accepts a restricted set of type arguments in this 13213 // International Standard. type shall be a POD structure or a POD union 13214 // (clause 9). 13215 // C++11 [support.types]p4: 13216 // If type is not a standard-layout class (Clause 9), the results are 13217 // undefined. 13218 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13219 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13220 unsigned DiagID = 13221 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13222 : diag::ext_offsetof_non_pod_type; 13223 13224 if (!IsSafe && !DidWarnAboutNonPOD && 13225 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13226 PDiag(DiagID) 13227 << SourceRange(Components[0].LocStart, OC.LocEnd) 13228 << CurrentType)) 13229 DidWarnAboutNonPOD = true; 13230 } 13231 13232 // Look for the field. 13233 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13234 LookupQualifiedName(R, RD); 13235 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13236 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13237 if (!MemberDecl) { 13238 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13239 MemberDecl = IndirectMemberDecl->getAnonField(); 13240 } 13241 13242 if (!MemberDecl) 13243 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13244 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13245 OC.LocEnd)); 13246 13247 // C99 7.17p3: 13248 // (If the specified member is a bit-field, the behavior is undefined.) 13249 // 13250 // We diagnose this as an error. 13251 if (MemberDecl->isBitField()) { 13252 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13253 << MemberDecl->getDeclName() 13254 << SourceRange(BuiltinLoc, RParenLoc); 13255 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13256 return ExprError(); 13257 } 13258 13259 RecordDecl *Parent = MemberDecl->getParent(); 13260 if (IndirectMemberDecl) 13261 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13262 13263 // If the member was found in a base class, introduce OffsetOfNodes for 13264 // the base class indirections. 13265 CXXBasePaths Paths; 13266 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13267 Paths)) { 13268 if (Paths.getDetectedVirtual()) { 13269 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13270 << MemberDecl->getDeclName() 13271 << SourceRange(BuiltinLoc, RParenLoc); 13272 return ExprError(); 13273 } 13274 13275 CXXBasePath &Path = Paths.front(); 13276 for (const CXXBasePathElement &B : Path) 13277 Comps.push_back(OffsetOfNode(B.Base)); 13278 } 13279 13280 if (IndirectMemberDecl) { 13281 for (auto *FI : IndirectMemberDecl->chain()) { 13282 assert(isa<FieldDecl>(FI)); 13283 Comps.push_back(OffsetOfNode(OC.LocStart, 13284 cast<FieldDecl>(FI), OC.LocEnd)); 13285 } 13286 } else 13287 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13288 13289 CurrentType = MemberDecl->getType().getNonReferenceType(); 13290 } 13291 13292 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13293 Comps, Exprs, RParenLoc); 13294 } 13295 13296 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13297 SourceLocation BuiltinLoc, 13298 SourceLocation TypeLoc, 13299 ParsedType ParsedArgTy, 13300 ArrayRef<OffsetOfComponent> Components, 13301 SourceLocation RParenLoc) { 13302 13303 TypeSourceInfo *ArgTInfo; 13304 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13305 if (ArgTy.isNull()) 13306 return ExprError(); 13307 13308 if (!ArgTInfo) 13309 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13310 13311 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13312 } 13313 13314 13315 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13316 Expr *CondExpr, 13317 Expr *LHSExpr, Expr *RHSExpr, 13318 SourceLocation RPLoc) { 13319 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13320 13321 ExprValueKind VK = VK_RValue; 13322 ExprObjectKind OK = OK_Ordinary; 13323 QualType resType; 13324 bool ValueDependent = false; 13325 bool CondIsTrue = false; 13326 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13327 resType = Context.DependentTy; 13328 ValueDependent = true; 13329 } else { 13330 // The conditional expression is required to be a constant expression. 13331 llvm::APSInt condEval(32); 13332 ExprResult CondICE 13333 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13334 diag::err_typecheck_choose_expr_requires_constant, false); 13335 if (CondICE.isInvalid()) 13336 return ExprError(); 13337 CondExpr = CondICE.get(); 13338 CondIsTrue = condEval.getZExtValue(); 13339 13340 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13341 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13342 13343 resType = ActiveExpr->getType(); 13344 ValueDependent = ActiveExpr->isValueDependent(); 13345 VK = ActiveExpr->getValueKind(); 13346 OK = ActiveExpr->getObjectKind(); 13347 } 13348 13349 return new (Context) 13350 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13351 CondIsTrue, resType->isDependentType(), ValueDependent); 13352 } 13353 13354 //===----------------------------------------------------------------------===// 13355 // Clang Extensions. 13356 //===----------------------------------------------------------------------===// 13357 13358 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13359 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13360 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13361 13362 if (LangOpts.CPlusPlus) { 13363 Decl *ManglingContextDecl; 13364 if (MangleNumberingContext *MCtx = 13365 getCurrentMangleNumberContext(Block->getDeclContext(), 13366 ManglingContextDecl)) { 13367 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13368 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13369 } 13370 } 13371 13372 PushBlockScope(CurScope, Block); 13373 CurContext->addDecl(Block); 13374 if (CurScope) 13375 PushDeclContext(CurScope, Block); 13376 else 13377 CurContext = Block; 13378 13379 getCurBlock()->HasImplicitReturnType = true; 13380 13381 // Enter a new evaluation context to insulate the block from any 13382 // cleanups from the enclosing full-expression. 13383 PushExpressionEvaluationContext( 13384 ExpressionEvaluationContext::PotentiallyEvaluated); 13385 } 13386 13387 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13388 Scope *CurScope) { 13389 assert(ParamInfo.getIdentifier() == nullptr && 13390 "block-id should have no identifier!"); 13391 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13392 BlockScopeInfo *CurBlock = getCurBlock(); 13393 13394 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13395 QualType T = Sig->getType(); 13396 13397 // FIXME: We should allow unexpanded parameter packs here, but that would, 13398 // in turn, make the block expression contain unexpanded parameter packs. 13399 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13400 // Drop the parameters. 13401 FunctionProtoType::ExtProtoInfo EPI; 13402 EPI.HasTrailingReturn = false; 13403 EPI.TypeQuals |= DeclSpec::TQ_const; 13404 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13405 Sig = Context.getTrivialTypeSourceInfo(T); 13406 } 13407 13408 // GetTypeForDeclarator always produces a function type for a block 13409 // literal signature. Furthermore, it is always a FunctionProtoType 13410 // unless the function was written with a typedef. 13411 assert(T->isFunctionType() && 13412 "GetTypeForDeclarator made a non-function block signature"); 13413 13414 // Look for an explicit signature in that function type. 13415 FunctionProtoTypeLoc ExplicitSignature; 13416 13417 if ((ExplicitSignature = 13418 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13419 13420 // Check whether that explicit signature was synthesized by 13421 // GetTypeForDeclarator. If so, don't save that as part of the 13422 // written signature. 13423 if (ExplicitSignature.getLocalRangeBegin() == 13424 ExplicitSignature.getLocalRangeEnd()) { 13425 // This would be much cheaper if we stored TypeLocs instead of 13426 // TypeSourceInfos. 13427 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13428 unsigned Size = Result.getFullDataSize(); 13429 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13430 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13431 13432 ExplicitSignature = FunctionProtoTypeLoc(); 13433 } 13434 } 13435 13436 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13437 CurBlock->FunctionType = T; 13438 13439 const FunctionType *Fn = T->getAs<FunctionType>(); 13440 QualType RetTy = Fn->getReturnType(); 13441 bool isVariadic = 13442 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13443 13444 CurBlock->TheDecl->setIsVariadic(isVariadic); 13445 13446 // Context.DependentTy is used as a placeholder for a missing block 13447 // return type. TODO: what should we do with declarators like: 13448 // ^ * { ... } 13449 // If the answer is "apply template argument deduction".... 13450 if (RetTy != Context.DependentTy) { 13451 CurBlock->ReturnType = RetTy; 13452 CurBlock->TheDecl->setBlockMissingReturnType(false); 13453 CurBlock->HasImplicitReturnType = false; 13454 } 13455 13456 // Push block parameters from the declarator if we had them. 13457 SmallVector<ParmVarDecl*, 8> Params; 13458 if (ExplicitSignature) { 13459 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13460 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13461 if (Param->getIdentifier() == nullptr && 13462 !Param->isImplicit() && 13463 !Param->isInvalidDecl() && 13464 !getLangOpts().CPlusPlus) 13465 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13466 Params.push_back(Param); 13467 } 13468 13469 // Fake up parameter variables if we have a typedef, like 13470 // ^ fntype { ... } 13471 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13472 for (const auto &I : Fn->param_types()) { 13473 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13474 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13475 Params.push_back(Param); 13476 } 13477 } 13478 13479 // Set the parameters on the block decl. 13480 if (!Params.empty()) { 13481 CurBlock->TheDecl->setParams(Params); 13482 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13483 /*CheckParameterNames=*/false); 13484 } 13485 13486 // Finally we can process decl attributes. 13487 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13488 13489 // Put the parameter variables in scope. 13490 for (auto AI : CurBlock->TheDecl->parameters()) { 13491 AI->setOwningFunction(CurBlock->TheDecl); 13492 13493 // If this has an identifier, add it to the scope stack. 13494 if (AI->getIdentifier()) { 13495 CheckShadow(CurBlock->TheScope, AI); 13496 13497 PushOnScopeChains(AI, CurBlock->TheScope); 13498 } 13499 } 13500 } 13501 13502 /// ActOnBlockError - If there is an error parsing a block, this callback 13503 /// is invoked to pop the information about the block from the action impl. 13504 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13505 // Leave the expression-evaluation context. 13506 DiscardCleanupsInEvaluationContext(); 13507 PopExpressionEvaluationContext(); 13508 13509 // Pop off CurBlock, handle nested blocks. 13510 PopDeclContext(); 13511 PopFunctionScopeInfo(); 13512 } 13513 13514 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13515 /// literal was successfully completed. ^(int x){...} 13516 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13517 Stmt *Body, Scope *CurScope) { 13518 // If blocks are disabled, emit an error. 13519 if (!LangOpts.Blocks) 13520 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13521 13522 // Leave the expression-evaluation context. 13523 if (hasAnyUnrecoverableErrorsInThisFunction()) 13524 DiscardCleanupsInEvaluationContext(); 13525 assert(!Cleanup.exprNeedsCleanups() && 13526 "cleanups within block not correctly bound!"); 13527 PopExpressionEvaluationContext(); 13528 13529 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13530 BlockDecl *BD = BSI->TheDecl; 13531 13532 if (BSI->HasImplicitReturnType) 13533 deduceClosureReturnType(*BSI); 13534 13535 PopDeclContext(); 13536 13537 QualType RetTy = Context.VoidTy; 13538 if (!BSI->ReturnType.isNull()) 13539 RetTy = BSI->ReturnType; 13540 13541 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13542 QualType BlockTy; 13543 13544 // Set the captured variables on the block. 13545 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13546 SmallVector<BlockDecl::Capture, 4> Captures; 13547 for (Capture &Cap : BSI->Captures) { 13548 if (Cap.isThisCapture()) 13549 continue; 13550 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13551 Cap.isNested(), Cap.getInitExpr()); 13552 Captures.push_back(NewCap); 13553 } 13554 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13555 13556 // If the user wrote a function type in some form, try to use that. 13557 if (!BSI->FunctionType.isNull()) { 13558 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13559 13560 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13561 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13562 13563 // Turn protoless block types into nullary block types. 13564 if (isa<FunctionNoProtoType>(FTy)) { 13565 FunctionProtoType::ExtProtoInfo EPI; 13566 EPI.ExtInfo = Ext; 13567 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13568 13569 // Otherwise, if we don't need to change anything about the function type, 13570 // preserve its sugar structure. 13571 } else if (FTy->getReturnType() == RetTy && 13572 (!NoReturn || FTy->getNoReturnAttr())) { 13573 BlockTy = BSI->FunctionType; 13574 13575 // Otherwise, make the minimal modifications to the function type. 13576 } else { 13577 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13578 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13579 EPI.TypeQuals = 0; // FIXME: silently? 13580 EPI.ExtInfo = Ext; 13581 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13582 } 13583 13584 // If we don't have a function type, just build one from nothing. 13585 } else { 13586 FunctionProtoType::ExtProtoInfo EPI; 13587 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13588 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13589 } 13590 13591 DiagnoseUnusedParameters(BD->parameters()); 13592 BlockTy = Context.getBlockPointerType(BlockTy); 13593 13594 // If needed, diagnose invalid gotos and switches in the block. 13595 if (getCurFunction()->NeedsScopeChecking() && 13596 !PP.isCodeCompletionEnabled()) 13597 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13598 13599 BD->setBody(cast<CompoundStmt>(Body)); 13600 13601 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13602 DiagnoseUnguardedAvailabilityViolations(BD); 13603 13604 // Try to apply the named return value optimization. We have to check again 13605 // if we can do this, though, because blocks keep return statements around 13606 // to deduce an implicit return type. 13607 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13608 !BD->isDependentContext()) 13609 computeNRVO(Body, BSI); 13610 13611 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13612 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13613 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13614 13615 // If the block isn't obviously global, i.e. it captures anything at 13616 // all, then we need to do a few things in the surrounding context: 13617 if (Result->getBlockDecl()->hasCaptures()) { 13618 // First, this expression has a new cleanup object. 13619 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13620 Cleanup.setExprNeedsCleanups(true); 13621 13622 // It also gets a branch-protected scope if any of the captured 13623 // variables needs destruction. 13624 for (const auto &CI : Result->getBlockDecl()->captures()) { 13625 const VarDecl *var = CI.getVariable(); 13626 if (var->getType().isDestructedType() != QualType::DK_none) { 13627 setFunctionHasBranchProtectedScope(); 13628 break; 13629 } 13630 } 13631 } 13632 13633 if (getCurFunction()) 13634 getCurFunction()->addBlock(BD); 13635 13636 return Result; 13637 } 13638 13639 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13640 SourceLocation RPLoc) { 13641 TypeSourceInfo *TInfo; 13642 GetTypeFromParser(Ty, &TInfo); 13643 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13644 } 13645 13646 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13647 Expr *E, TypeSourceInfo *TInfo, 13648 SourceLocation RPLoc) { 13649 Expr *OrigExpr = E; 13650 bool IsMS = false; 13651 13652 // CUDA device code does not support varargs. 13653 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13654 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13655 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13656 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13657 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13658 } 13659 } 13660 13661 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13662 // as Microsoft ABI on an actual Microsoft platform, where 13663 // __builtin_ms_va_list and __builtin_va_list are the same.) 13664 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13665 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13666 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13667 if (Context.hasSameType(MSVaListType, E->getType())) { 13668 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13669 return ExprError(); 13670 IsMS = true; 13671 } 13672 } 13673 13674 // Get the va_list type 13675 QualType VaListType = Context.getBuiltinVaListType(); 13676 if (!IsMS) { 13677 if (VaListType->isArrayType()) { 13678 // Deal with implicit array decay; for example, on x86-64, 13679 // va_list is an array, but it's supposed to decay to 13680 // a pointer for va_arg. 13681 VaListType = Context.getArrayDecayedType(VaListType); 13682 // Make sure the input expression also decays appropriately. 13683 ExprResult Result = UsualUnaryConversions(E); 13684 if (Result.isInvalid()) 13685 return ExprError(); 13686 E = Result.get(); 13687 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13688 // If va_list is a record type and we are compiling in C++ mode, 13689 // check the argument using reference binding. 13690 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13691 Context, Context.getLValueReferenceType(VaListType), false); 13692 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13693 if (Init.isInvalid()) 13694 return ExprError(); 13695 E = Init.getAs<Expr>(); 13696 } else { 13697 // Otherwise, the va_list argument must be an l-value because 13698 // it is modified by va_arg. 13699 if (!E->isTypeDependent() && 13700 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13701 return ExprError(); 13702 } 13703 } 13704 13705 if (!IsMS && !E->isTypeDependent() && 13706 !Context.hasSameType(VaListType, E->getType())) 13707 return ExprError( 13708 Diag(E->getBeginLoc(), 13709 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13710 << OrigExpr->getType() << E->getSourceRange()); 13711 13712 if (!TInfo->getType()->isDependentType()) { 13713 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13714 diag::err_second_parameter_to_va_arg_incomplete, 13715 TInfo->getTypeLoc())) 13716 return ExprError(); 13717 13718 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13719 TInfo->getType(), 13720 diag::err_second_parameter_to_va_arg_abstract, 13721 TInfo->getTypeLoc())) 13722 return ExprError(); 13723 13724 if (!TInfo->getType().isPODType(Context)) { 13725 Diag(TInfo->getTypeLoc().getBeginLoc(), 13726 TInfo->getType()->isObjCLifetimeType() 13727 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13728 : diag::warn_second_parameter_to_va_arg_not_pod) 13729 << TInfo->getType() 13730 << TInfo->getTypeLoc().getSourceRange(); 13731 } 13732 13733 // Check for va_arg where arguments of the given type will be promoted 13734 // (i.e. this va_arg is guaranteed to have undefined behavior). 13735 QualType PromoteType; 13736 if (TInfo->getType()->isPromotableIntegerType()) { 13737 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13738 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13739 PromoteType = QualType(); 13740 } 13741 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13742 PromoteType = Context.DoubleTy; 13743 if (!PromoteType.isNull()) 13744 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13745 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13746 << TInfo->getType() 13747 << PromoteType 13748 << TInfo->getTypeLoc().getSourceRange()); 13749 } 13750 13751 QualType T = TInfo->getType().getNonLValueExprType(Context); 13752 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13753 } 13754 13755 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13756 // The type of __null will be int or long, depending on the size of 13757 // pointers on the target. 13758 QualType Ty; 13759 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13760 if (pw == Context.getTargetInfo().getIntWidth()) 13761 Ty = Context.IntTy; 13762 else if (pw == Context.getTargetInfo().getLongWidth()) 13763 Ty = Context.LongTy; 13764 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13765 Ty = Context.LongLongTy; 13766 else { 13767 llvm_unreachable("I don't know size of pointer!"); 13768 } 13769 13770 return new (Context) GNUNullExpr(Ty, TokenLoc); 13771 } 13772 13773 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13774 bool Diagnose) { 13775 if (!getLangOpts().ObjC) 13776 return false; 13777 13778 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13779 if (!PT) 13780 return false; 13781 13782 if (!PT->isObjCIdType()) { 13783 // Check if the destination is the 'NSString' interface. 13784 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13785 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13786 return false; 13787 } 13788 13789 // Ignore any parens, implicit casts (should only be 13790 // array-to-pointer decays), and not-so-opaque values. The last is 13791 // important for making this trigger for property assignments. 13792 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13793 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13794 if (OV->getSourceExpr()) 13795 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13796 13797 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13798 if (!SL || !SL->isAscii()) 13799 return false; 13800 if (Diagnose) { 13801 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13802 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13803 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13804 } 13805 return true; 13806 } 13807 13808 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13809 const Expr *SrcExpr) { 13810 if (!DstType->isFunctionPointerType() || 13811 !SrcExpr->getType()->isFunctionType()) 13812 return false; 13813 13814 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13815 if (!DRE) 13816 return false; 13817 13818 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13819 if (!FD) 13820 return false; 13821 13822 return !S.checkAddressOfFunctionIsAvailable(FD, 13823 /*Complain=*/true, 13824 SrcExpr->getBeginLoc()); 13825 } 13826 13827 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13828 SourceLocation Loc, 13829 QualType DstType, QualType SrcType, 13830 Expr *SrcExpr, AssignmentAction Action, 13831 bool *Complained) { 13832 if (Complained) 13833 *Complained = false; 13834 13835 // Decode the result (notice that AST's are still created for extensions). 13836 bool CheckInferredResultType = false; 13837 bool isInvalid = false; 13838 unsigned DiagKind = 0; 13839 FixItHint Hint; 13840 ConversionFixItGenerator ConvHints; 13841 bool MayHaveConvFixit = false; 13842 bool MayHaveFunctionDiff = false; 13843 const ObjCInterfaceDecl *IFace = nullptr; 13844 const ObjCProtocolDecl *PDecl = nullptr; 13845 13846 switch (ConvTy) { 13847 case Compatible: 13848 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13849 return false; 13850 13851 case PointerToInt: 13852 DiagKind = diag::ext_typecheck_convert_pointer_int; 13853 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13854 MayHaveConvFixit = true; 13855 break; 13856 case IntToPointer: 13857 DiagKind = diag::ext_typecheck_convert_int_pointer; 13858 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13859 MayHaveConvFixit = true; 13860 break; 13861 case IncompatiblePointer: 13862 if (Action == AA_Passing_CFAudited) 13863 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13864 else if (SrcType->isFunctionPointerType() && 13865 DstType->isFunctionPointerType()) 13866 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13867 else 13868 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13869 13870 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13871 SrcType->isObjCObjectPointerType(); 13872 if (Hint.isNull() && !CheckInferredResultType) { 13873 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13874 } 13875 else if (CheckInferredResultType) { 13876 SrcType = SrcType.getUnqualifiedType(); 13877 DstType = DstType.getUnqualifiedType(); 13878 } 13879 MayHaveConvFixit = true; 13880 break; 13881 case IncompatiblePointerSign: 13882 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13883 break; 13884 case FunctionVoidPointer: 13885 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13886 break; 13887 case IncompatiblePointerDiscardsQualifiers: { 13888 // Perform array-to-pointer decay if necessary. 13889 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13890 13891 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13892 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13893 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13894 DiagKind = diag::err_typecheck_incompatible_address_space; 13895 break; 13896 13897 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13898 DiagKind = diag::err_typecheck_incompatible_ownership; 13899 break; 13900 } 13901 13902 llvm_unreachable("unknown error case for discarding qualifiers!"); 13903 // fallthrough 13904 } 13905 case CompatiblePointerDiscardsQualifiers: 13906 // If the qualifiers lost were because we were applying the 13907 // (deprecated) C++ conversion from a string literal to a char* 13908 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13909 // Ideally, this check would be performed in 13910 // checkPointerTypesForAssignment. However, that would require a 13911 // bit of refactoring (so that the second argument is an 13912 // expression, rather than a type), which should be done as part 13913 // of a larger effort to fix checkPointerTypesForAssignment for 13914 // C++ semantics. 13915 if (getLangOpts().CPlusPlus && 13916 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13917 return false; 13918 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13919 break; 13920 case IncompatibleNestedPointerQualifiers: 13921 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13922 break; 13923 case IntToBlockPointer: 13924 DiagKind = diag::err_int_to_block_pointer; 13925 break; 13926 case IncompatibleBlockPointer: 13927 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13928 break; 13929 case IncompatibleObjCQualifiedId: { 13930 if (SrcType->isObjCQualifiedIdType()) { 13931 const ObjCObjectPointerType *srcOPT = 13932 SrcType->getAs<ObjCObjectPointerType>(); 13933 for (auto *srcProto : srcOPT->quals()) { 13934 PDecl = srcProto; 13935 break; 13936 } 13937 if (const ObjCInterfaceType *IFaceT = 13938 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13939 IFace = IFaceT->getDecl(); 13940 } 13941 else if (DstType->isObjCQualifiedIdType()) { 13942 const ObjCObjectPointerType *dstOPT = 13943 DstType->getAs<ObjCObjectPointerType>(); 13944 for (auto *dstProto : dstOPT->quals()) { 13945 PDecl = dstProto; 13946 break; 13947 } 13948 if (const ObjCInterfaceType *IFaceT = 13949 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13950 IFace = IFaceT->getDecl(); 13951 } 13952 DiagKind = diag::warn_incompatible_qualified_id; 13953 break; 13954 } 13955 case IncompatibleVectors: 13956 DiagKind = diag::warn_incompatible_vectors; 13957 break; 13958 case IncompatibleObjCWeakRef: 13959 DiagKind = diag::err_arc_weak_unavailable_assign; 13960 break; 13961 case Incompatible: 13962 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13963 if (Complained) 13964 *Complained = true; 13965 return true; 13966 } 13967 13968 DiagKind = diag::err_typecheck_convert_incompatible; 13969 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13970 MayHaveConvFixit = true; 13971 isInvalid = true; 13972 MayHaveFunctionDiff = true; 13973 break; 13974 } 13975 13976 QualType FirstType, SecondType; 13977 switch (Action) { 13978 case AA_Assigning: 13979 case AA_Initializing: 13980 // The destination type comes first. 13981 FirstType = DstType; 13982 SecondType = SrcType; 13983 break; 13984 13985 case AA_Returning: 13986 case AA_Passing: 13987 case AA_Passing_CFAudited: 13988 case AA_Converting: 13989 case AA_Sending: 13990 case AA_Casting: 13991 // The source type comes first. 13992 FirstType = SrcType; 13993 SecondType = DstType; 13994 break; 13995 } 13996 13997 PartialDiagnostic FDiag = PDiag(DiagKind); 13998 if (Action == AA_Passing_CFAudited) 13999 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14000 else 14001 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14002 14003 // If we can fix the conversion, suggest the FixIts. 14004 assert(ConvHints.isNull() || Hint.isNull()); 14005 if (!ConvHints.isNull()) { 14006 for (FixItHint &H : ConvHints.Hints) 14007 FDiag << H; 14008 } else { 14009 FDiag << Hint; 14010 } 14011 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14012 14013 if (MayHaveFunctionDiff) 14014 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14015 14016 Diag(Loc, FDiag); 14017 if (DiagKind == diag::warn_incompatible_qualified_id && 14018 PDecl && IFace && !IFace->hasDefinition()) 14019 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14020 << IFace << PDecl; 14021 14022 if (SecondType == Context.OverloadTy) 14023 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14024 FirstType, /*TakingAddress=*/true); 14025 14026 if (CheckInferredResultType) 14027 EmitRelatedResultTypeNote(SrcExpr); 14028 14029 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14030 EmitRelatedResultTypeNoteForReturn(DstType); 14031 14032 if (Complained) 14033 *Complained = true; 14034 return isInvalid; 14035 } 14036 14037 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14038 llvm::APSInt *Result) { 14039 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14040 public: 14041 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14042 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14043 } 14044 } Diagnoser; 14045 14046 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14047 } 14048 14049 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14050 llvm::APSInt *Result, 14051 unsigned DiagID, 14052 bool AllowFold) { 14053 class IDDiagnoser : public VerifyICEDiagnoser { 14054 unsigned DiagID; 14055 14056 public: 14057 IDDiagnoser(unsigned DiagID) 14058 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14059 14060 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14061 S.Diag(Loc, DiagID) << SR; 14062 } 14063 } Diagnoser(DiagID); 14064 14065 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14066 } 14067 14068 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14069 SourceRange SR) { 14070 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14071 } 14072 14073 ExprResult 14074 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14075 VerifyICEDiagnoser &Diagnoser, 14076 bool AllowFold) { 14077 SourceLocation DiagLoc = E->getBeginLoc(); 14078 14079 if (getLangOpts().CPlusPlus11) { 14080 // C++11 [expr.const]p5: 14081 // If an expression of literal class type is used in a context where an 14082 // integral constant expression is required, then that class type shall 14083 // have a single non-explicit conversion function to an integral or 14084 // unscoped enumeration type 14085 ExprResult Converted; 14086 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14087 public: 14088 CXX11ConvertDiagnoser(bool Silent) 14089 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14090 Silent, true) {} 14091 14092 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14093 QualType T) override { 14094 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14095 } 14096 14097 SemaDiagnosticBuilder diagnoseIncomplete( 14098 Sema &S, SourceLocation Loc, QualType T) override { 14099 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14100 } 14101 14102 SemaDiagnosticBuilder diagnoseExplicitConv( 14103 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14104 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14105 } 14106 14107 SemaDiagnosticBuilder noteExplicitConv( 14108 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14109 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14110 << ConvTy->isEnumeralType() << ConvTy; 14111 } 14112 14113 SemaDiagnosticBuilder diagnoseAmbiguous( 14114 Sema &S, SourceLocation Loc, QualType T) override { 14115 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14116 } 14117 14118 SemaDiagnosticBuilder noteAmbiguous( 14119 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14120 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14121 << ConvTy->isEnumeralType() << ConvTy; 14122 } 14123 14124 SemaDiagnosticBuilder diagnoseConversion( 14125 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14126 llvm_unreachable("conversion functions are permitted"); 14127 } 14128 } ConvertDiagnoser(Diagnoser.Suppress); 14129 14130 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14131 ConvertDiagnoser); 14132 if (Converted.isInvalid()) 14133 return Converted; 14134 E = Converted.get(); 14135 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14136 return ExprError(); 14137 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14138 // An ICE must be of integral or unscoped enumeration type. 14139 if (!Diagnoser.Suppress) 14140 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14141 return ExprError(); 14142 } 14143 14144 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14145 // in the non-ICE case. 14146 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14147 if (Result) 14148 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14149 return new (Context) ConstantExpr(E); 14150 } 14151 14152 Expr::EvalResult EvalResult; 14153 SmallVector<PartialDiagnosticAt, 8> Notes; 14154 EvalResult.Diag = &Notes; 14155 14156 // Try to evaluate the expression, and produce diagnostics explaining why it's 14157 // not a constant expression as a side-effect. 14158 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14159 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14160 14161 // In C++11, we can rely on diagnostics being produced for any expression 14162 // which is not a constant expression. If no diagnostics were produced, then 14163 // this is a constant expression. 14164 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14165 if (Result) 14166 *Result = EvalResult.Val.getInt(); 14167 return new (Context) ConstantExpr(E); 14168 } 14169 14170 // If our only note is the usual "invalid subexpression" note, just point 14171 // the caret at its location rather than producing an essentially 14172 // redundant note. 14173 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14174 diag::note_invalid_subexpr_in_const_expr) { 14175 DiagLoc = Notes[0].first; 14176 Notes.clear(); 14177 } 14178 14179 if (!Folded || !AllowFold) { 14180 if (!Diagnoser.Suppress) { 14181 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14182 for (const PartialDiagnosticAt &Note : Notes) 14183 Diag(Note.first, Note.second); 14184 } 14185 14186 return ExprError(); 14187 } 14188 14189 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14190 for (const PartialDiagnosticAt &Note : Notes) 14191 Diag(Note.first, Note.second); 14192 14193 if (Result) 14194 *Result = EvalResult.Val.getInt(); 14195 return new (Context) ConstantExpr(E); 14196 } 14197 14198 namespace { 14199 // Handle the case where we conclude a expression which we speculatively 14200 // considered to be unevaluated is actually evaluated. 14201 class TransformToPE : public TreeTransform<TransformToPE> { 14202 typedef TreeTransform<TransformToPE> BaseTransform; 14203 14204 public: 14205 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14206 14207 // Make sure we redo semantic analysis 14208 bool AlwaysRebuild() { return true; } 14209 14210 // Make sure we handle LabelStmts correctly. 14211 // FIXME: This does the right thing, but maybe we need a more general 14212 // fix to TreeTransform? 14213 StmtResult TransformLabelStmt(LabelStmt *S) { 14214 S->getDecl()->setStmt(nullptr); 14215 return BaseTransform::TransformLabelStmt(S); 14216 } 14217 14218 // We need to special-case DeclRefExprs referring to FieldDecls which 14219 // are not part of a member pointer formation; normal TreeTransforming 14220 // doesn't catch this case because of the way we represent them in the AST. 14221 // FIXME: This is a bit ugly; is it really the best way to handle this 14222 // case? 14223 // 14224 // Error on DeclRefExprs referring to FieldDecls. 14225 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14226 if (isa<FieldDecl>(E->getDecl()) && 14227 !SemaRef.isUnevaluatedContext()) 14228 return SemaRef.Diag(E->getLocation(), 14229 diag::err_invalid_non_static_member_use) 14230 << E->getDecl() << E->getSourceRange(); 14231 14232 return BaseTransform::TransformDeclRefExpr(E); 14233 } 14234 14235 // Exception: filter out member pointer formation 14236 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14237 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14238 return E; 14239 14240 return BaseTransform::TransformUnaryOperator(E); 14241 } 14242 14243 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14244 // Lambdas never need to be transformed. 14245 return E; 14246 } 14247 }; 14248 } 14249 14250 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14251 assert(isUnevaluatedContext() && 14252 "Should only transform unevaluated expressions"); 14253 ExprEvalContexts.back().Context = 14254 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14255 if (isUnevaluatedContext()) 14256 return E; 14257 return TransformToPE(*this).TransformExpr(E); 14258 } 14259 14260 void 14261 Sema::PushExpressionEvaluationContext( 14262 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14263 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14264 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14265 LambdaContextDecl, ExprContext); 14266 Cleanup.reset(); 14267 if (!MaybeODRUseExprs.empty()) 14268 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14269 } 14270 14271 void 14272 Sema::PushExpressionEvaluationContext( 14273 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14274 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14275 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14276 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14277 } 14278 14279 void Sema::PopExpressionEvaluationContext() { 14280 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14281 unsigned NumTypos = Rec.NumTypos; 14282 14283 if (!Rec.Lambdas.empty()) { 14284 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14285 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14286 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14287 unsigned D; 14288 if (Rec.isUnevaluated()) { 14289 // C++11 [expr.prim.lambda]p2: 14290 // A lambda-expression shall not appear in an unevaluated operand 14291 // (Clause 5). 14292 D = diag::err_lambda_unevaluated_operand; 14293 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14294 // C++1y [expr.const]p2: 14295 // A conditional-expression e is a core constant expression unless the 14296 // evaluation of e, following the rules of the abstract machine, would 14297 // evaluate [...] a lambda-expression. 14298 D = diag::err_lambda_in_constant_expression; 14299 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14300 // C++17 [expr.prim.lamda]p2: 14301 // A lambda-expression shall not appear [...] in a template-argument. 14302 D = diag::err_lambda_in_invalid_context; 14303 } else 14304 llvm_unreachable("Couldn't infer lambda error message."); 14305 14306 for (const auto *L : Rec.Lambdas) 14307 Diag(L->getBeginLoc(), D); 14308 } else { 14309 // Mark the capture expressions odr-used. This was deferred 14310 // during lambda expression creation. 14311 for (auto *Lambda : Rec.Lambdas) { 14312 for (auto *C : Lambda->capture_inits()) 14313 MarkDeclarationsReferencedInExpr(C); 14314 } 14315 } 14316 } 14317 14318 // When are coming out of an unevaluated context, clear out any 14319 // temporaries that we may have created as part of the evaluation of 14320 // the expression in that context: they aren't relevant because they 14321 // will never be constructed. 14322 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14323 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14324 ExprCleanupObjects.end()); 14325 Cleanup = Rec.ParentCleanup; 14326 CleanupVarDeclMarking(); 14327 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14328 // Otherwise, merge the contexts together. 14329 } else { 14330 Cleanup.mergeFrom(Rec.ParentCleanup); 14331 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14332 Rec.SavedMaybeODRUseExprs.end()); 14333 } 14334 14335 // Pop the current expression evaluation context off the stack. 14336 ExprEvalContexts.pop_back(); 14337 14338 if (!ExprEvalContexts.empty()) 14339 ExprEvalContexts.back().NumTypos += NumTypos; 14340 else 14341 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14342 "last ExpressionEvaluationContextRecord"); 14343 } 14344 14345 void Sema::DiscardCleanupsInEvaluationContext() { 14346 ExprCleanupObjects.erase( 14347 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14348 ExprCleanupObjects.end()); 14349 Cleanup.reset(); 14350 MaybeODRUseExprs.clear(); 14351 } 14352 14353 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14354 if (!E->getType()->isVariablyModifiedType()) 14355 return E; 14356 return TransformToPotentiallyEvaluated(E); 14357 } 14358 14359 /// Are we within a context in which some evaluation could be performed (be it 14360 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14361 /// captured by C++'s idea of an "unevaluated context". 14362 static bool isEvaluatableContext(Sema &SemaRef) { 14363 switch (SemaRef.ExprEvalContexts.back().Context) { 14364 case Sema::ExpressionEvaluationContext::Unevaluated: 14365 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14366 // Expressions in this context are never evaluated. 14367 return false; 14368 14369 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14370 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14371 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14372 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14373 // Expressions in this context could be evaluated. 14374 return true; 14375 14376 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14377 // Referenced declarations will only be used if the construct in the 14378 // containing expression is used, at which point we'll be given another 14379 // turn to mark them. 14380 return false; 14381 } 14382 llvm_unreachable("Invalid context"); 14383 } 14384 14385 /// Are we within a context in which references to resolved functions or to 14386 /// variables result in odr-use? 14387 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14388 // An expression in a template is not really an expression until it's been 14389 // instantiated, so it doesn't trigger odr-use. 14390 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14391 return false; 14392 14393 switch (SemaRef.ExprEvalContexts.back().Context) { 14394 case Sema::ExpressionEvaluationContext::Unevaluated: 14395 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14396 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14397 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14398 return false; 14399 14400 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14401 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14402 return true; 14403 14404 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14405 return false; 14406 } 14407 llvm_unreachable("Invalid context"); 14408 } 14409 14410 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14411 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14412 return Func->isConstexpr() && 14413 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14414 } 14415 14416 /// Mark a function referenced, and check whether it is odr-used 14417 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14418 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14419 bool MightBeOdrUse) { 14420 assert(Func && "No function?"); 14421 14422 Func->setReferenced(); 14423 14424 // C++11 [basic.def.odr]p3: 14425 // A function whose name appears as a potentially-evaluated expression is 14426 // odr-used if it is the unique lookup result or the selected member of a 14427 // set of overloaded functions [...]. 14428 // 14429 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14430 // can just check that here. 14431 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14432 14433 // Determine whether we require a function definition to exist, per 14434 // C++11 [temp.inst]p3: 14435 // Unless a function template specialization has been explicitly 14436 // instantiated or explicitly specialized, the function template 14437 // specialization is implicitly instantiated when the specialization is 14438 // referenced in a context that requires a function definition to exist. 14439 // 14440 // That is either when this is an odr-use, or when a usage of a constexpr 14441 // function occurs within an evaluatable context. 14442 bool NeedDefinition = 14443 OdrUse || (isEvaluatableContext(*this) && 14444 isImplicitlyDefinableConstexprFunction(Func)); 14445 14446 // C++14 [temp.expl.spec]p6: 14447 // If a template [...] is explicitly specialized then that specialization 14448 // shall be declared before the first use of that specialization that would 14449 // cause an implicit instantiation to take place, in every translation unit 14450 // in which such a use occurs 14451 if (NeedDefinition && 14452 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14453 Func->getMemberSpecializationInfo())) 14454 checkSpecializationVisibility(Loc, Func); 14455 14456 // C++14 [except.spec]p17: 14457 // An exception-specification is considered to be needed when: 14458 // - the function is odr-used or, if it appears in an unevaluated operand, 14459 // would be odr-used if the expression were potentially-evaluated; 14460 // 14461 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14462 // function is a pure virtual function we're calling, and in that case the 14463 // function was selected by overload resolution and we need to resolve its 14464 // exception specification for a different reason. 14465 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14466 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14467 ResolveExceptionSpec(Loc, FPT); 14468 14469 // If we don't need to mark the function as used, and we don't need to 14470 // try to provide a definition, there's nothing more to do. 14471 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14472 (!NeedDefinition || Func->getBody())) 14473 return; 14474 14475 // Note that this declaration has been used. 14476 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14477 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14478 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14479 if (Constructor->isDefaultConstructor()) { 14480 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14481 return; 14482 DefineImplicitDefaultConstructor(Loc, Constructor); 14483 } else if (Constructor->isCopyConstructor()) { 14484 DefineImplicitCopyConstructor(Loc, Constructor); 14485 } else if (Constructor->isMoveConstructor()) { 14486 DefineImplicitMoveConstructor(Loc, Constructor); 14487 } 14488 } else if (Constructor->getInheritedConstructor()) { 14489 DefineInheritingConstructor(Loc, Constructor); 14490 } 14491 } else if (CXXDestructorDecl *Destructor = 14492 dyn_cast<CXXDestructorDecl>(Func)) { 14493 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14494 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14495 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14496 return; 14497 DefineImplicitDestructor(Loc, Destructor); 14498 } 14499 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14500 MarkVTableUsed(Loc, Destructor->getParent()); 14501 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14502 if (MethodDecl->isOverloadedOperator() && 14503 MethodDecl->getOverloadedOperator() == OO_Equal) { 14504 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14505 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14506 if (MethodDecl->isCopyAssignmentOperator()) 14507 DefineImplicitCopyAssignment(Loc, MethodDecl); 14508 else if (MethodDecl->isMoveAssignmentOperator()) 14509 DefineImplicitMoveAssignment(Loc, MethodDecl); 14510 } 14511 } else if (isa<CXXConversionDecl>(MethodDecl) && 14512 MethodDecl->getParent()->isLambda()) { 14513 CXXConversionDecl *Conversion = 14514 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14515 if (Conversion->isLambdaToBlockPointerConversion()) 14516 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14517 else 14518 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14519 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14520 MarkVTableUsed(Loc, MethodDecl->getParent()); 14521 } 14522 14523 // Recursive functions should be marked when used from another function. 14524 // FIXME: Is this really right? 14525 if (CurContext == Func) return; 14526 14527 // Implicit instantiation of function templates and member functions of 14528 // class templates. 14529 if (Func->isImplicitlyInstantiable()) { 14530 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14531 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14532 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14533 if (FirstInstantiation) { 14534 PointOfInstantiation = Loc; 14535 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14536 } else if (TSK != TSK_ImplicitInstantiation) { 14537 // Use the point of use as the point of instantiation, instead of the 14538 // point of explicit instantiation (which we track as the actual point of 14539 // instantiation). This gives better backtraces in diagnostics. 14540 PointOfInstantiation = Loc; 14541 } 14542 14543 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14544 Func->isConstexpr()) { 14545 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14546 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14547 CodeSynthesisContexts.size()) 14548 PendingLocalImplicitInstantiations.push_back( 14549 std::make_pair(Func, PointOfInstantiation)); 14550 else if (Func->isConstexpr()) 14551 // Do not defer instantiations of constexpr functions, to avoid the 14552 // expression evaluator needing to call back into Sema if it sees a 14553 // call to such a function. 14554 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14555 else { 14556 Func->setInstantiationIsPending(true); 14557 PendingInstantiations.push_back(std::make_pair(Func, 14558 PointOfInstantiation)); 14559 // Notify the consumer that a function was implicitly instantiated. 14560 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14561 } 14562 } 14563 } else { 14564 // Walk redefinitions, as some of them may be instantiable. 14565 for (auto i : Func->redecls()) { 14566 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14567 MarkFunctionReferenced(Loc, i, OdrUse); 14568 } 14569 } 14570 14571 if (!OdrUse) return; 14572 14573 // Keep track of used but undefined functions. 14574 if (!Func->isDefined()) { 14575 if (mightHaveNonExternalLinkage(Func)) 14576 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14577 else if (Func->getMostRecentDecl()->isInlined() && 14578 !LangOpts.GNUInline && 14579 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14580 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14581 else if (isExternalWithNoLinkageType(Func)) 14582 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14583 } 14584 14585 Func->markUsed(Context); 14586 } 14587 14588 static void 14589 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14590 ValueDecl *var, DeclContext *DC) { 14591 DeclContext *VarDC = var->getDeclContext(); 14592 14593 // If the parameter still belongs to the translation unit, then 14594 // we're actually just using one parameter in the declaration of 14595 // the next. 14596 if (isa<ParmVarDecl>(var) && 14597 isa<TranslationUnitDecl>(VarDC)) 14598 return; 14599 14600 // For C code, don't diagnose about capture if we're not actually in code 14601 // right now; it's impossible to write a non-constant expression outside of 14602 // function context, so we'll get other (more useful) diagnostics later. 14603 // 14604 // For C++, things get a bit more nasty... it would be nice to suppress this 14605 // diagnostic for certain cases like using a local variable in an array bound 14606 // for a member of a local class, but the correct predicate is not obvious. 14607 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14608 return; 14609 14610 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14611 unsigned ContextKind = 3; // unknown 14612 if (isa<CXXMethodDecl>(VarDC) && 14613 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14614 ContextKind = 2; 14615 } else if (isa<FunctionDecl>(VarDC)) { 14616 ContextKind = 0; 14617 } else if (isa<BlockDecl>(VarDC)) { 14618 ContextKind = 1; 14619 } 14620 14621 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14622 << var << ValueKind << ContextKind << VarDC; 14623 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14624 << var; 14625 14626 // FIXME: Add additional diagnostic info about class etc. which prevents 14627 // capture. 14628 } 14629 14630 14631 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14632 bool &SubCapturesAreNested, 14633 QualType &CaptureType, 14634 QualType &DeclRefType) { 14635 // Check whether we've already captured it. 14636 if (CSI->CaptureMap.count(Var)) { 14637 // If we found a capture, any subcaptures are nested. 14638 SubCapturesAreNested = true; 14639 14640 // Retrieve the capture type for this variable. 14641 CaptureType = CSI->getCapture(Var).getCaptureType(); 14642 14643 // Compute the type of an expression that refers to this variable. 14644 DeclRefType = CaptureType.getNonReferenceType(); 14645 14646 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14647 // are mutable in the sense that user can change their value - they are 14648 // private instances of the captured declarations. 14649 const Capture &Cap = CSI->getCapture(Var); 14650 if (Cap.isCopyCapture() && 14651 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14652 !(isa<CapturedRegionScopeInfo>(CSI) && 14653 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14654 DeclRefType.addConst(); 14655 return true; 14656 } 14657 return false; 14658 } 14659 14660 // Only block literals, captured statements, and lambda expressions can 14661 // capture; other scopes don't work. 14662 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14663 SourceLocation Loc, 14664 const bool Diagnose, Sema &S) { 14665 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14666 return getLambdaAwareParentOfDeclContext(DC); 14667 else if (Var->hasLocalStorage()) { 14668 if (Diagnose) 14669 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14670 } 14671 return nullptr; 14672 } 14673 14674 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14675 // certain types of variables (unnamed, variably modified types etc.) 14676 // so check for eligibility. 14677 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14678 SourceLocation Loc, 14679 const bool Diagnose, Sema &S) { 14680 14681 bool IsBlock = isa<BlockScopeInfo>(CSI); 14682 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14683 14684 // Lambdas are not allowed to capture unnamed variables 14685 // (e.g. anonymous unions). 14686 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14687 // assuming that's the intent. 14688 if (IsLambda && !Var->getDeclName()) { 14689 if (Diagnose) { 14690 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14691 S.Diag(Var->getLocation(), diag::note_declared_at); 14692 } 14693 return false; 14694 } 14695 14696 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14697 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14698 if (Diagnose) { 14699 S.Diag(Loc, diag::err_ref_vm_type); 14700 S.Diag(Var->getLocation(), diag::note_previous_decl) 14701 << Var->getDeclName(); 14702 } 14703 return false; 14704 } 14705 // Prohibit structs with flexible array members too. 14706 // We cannot capture what is in the tail end of the struct. 14707 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14708 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14709 if (Diagnose) { 14710 if (IsBlock) 14711 S.Diag(Loc, diag::err_ref_flexarray_type); 14712 else 14713 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14714 << Var->getDeclName(); 14715 S.Diag(Var->getLocation(), diag::note_previous_decl) 14716 << Var->getDeclName(); 14717 } 14718 return false; 14719 } 14720 } 14721 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14722 // Lambdas and captured statements are not allowed to capture __block 14723 // variables; they don't support the expected semantics. 14724 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14725 if (Diagnose) { 14726 S.Diag(Loc, diag::err_capture_block_variable) 14727 << Var->getDeclName() << !IsLambda; 14728 S.Diag(Var->getLocation(), diag::note_previous_decl) 14729 << Var->getDeclName(); 14730 } 14731 return false; 14732 } 14733 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14734 if (S.getLangOpts().OpenCL && IsBlock && 14735 Var->getType()->isBlockPointerType()) { 14736 if (Diagnose) 14737 S.Diag(Loc, diag::err_opencl_block_ref_block); 14738 return false; 14739 } 14740 14741 return true; 14742 } 14743 14744 // Returns true if the capture by block was successful. 14745 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14746 SourceLocation Loc, 14747 const bool BuildAndDiagnose, 14748 QualType &CaptureType, 14749 QualType &DeclRefType, 14750 const bool Nested, 14751 Sema &S) { 14752 Expr *CopyExpr = nullptr; 14753 bool ByRef = false; 14754 14755 // Blocks are not allowed to capture arrays, excepting OpenCL. 14756 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 14757 // (decayed to pointers). 14758 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 14759 if (BuildAndDiagnose) { 14760 S.Diag(Loc, diag::err_ref_array_type); 14761 S.Diag(Var->getLocation(), diag::note_previous_decl) 14762 << Var->getDeclName(); 14763 } 14764 return false; 14765 } 14766 14767 // Forbid the block-capture of autoreleasing variables. 14768 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14769 if (BuildAndDiagnose) { 14770 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14771 << /*block*/ 0; 14772 S.Diag(Var->getLocation(), diag::note_previous_decl) 14773 << Var->getDeclName(); 14774 } 14775 return false; 14776 } 14777 14778 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14779 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14780 // This function finds out whether there is an AttributedType of kind 14781 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14782 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14783 // rather than being added implicitly by the compiler. 14784 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14785 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14786 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 14787 return true; 14788 14789 // Peel off AttributedTypes that are not of kind ObjCOwnership. 14790 Ty = AttrTy->getModifiedType(); 14791 } 14792 14793 return false; 14794 }; 14795 14796 QualType PointeeTy = PT->getPointeeType(); 14797 14798 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14799 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14800 !IsObjCOwnershipAttributedType(PointeeTy)) { 14801 if (BuildAndDiagnose) { 14802 SourceLocation VarLoc = Var->getLocation(); 14803 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14804 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14805 } 14806 } 14807 } 14808 14809 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14810 if (HasBlocksAttr || CaptureType->isReferenceType() || 14811 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14812 // Block capture by reference does not change the capture or 14813 // declaration reference types. 14814 ByRef = true; 14815 } else { 14816 // Block capture by copy introduces 'const'. 14817 CaptureType = CaptureType.getNonReferenceType().withConst(); 14818 DeclRefType = CaptureType; 14819 14820 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14821 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14822 // The capture logic needs the destructor, so make sure we mark it. 14823 // Usually this is unnecessary because most local variables have 14824 // their destructors marked at declaration time, but parameters are 14825 // an exception because it's technically only the call site that 14826 // actually requires the destructor. 14827 if (isa<ParmVarDecl>(Var)) 14828 S.FinalizeVarWithDestructor(Var, Record); 14829 14830 // Enter a new evaluation context to insulate the copy 14831 // full-expression. 14832 EnterExpressionEvaluationContext scope( 14833 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14834 14835 // According to the blocks spec, the capture of a variable from 14836 // the stack requires a const copy constructor. This is not true 14837 // of the copy/move done to move a __block variable to the heap. 14838 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14839 DeclRefType.withConst(), 14840 VK_LValue, Loc); 14841 14842 ExprResult Result 14843 = S.PerformCopyInitialization( 14844 InitializedEntity::InitializeBlock(Var->getLocation(), 14845 CaptureType, false), 14846 Loc, DeclRef); 14847 14848 // Build a full-expression copy expression if initialization 14849 // succeeded and used a non-trivial constructor. Recover from 14850 // errors by pretending that the copy isn't necessary. 14851 if (!Result.isInvalid() && 14852 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14853 ->isTrivial()) { 14854 Result = S.MaybeCreateExprWithCleanups(Result); 14855 CopyExpr = Result.get(); 14856 } 14857 } 14858 } 14859 } 14860 14861 // Actually capture the variable. 14862 if (BuildAndDiagnose) 14863 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14864 SourceLocation(), CaptureType, CopyExpr); 14865 14866 return true; 14867 14868 } 14869 14870 14871 /// Capture the given variable in the captured region. 14872 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14873 VarDecl *Var, 14874 SourceLocation Loc, 14875 const bool BuildAndDiagnose, 14876 QualType &CaptureType, 14877 QualType &DeclRefType, 14878 const bool RefersToCapturedVariable, 14879 Sema &S) { 14880 // By default, capture variables by reference. 14881 bool ByRef = true; 14882 // Using an LValue reference type is consistent with Lambdas (see below). 14883 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14884 if (S.isOpenMPCapturedDecl(Var)) { 14885 bool HasConst = DeclRefType.isConstQualified(); 14886 DeclRefType = DeclRefType.getUnqualifiedType(); 14887 // Don't lose diagnostics about assignments to const. 14888 if (HasConst) 14889 DeclRefType.addConst(); 14890 } 14891 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14892 } 14893 14894 if (ByRef) 14895 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14896 else 14897 CaptureType = DeclRefType; 14898 14899 Expr *CopyExpr = nullptr; 14900 if (BuildAndDiagnose) { 14901 // The current implementation assumes that all variables are captured 14902 // by references. Since there is no capture by copy, no expression 14903 // evaluation will be needed. 14904 RecordDecl *RD = RSI->TheRecordDecl; 14905 14906 FieldDecl *Field 14907 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14908 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14909 nullptr, false, ICIS_NoInit); 14910 Field->setImplicit(true); 14911 Field->setAccess(AS_private); 14912 RD->addDecl(Field); 14913 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14914 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14915 14916 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14917 DeclRefType, VK_LValue, Loc); 14918 Var->setReferenced(true); 14919 Var->markUsed(S.Context); 14920 } 14921 14922 // Actually capture the variable. 14923 if (BuildAndDiagnose) 14924 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14925 SourceLocation(), CaptureType, CopyExpr); 14926 14927 14928 return true; 14929 } 14930 14931 /// Create a field within the lambda class for the variable 14932 /// being captured. 14933 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14934 QualType FieldType, QualType DeclRefType, 14935 SourceLocation Loc, 14936 bool RefersToCapturedVariable) { 14937 CXXRecordDecl *Lambda = LSI->Lambda; 14938 14939 // Build the non-static data member. 14940 FieldDecl *Field 14941 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14942 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14943 nullptr, false, ICIS_NoInit); 14944 Field->setImplicit(true); 14945 Field->setAccess(AS_private); 14946 Lambda->addDecl(Field); 14947 } 14948 14949 /// Capture the given variable in the lambda. 14950 static bool captureInLambda(LambdaScopeInfo *LSI, 14951 VarDecl *Var, 14952 SourceLocation Loc, 14953 const bool BuildAndDiagnose, 14954 QualType &CaptureType, 14955 QualType &DeclRefType, 14956 const bool RefersToCapturedVariable, 14957 const Sema::TryCaptureKind Kind, 14958 SourceLocation EllipsisLoc, 14959 const bool IsTopScope, 14960 Sema &S) { 14961 14962 // Determine whether we are capturing by reference or by value. 14963 bool ByRef = false; 14964 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14965 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14966 } else { 14967 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14968 } 14969 14970 // Compute the type of the field that will capture this variable. 14971 if (ByRef) { 14972 // C++11 [expr.prim.lambda]p15: 14973 // An entity is captured by reference if it is implicitly or 14974 // explicitly captured but not captured by copy. It is 14975 // unspecified whether additional unnamed non-static data 14976 // members are declared in the closure type for entities 14977 // captured by reference. 14978 // 14979 // FIXME: It is not clear whether we want to build an lvalue reference 14980 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14981 // to do the former, while EDG does the latter. Core issue 1249 will 14982 // clarify, but for now we follow GCC because it's a more permissive and 14983 // easily defensible position. 14984 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14985 } else { 14986 // C++11 [expr.prim.lambda]p14: 14987 // For each entity captured by copy, an unnamed non-static 14988 // data member is declared in the closure type. The 14989 // declaration order of these members is unspecified. The type 14990 // of such a data member is the type of the corresponding 14991 // captured entity if the entity is not a reference to an 14992 // object, or the referenced type otherwise. [Note: If the 14993 // captured entity is a reference to a function, the 14994 // corresponding data member is also a reference to a 14995 // function. - end note ] 14996 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14997 if (!RefType->getPointeeType()->isFunctionType()) 14998 CaptureType = RefType->getPointeeType(); 14999 } 15000 15001 // Forbid the lambda copy-capture of autoreleasing variables. 15002 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15003 if (BuildAndDiagnose) { 15004 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15005 S.Diag(Var->getLocation(), diag::note_previous_decl) 15006 << Var->getDeclName(); 15007 } 15008 return false; 15009 } 15010 15011 // Make sure that by-copy captures are of a complete and non-abstract type. 15012 if (BuildAndDiagnose) { 15013 if (!CaptureType->isDependentType() && 15014 S.RequireCompleteType(Loc, CaptureType, 15015 diag::err_capture_of_incomplete_type, 15016 Var->getDeclName())) 15017 return false; 15018 15019 if (S.RequireNonAbstractType(Loc, CaptureType, 15020 diag::err_capture_of_abstract_type)) 15021 return false; 15022 } 15023 } 15024 15025 // Capture this variable in the lambda. 15026 if (BuildAndDiagnose) 15027 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 15028 RefersToCapturedVariable); 15029 15030 // Compute the type of a reference to this captured variable. 15031 if (ByRef) 15032 DeclRefType = CaptureType.getNonReferenceType(); 15033 else { 15034 // C++ [expr.prim.lambda]p5: 15035 // The closure type for a lambda-expression has a public inline 15036 // function call operator [...]. This function call operator is 15037 // declared const (9.3.1) if and only if the lambda-expression's 15038 // parameter-declaration-clause is not followed by mutable. 15039 DeclRefType = CaptureType.getNonReferenceType(); 15040 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15041 DeclRefType.addConst(); 15042 } 15043 15044 // Add the capture. 15045 if (BuildAndDiagnose) 15046 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15047 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15048 15049 return true; 15050 } 15051 15052 bool Sema::tryCaptureVariable( 15053 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15054 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15055 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15056 // An init-capture is notionally from the context surrounding its 15057 // declaration, but its parent DC is the lambda class. 15058 DeclContext *VarDC = Var->getDeclContext(); 15059 if (Var->isInitCapture()) 15060 VarDC = VarDC->getParent(); 15061 15062 DeclContext *DC = CurContext; 15063 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15064 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15065 // We need to sync up the Declaration Context with the 15066 // FunctionScopeIndexToStopAt 15067 if (FunctionScopeIndexToStopAt) { 15068 unsigned FSIndex = FunctionScopes.size() - 1; 15069 while (FSIndex != MaxFunctionScopesIndex) { 15070 DC = getLambdaAwareParentOfDeclContext(DC); 15071 --FSIndex; 15072 } 15073 } 15074 15075 15076 // If the variable is declared in the current context, there is no need to 15077 // capture it. 15078 if (VarDC == DC) return true; 15079 15080 // Capture global variables if it is required to use private copy of this 15081 // variable. 15082 bool IsGlobal = !Var->hasLocalStorage(); 15083 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15084 return true; 15085 Var = Var->getCanonicalDecl(); 15086 15087 // Walk up the stack to determine whether we can capture the variable, 15088 // performing the "simple" checks that don't depend on type. We stop when 15089 // we've either hit the declared scope of the variable or find an existing 15090 // capture of that variable. We start from the innermost capturing-entity 15091 // (the DC) and ensure that all intervening capturing-entities 15092 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15093 // declcontext can either capture the variable or have already captured 15094 // the variable. 15095 CaptureType = Var->getType(); 15096 DeclRefType = CaptureType.getNonReferenceType(); 15097 bool Nested = false; 15098 bool Explicit = (Kind != TryCapture_Implicit); 15099 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15100 do { 15101 // Only block literals, captured statements, and lambda expressions can 15102 // capture; other scopes don't work. 15103 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15104 ExprLoc, 15105 BuildAndDiagnose, 15106 *this); 15107 // We need to check for the parent *first* because, if we *have* 15108 // private-captured a global variable, we need to recursively capture it in 15109 // intermediate blocks, lambdas, etc. 15110 if (!ParentDC) { 15111 if (IsGlobal) { 15112 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15113 break; 15114 } 15115 return true; 15116 } 15117 15118 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15119 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15120 15121 15122 // Check whether we've already captured it. 15123 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15124 DeclRefType)) { 15125 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15126 break; 15127 } 15128 // If we are instantiating a generic lambda call operator body, 15129 // we do not want to capture new variables. What was captured 15130 // during either a lambdas transformation or initial parsing 15131 // should be used. 15132 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15133 if (BuildAndDiagnose) { 15134 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15135 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15136 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15137 Diag(Var->getLocation(), diag::note_previous_decl) 15138 << Var->getDeclName(); 15139 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15140 } else 15141 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15142 } 15143 return true; 15144 } 15145 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15146 // certain types of variables (unnamed, variably modified types etc.) 15147 // so check for eligibility. 15148 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15149 return true; 15150 15151 // Try to capture variable-length arrays types. 15152 if (Var->getType()->isVariablyModifiedType()) { 15153 // We're going to walk down into the type and look for VLA 15154 // expressions. 15155 QualType QTy = Var->getType(); 15156 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15157 QTy = PVD->getOriginalType(); 15158 captureVariablyModifiedType(Context, QTy, CSI); 15159 } 15160 15161 if (getLangOpts().OpenMP) { 15162 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15163 // OpenMP private variables should not be captured in outer scope, so 15164 // just break here. Similarly, global variables that are captured in a 15165 // target region should not be captured outside the scope of the region. 15166 if (RSI->CapRegionKind == CR_OpenMP) { 15167 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15168 auto IsTargetCap = !IsOpenMPPrivateDecl && 15169 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15170 // When we detect target captures we are looking from inside the 15171 // target region, therefore we need to propagate the capture from the 15172 // enclosing region. Therefore, the capture is not initially nested. 15173 if (IsTargetCap) 15174 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15175 15176 if (IsTargetCap || IsOpenMPPrivateDecl) { 15177 Nested = !IsTargetCap; 15178 DeclRefType = DeclRefType.getUnqualifiedType(); 15179 CaptureType = Context.getLValueReferenceType(DeclRefType); 15180 break; 15181 } 15182 } 15183 } 15184 } 15185 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15186 // No capture-default, and this is not an explicit capture 15187 // so cannot capture this variable. 15188 if (BuildAndDiagnose) { 15189 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15190 Diag(Var->getLocation(), diag::note_previous_decl) 15191 << Var->getDeclName(); 15192 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15193 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15194 diag::note_lambda_decl); 15195 // FIXME: If we error out because an outer lambda can not implicitly 15196 // capture a variable that an inner lambda explicitly captures, we 15197 // should have the inner lambda do the explicit capture - because 15198 // it makes for cleaner diagnostics later. This would purely be done 15199 // so that the diagnostic does not misleadingly claim that a variable 15200 // can not be captured by a lambda implicitly even though it is captured 15201 // explicitly. Suggestion: 15202 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15203 // at the function head 15204 // - cache the StartingDeclContext - this must be a lambda 15205 // - captureInLambda in the innermost lambda the variable. 15206 } 15207 return true; 15208 } 15209 15210 FunctionScopesIndex--; 15211 DC = ParentDC; 15212 Explicit = false; 15213 } while (!VarDC->Equals(DC)); 15214 15215 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15216 // computing the type of the capture at each step, checking type-specific 15217 // requirements, and adding captures if requested. 15218 // If the variable had already been captured previously, we start capturing 15219 // at the lambda nested within that one. 15220 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15221 ++I) { 15222 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15223 15224 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15225 if (!captureInBlock(BSI, Var, ExprLoc, 15226 BuildAndDiagnose, CaptureType, 15227 DeclRefType, Nested, *this)) 15228 return true; 15229 Nested = true; 15230 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15231 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15232 BuildAndDiagnose, CaptureType, 15233 DeclRefType, Nested, *this)) 15234 return true; 15235 Nested = true; 15236 } else { 15237 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15238 if (!captureInLambda(LSI, Var, ExprLoc, 15239 BuildAndDiagnose, CaptureType, 15240 DeclRefType, Nested, Kind, EllipsisLoc, 15241 /*IsTopScope*/I == N - 1, *this)) 15242 return true; 15243 Nested = true; 15244 } 15245 } 15246 return false; 15247 } 15248 15249 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15250 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15251 QualType CaptureType; 15252 QualType DeclRefType; 15253 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15254 /*BuildAndDiagnose=*/true, CaptureType, 15255 DeclRefType, nullptr); 15256 } 15257 15258 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15259 QualType CaptureType; 15260 QualType DeclRefType; 15261 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15262 /*BuildAndDiagnose=*/false, CaptureType, 15263 DeclRefType, nullptr); 15264 } 15265 15266 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15267 QualType CaptureType; 15268 QualType DeclRefType; 15269 15270 // Determine whether we can capture this variable. 15271 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15272 /*BuildAndDiagnose=*/false, CaptureType, 15273 DeclRefType, nullptr)) 15274 return QualType(); 15275 15276 return DeclRefType; 15277 } 15278 15279 15280 15281 // If either the type of the variable or the initializer is dependent, 15282 // return false. Otherwise, determine whether the variable is a constant 15283 // expression. Use this if you need to know if a variable that might or 15284 // might not be dependent is truly a constant expression. 15285 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15286 ASTContext &Context) { 15287 15288 if (Var->getType()->isDependentType()) 15289 return false; 15290 const VarDecl *DefVD = nullptr; 15291 Var->getAnyInitializer(DefVD); 15292 if (!DefVD) 15293 return false; 15294 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15295 Expr *Init = cast<Expr>(Eval->Value); 15296 if (Init->isValueDependent()) 15297 return false; 15298 return IsVariableAConstantExpression(Var, Context); 15299 } 15300 15301 15302 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15303 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15304 // an object that satisfies the requirements for appearing in a 15305 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15306 // is immediately applied." This function handles the lvalue-to-rvalue 15307 // conversion part. 15308 MaybeODRUseExprs.erase(E->IgnoreParens()); 15309 15310 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15311 // to a variable that is a constant expression, and if so, identify it as 15312 // a reference to a variable that does not involve an odr-use of that 15313 // variable. 15314 if (LambdaScopeInfo *LSI = getCurLambda()) { 15315 Expr *SansParensExpr = E->IgnoreParens(); 15316 VarDecl *Var = nullptr; 15317 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15318 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15319 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15320 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15321 15322 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15323 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15324 } 15325 } 15326 15327 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15328 Res = CorrectDelayedTyposInExpr(Res); 15329 15330 if (!Res.isUsable()) 15331 return Res; 15332 15333 // If a constant-expression is a reference to a variable where we delay 15334 // deciding whether it is an odr-use, just assume we will apply the 15335 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15336 // (a non-type template argument), we have special handling anyway. 15337 UpdateMarkingForLValueToRValue(Res.get()); 15338 return Res; 15339 } 15340 15341 void Sema::CleanupVarDeclMarking() { 15342 for (Expr *E : MaybeODRUseExprs) { 15343 VarDecl *Var; 15344 SourceLocation Loc; 15345 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15346 Var = cast<VarDecl>(DRE->getDecl()); 15347 Loc = DRE->getLocation(); 15348 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15349 Var = cast<VarDecl>(ME->getMemberDecl()); 15350 Loc = ME->getMemberLoc(); 15351 } else { 15352 llvm_unreachable("Unexpected expression"); 15353 } 15354 15355 MarkVarDeclODRUsed(Var, Loc, *this, 15356 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15357 } 15358 15359 MaybeODRUseExprs.clear(); 15360 } 15361 15362 15363 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15364 VarDecl *Var, Expr *E) { 15365 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15366 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15367 Var->setReferenced(); 15368 15369 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15370 15371 bool OdrUseContext = isOdrUseContext(SemaRef); 15372 bool UsableInConstantExpr = 15373 Var->isUsableInConstantExpressions(SemaRef.Context); 15374 bool NeedDefinition = 15375 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15376 15377 VarTemplateSpecializationDecl *VarSpec = 15378 dyn_cast<VarTemplateSpecializationDecl>(Var); 15379 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15380 "Can't instantiate a partial template specialization."); 15381 15382 // If this might be a member specialization of a static data member, check 15383 // the specialization is visible. We already did the checks for variable 15384 // template specializations when we created them. 15385 if (NeedDefinition && TSK != TSK_Undeclared && 15386 !isa<VarTemplateSpecializationDecl>(Var)) 15387 SemaRef.checkSpecializationVisibility(Loc, Var); 15388 15389 // Perform implicit instantiation of static data members, static data member 15390 // templates of class templates, and variable template specializations. Delay 15391 // instantiations of variable templates, except for those that could be used 15392 // in a constant expression. 15393 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15394 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15395 // instantiation declaration if a variable is usable in a constant 15396 // expression (among other cases). 15397 bool TryInstantiating = 15398 TSK == TSK_ImplicitInstantiation || 15399 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15400 15401 if (TryInstantiating) { 15402 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15403 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15404 if (FirstInstantiation) { 15405 PointOfInstantiation = Loc; 15406 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15407 } 15408 15409 bool InstantiationDependent = false; 15410 bool IsNonDependent = 15411 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15412 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15413 : true; 15414 15415 // Do not instantiate specializations that are still type-dependent. 15416 if (IsNonDependent) { 15417 if (UsableInConstantExpr) { 15418 // Do not defer instantiations of variables that could be used in a 15419 // constant expression. 15420 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15421 } else if (FirstInstantiation || 15422 isa<VarTemplateSpecializationDecl>(Var)) { 15423 // FIXME: For a specialization of a variable template, we don't 15424 // distinguish between "declaration and type implicitly instantiated" 15425 // and "implicit instantiation of definition requested", so we have 15426 // no direct way to avoid enqueueing the pending instantiation 15427 // multiple times. 15428 SemaRef.PendingInstantiations 15429 .push_back(std::make_pair(Var, PointOfInstantiation)); 15430 } 15431 } 15432 } 15433 } 15434 15435 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15436 // the requirements for appearing in a constant expression (5.19) and, if 15437 // it is an object, the lvalue-to-rvalue conversion (4.1) 15438 // is immediately applied." We check the first part here, and 15439 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15440 // Note that we use the C++11 definition everywhere because nothing in 15441 // C++03 depends on whether we get the C++03 version correct. The second 15442 // part does not apply to references, since they are not objects. 15443 if (OdrUseContext && E && 15444 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15445 // A reference initialized by a constant expression can never be 15446 // odr-used, so simply ignore it. 15447 if (!Var->getType()->isReferenceType() || 15448 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15449 SemaRef.MaybeODRUseExprs.insert(E); 15450 } else if (OdrUseContext) { 15451 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15452 /*MaxFunctionScopeIndex ptr*/ nullptr); 15453 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15454 // If this is a dependent context, we don't need to mark variables as 15455 // odr-used, but we may still need to track them for lambda capture. 15456 // FIXME: Do we also need to do this inside dependent typeid expressions 15457 // (which are modeled as unevaluated at this point)? 15458 const bool RefersToEnclosingScope = 15459 (SemaRef.CurContext != Var->getDeclContext() && 15460 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15461 if (RefersToEnclosingScope) { 15462 LambdaScopeInfo *const LSI = 15463 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15464 if (LSI && (!LSI->CallOperator || 15465 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15466 // If a variable could potentially be odr-used, defer marking it so 15467 // until we finish analyzing the full expression for any 15468 // lvalue-to-rvalue 15469 // or discarded value conversions that would obviate odr-use. 15470 // Add it to the list of potential captures that will be analyzed 15471 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15472 // unless the variable is a reference that was initialized by a constant 15473 // expression (this will never need to be captured or odr-used). 15474 assert(E && "Capture variable should be used in an expression."); 15475 if (!Var->getType()->isReferenceType() || 15476 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15477 LSI->addPotentialCapture(E->IgnoreParens()); 15478 } 15479 } 15480 } 15481 } 15482 15483 /// Mark a variable referenced, and check whether it is odr-used 15484 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15485 /// used directly for normal expressions referring to VarDecl. 15486 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15487 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15488 } 15489 15490 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15491 Decl *D, Expr *E, bool MightBeOdrUse) { 15492 if (SemaRef.isInOpenMPDeclareTargetContext()) 15493 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15494 15495 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15496 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15497 return; 15498 } 15499 15500 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15501 15502 // If this is a call to a method via a cast, also mark the method in the 15503 // derived class used in case codegen can devirtualize the call. 15504 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15505 if (!ME) 15506 return; 15507 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15508 if (!MD) 15509 return; 15510 // Only attempt to devirtualize if this is truly a virtual call. 15511 bool IsVirtualCall = MD->isVirtual() && 15512 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15513 if (!IsVirtualCall) 15514 return; 15515 15516 // If it's possible to devirtualize the call, mark the called function 15517 // referenced. 15518 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15519 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15520 if (DM) 15521 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15522 } 15523 15524 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15525 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15526 // TODO: update this with DR# once a defect report is filed. 15527 // C++11 defect. The address of a pure member should not be an ODR use, even 15528 // if it's a qualified reference. 15529 bool OdrUse = true; 15530 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15531 if (Method->isVirtual() && 15532 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15533 OdrUse = false; 15534 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15535 } 15536 15537 /// Perform reference-marking and odr-use handling for a MemberExpr. 15538 void Sema::MarkMemberReferenced(MemberExpr *E) { 15539 // C++11 [basic.def.odr]p2: 15540 // A non-overloaded function whose name appears as a potentially-evaluated 15541 // expression or a member of a set of candidate functions, if selected by 15542 // overload resolution when referred to from a potentially-evaluated 15543 // expression, is odr-used, unless it is a pure virtual function and its 15544 // name is not explicitly qualified. 15545 bool MightBeOdrUse = true; 15546 if (E->performsVirtualDispatch(getLangOpts())) { 15547 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15548 if (Method->isPure()) 15549 MightBeOdrUse = false; 15550 } 15551 SourceLocation Loc = 15552 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15553 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15554 } 15555 15556 /// Perform marking for a reference to an arbitrary declaration. It 15557 /// marks the declaration referenced, and performs odr-use checking for 15558 /// functions and variables. This method should not be used when building a 15559 /// normal expression which refers to a variable. 15560 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15561 bool MightBeOdrUse) { 15562 if (MightBeOdrUse) { 15563 if (auto *VD = dyn_cast<VarDecl>(D)) { 15564 MarkVariableReferenced(Loc, VD); 15565 return; 15566 } 15567 } 15568 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15569 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15570 return; 15571 } 15572 D->setReferenced(); 15573 } 15574 15575 namespace { 15576 // Mark all of the declarations used by a type as referenced. 15577 // FIXME: Not fully implemented yet! We need to have a better understanding 15578 // of when we're entering a context we should not recurse into. 15579 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15580 // TreeTransforms rebuilding the type in a new context. Rather than 15581 // duplicating the TreeTransform logic, we should consider reusing it here. 15582 // Currently that causes problems when rebuilding LambdaExprs. 15583 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15584 Sema &S; 15585 SourceLocation Loc; 15586 15587 public: 15588 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15589 15590 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15591 15592 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15593 }; 15594 } 15595 15596 bool MarkReferencedDecls::TraverseTemplateArgument( 15597 const TemplateArgument &Arg) { 15598 { 15599 // A non-type template argument is a constant-evaluated context. 15600 EnterExpressionEvaluationContext Evaluated( 15601 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15602 if (Arg.getKind() == TemplateArgument::Declaration) { 15603 if (Decl *D = Arg.getAsDecl()) 15604 S.MarkAnyDeclReferenced(Loc, D, true); 15605 } else if (Arg.getKind() == TemplateArgument::Expression) { 15606 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15607 } 15608 } 15609 15610 return Inherited::TraverseTemplateArgument(Arg); 15611 } 15612 15613 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15614 MarkReferencedDecls Marker(*this, Loc); 15615 Marker.TraverseType(T); 15616 } 15617 15618 namespace { 15619 /// Helper class that marks all of the declarations referenced by 15620 /// potentially-evaluated subexpressions as "referenced". 15621 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15622 Sema &S; 15623 bool SkipLocalVariables; 15624 15625 public: 15626 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15627 15628 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15629 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15630 15631 void VisitDeclRefExpr(DeclRefExpr *E) { 15632 // If we were asked not to visit local variables, don't. 15633 if (SkipLocalVariables) { 15634 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15635 if (VD->hasLocalStorage()) 15636 return; 15637 } 15638 15639 S.MarkDeclRefReferenced(E); 15640 } 15641 15642 void VisitMemberExpr(MemberExpr *E) { 15643 S.MarkMemberReferenced(E); 15644 Inherited::VisitMemberExpr(E); 15645 } 15646 15647 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15648 S.MarkFunctionReferenced( 15649 E->getBeginLoc(), 15650 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15651 Visit(E->getSubExpr()); 15652 } 15653 15654 void VisitCXXNewExpr(CXXNewExpr *E) { 15655 if (E->getOperatorNew()) 15656 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15657 if (E->getOperatorDelete()) 15658 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15659 Inherited::VisitCXXNewExpr(E); 15660 } 15661 15662 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15663 if (E->getOperatorDelete()) 15664 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15665 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15666 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15667 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15668 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15669 } 15670 15671 Inherited::VisitCXXDeleteExpr(E); 15672 } 15673 15674 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15675 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15676 Inherited::VisitCXXConstructExpr(E); 15677 } 15678 15679 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15680 Visit(E->getExpr()); 15681 } 15682 15683 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15684 Inherited::VisitImplicitCastExpr(E); 15685 15686 if (E->getCastKind() == CK_LValueToRValue) 15687 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15688 } 15689 }; 15690 } 15691 15692 /// Mark any declarations that appear within this expression or any 15693 /// potentially-evaluated subexpressions as "referenced". 15694 /// 15695 /// \param SkipLocalVariables If true, don't mark local variables as 15696 /// 'referenced'. 15697 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15698 bool SkipLocalVariables) { 15699 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15700 } 15701 15702 /// Emit a diagnostic that describes an effect on the run-time behavior 15703 /// of the program being compiled. 15704 /// 15705 /// This routine emits the given diagnostic when the code currently being 15706 /// type-checked is "potentially evaluated", meaning that there is a 15707 /// possibility that the code will actually be executable. Code in sizeof() 15708 /// expressions, code used only during overload resolution, etc., are not 15709 /// potentially evaluated. This routine will suppress such diagnostics or, 15710 /// in the absolutely nutty case of potentially potentially evaluated 15711 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15712 /// later. 15713 /// 15714 /// This routine should be used for all diagnostics that describe the run-time 15715 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15716 /// Failure to do so will likely result in spurious diagnostics or failures 15717 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15718 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15719 const PartialDiagnostic &PD) { 15720 switch (ExprEvalContexts.back().Context) { 15721 case ExpressionEvaluationContext::Unevaluated: 15722 case ExpressionEvaluationContext::UnevaluatedList: 15723 case ExpressionEvaluationContext::UnevaluatedAbstract: 15724 case ExpressionEvaluationContext::DiscardedStatement: 15725 // The argument will never be evaluated, so don't complain. 15726 break; 15727 15728 case ExpressionEvaluationContext::ConstantEvaluated: 15729 // Relevant diagnostics should be produced by constant evaluation. 15730 break; 15731 15732 case ExpressionEvaluationContext::PotentiallyEvaluated: 15733 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15734 if (Statement && getCurFunctionOrMethodDecl()) { 15735 FunctionScopes.back()->PossiblyUnreachableDiags. 15736 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15737 return true; 15738 } 15739 15740 // The initializer of a constexpr variable or of the first declaration of a 15741 // static data member is not syntactically a constant evaluated constant, 15742 // but nonetheless is always required to be a constant expression, so we 15743 // can skip diagnosing. 15744 // FIXME: Using the mangling context here is a hack. 15745 if (auto *VD = dyn_cast_or_null<VarDecl>( 15746 ExprEvalContexts.back().ManglingContextDecl)) { 15747 if (VD->isConstexpr() || 15748 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15749 break; 15750 // FIXME: For any other kind of variable, we should build a CFG for its 15751 // initializer and check whether the context in question is reachable. 15752 } 15753 15754 Diag(Loc, PD); 15755 return true; 15756 } 15757 15758 return false; 15759 } 15760 15761 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15762 CallExpr *CE, FunctionDecl *FD) { 15763 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15764 return false; 15765 15766 // If we're inside a decltype's expression, don't check for a valid return 15767 // type or construct temporaries until we know whether this is the last call. 15768 if (ExprEvalContexts.back().ExprContext == 15769 ExpressionEvaluationContextRecord::EK_Decltype) { 15770 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15771 return false; 15772 } 15773 15774 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15775 FunctionDecl *FD; 15776 CallExpr *CE; 15777 15778 public: 15779 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15780 : FD(FD), CE(CE) { } 15781 15782 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15783 if (!FD) { 15784 S.Diag(Loc, diag::err_call_incomplete_return) 15785 << T << CE->getSourceRange(); 15786 return; 15787 } 15788 15789 S.Diag(Loc, diag::err_call_function_incomplete_return) 15790 << CE->getSourceRange() << FD->getDeclName() << T; 15791 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15792 << FD->getDeclName(); 15793 } 15794 } Diagnoser(FD, CE); 15795 15796 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15797 return true; 15798 15799 return false; 15800 } 15801 15802 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15803 // will prevent this condition from triggering, which is what we want. 15804 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15805 SourceLocation Loc; 15806 15807 unsigned diagnostic = diag::warn_condition_is_assignment; 15808 bool IsOrAssign = false; 15809 15810 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15811 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15812 return; 15813 15814 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15815 15816 // Greylist some idioms by putting them into a warning subcategory. 15817 if (ObjCMessageExpr *ME 15818 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15819 Selector Sel = ME->getSelector(); 15820 15821 // self = [<foo> init...] 15822 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15823 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15824 15825 // <foo> = [<bar> nextObject] 15826 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15827 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15828 } 15829 15830 Loc = Op->getOperatorLoc(); 15831 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15832 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15833 return; 15834 15835 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15836 Loc = Op->getOperatorLoc(); 15837 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15838 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15839 else { 15840 // Not an assignment. 15841 return; 15842 } 15843 15844 Diag(Loc, diagnostic) << E->getSourceRange(); 15845 15846 SourceLocation Open = E->getBeginLoc(); 15847 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15848 Diag(Loc, diag::note_condition_assign_silence) 15849 << FixItHint::CreateInsertion(Open, "(") 15850 << FixItHint::CreateInsertion(Close, ")"); 15851 15852 if (IsOrAssign) 15853 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15854 << FixItHint::CreateReplacement(Loc, "!="); 15855 else 15856 Diag(Loc, diag::note_condition_assign_to_comparison) 15857 << FixItHint::CreateReplacement(Loc, "=="); 15858 } 15859 15860 /// Redundant parentheses over an equality comparison can indicate 15861 /// that the user intended an assignment used as condition. 15862 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15863 // Don't warn if the parens came from a macro. 15864 SourceLocation parenLoc = ParenE->getBeginLoc(); 15865 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15866 return; 15867 // Don't warn for dependent expressions. 15868 if (ParenE->isTypeDependent()) 15869 return; 15870 15871 Expr *E = ParenE->IgnoreParens(); 15872 15873 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15874 if (opE->getOpcode() == BO_EQ && 15875 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15876 == Expr::MLV_Valid) { 15877 SourceLocation Loc = opE->getOperatorLoc(); 15878 15879 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15880 SourceRange ParenERange = ParenE->getSourceRange(); 15881 Diag(Loc, diag::note_equality_comparison_silence) 15882 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15883 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15884 Diag(Loc, diag::note_equality_comparison_to_assign) 15885 << FixItHint::CreateReplacement(Loc, "="); 15886 } 15887 } 15888 15889 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15890 bool IsConstexpr) { 15891 DiagnoseAssignmentAsCondition(E); 15892 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15893 DiagnoseEqualityWithExtraParens(parenE); 15894 15895 ExprResult result = CheckPlaceholderExpr(E); 15896 if (result.isInvalid()) return ExprError(); 15897 E = result.get(); 15898 15899 if (!E->isTypeDependent()) { 15900 if (getLangOpts().CPlusPlus) 15901 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15902 15903 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15904 if (ERes.isInvalid()) 15905 return ExprError(); 15906 E = ERes.get(); 15907 15908 QualType T = E->getType(); 15909 if (!T->isScalarType()) { // C99 6.8.4.1p1 15910 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15911 << T << E->getSourceRange(); 15912 return ExprError(); 15913 } 15914 CheckBoolLikeConversion(E, Loc); 15915 } 15916 15917 return E; 15918 } 15919 15920 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15921 Expr *SubExpr, ConditionKind CK) { 15922 // Empty conditions are valid in for-statements. 15923 if (!SubExpr) 15924 return ConditionResult(); 15925 15926 ExprResult Cond; 15927 switch (CK) { 15928 case ConditionKind::Boolean: 15929 Cond = CheckBooleanCondition(Loc, SubExpr); 15930 break; 15931 15932 case ConditionKind::ConstexprIf: 15933 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15934 break; 15935 15936 case ConditionKind::Switch: 15937 Cond = CheckSwitchCondition(Loc, SubExpr); 15938 break; 15939 } 15940 if (Cond.isInvalid()) 15941 return ConditionError(); 15942 15943 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15944 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15945 if (!FullExpr.get()) 15946 return ConditionError(); 15947 15948 return ConditionResult(*this, nullptr, FullExpr, 15949 CK == ConditionKind::ConstexprIf); 15950 } 15951 15952 namespace { 15953 /// A visitor for rebuilding a call to an __unknown_any expression 15954 /// to have an appropriate type. 15955 struct RebuildUnknownAnyFunction 15956 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15957 15958 Sema &S; 15959 15960 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15961 15962 ExprResult VisitStmt(Stmt *S) { 15963 llvm_unreachable("unexpected statement!"); 15964 } 15965 15966 ExprResult VisitExpr(Expr *E) { 15967 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15968 << E->getSourceRange(); 15969 return ExprError(); 15970 } 15971 15972 /// Rebuild an expression which simply semantically wraps another 15973 /// expression which it shares the type and value kind of. 15974 template <class T> ExprResult rebuildSugarExpr(T *E) { 15975 ExprResult SubResult = Visit(E->getSubExpr()); 15976 if (SubResult.isInvalid()) return ExprError(); 15977 15978 Expr *SubExpr = SubResult.get(); 15979 E->setSubExpr(SubExpr); 15980 E->setType(SubExpr->getType()); 15981 E->setValueKind(SubExpr->getValueKind()); 15982 assert(E->getObjectKind() == OK_Ordinary); 15983 return E; 15984 } 15985 15986 ExprResult VisitParenExpr(ParenExpr *E) { 15987 return rebuildSugarExpr(E); 15988 } 15989 15990 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15991 return rebuildSugarExpr(E); 15992 } 15993 15994 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15995 ExprResult SubResult = Visit(E->getSubExpr()); 15996 if (SubResult.isInvalid()) return ExprError(); 15997 15998 Expr *SubExpr = SubResult.get(); 15999 E->setSubExpr(SubExpr); 16000 E->setType(S.Context.getPointerType(SubExpr->getType())); 16001 assert(E->getValueKind() == VK_RValue); 16002 assert(E->getObjectKind() == OK_Ordinary); 16003 return E; 16004 } 16005 16006 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 16007 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 16008 16009 E->setType(VD->getType()); 16010 16011 assert(E->getValueKind() == VK_RValue); 16012 if (S.getLangOpts().CPlusPlus && 16013 !(isa<CXXMethodDecl>(VD) && 16014 cast<CXXMethodDecl>(VD)->isInstance())) 16015 E->setValueKind(VK_LValue); 16016 16017 return E; 16018 } 16019 16020 ExprResult VisitMemberExpr(MemberExpr *E) { 16021 return resolveDecl(E, E->getMemberDecl()); 16022 } 16023 16024 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16025 return resolveDecl(E, E->getDecl()); 16026 } 16027 }; 16028 } 16029 16030 /// Given a function expression of unknown-any type, try to rebuild it 16031 /// to have a function type. 16032 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 16033 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16034 if (Result.isInvalid()) return ExprError(); 16035 return S.DefaultFunctionArrayConversion(Result.get()); 16036 } 16037 16038 namespace { 16039 /// A visitor for rebuilding an expression of type __unknown_anytype 16040 /// into one which resolves the type directly on the referring 16041 /// expression. Strict preservation of the original source 16042 /// structure is not a goal. 16043 struct RebuildUnknownAnyExpr 16044 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16045 16046 Sema &S; 16047 16048 /// The current destination type. 16049 QualType DestType; 16050 16051 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16052 : S(S), DestType(CastType) {} 16053 16054 ExprResult VisitStmt(Stmt *S) { 16055 llvm_unreachable("unexpected statement!"); 16056 } 16057 16058 ExprResult VisitExpr(Expr *E) { 16059 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16060 << E->getSourceRange(); 16061 return ExprError(); 16062 } 16063 16064 ExprResult VisitCallExpr(CallExpr *E); 16065 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16066 16067 /// Rebuild an expression which simply semantically wraps another 16068 /// expression which it shares the type and value kind of. 16069 template <class T> ExprResult rebuildSugarExpr(T *E) { 16070 ExprResult SubResult = Visit(E->getSubExpr()); 16071 if (SubResult.isInvalid()) return ExprError(); 16072 Expr *SubExpr = SubResult.get(); 16073 E->setSubExpr(SubExpr); 16074 E->setType(SubExpr->getType()); 16075 E->setValueKind(SubExpr->getValueKind()); 16076 assert(E->getObjectKind() == OK_Ordinary); 16077 return E; 16078 } 16079 16080 ExprResult VisitParenExpr(ParenExpr *E) { 16081 return rebuildSugarExpr(E); 16082 } 16083 16084 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16085 return rebuildSugarExpr(E); 16086 } 16087 16088 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16089 const PointerType *Ptr = DestType->getAs<PointerType>(); 16090 if (!Ptr) { 16091 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16092 << E->getSourceRange(); 16093 return ExprError(); 16094 } 16095 16096 if (isa<CallExpr>(E->getSubExpr())) { 16097 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16098 << E->getSourceRange(); 16099 return ExprError(); 16100 } 16101 16102 assert(E->getValueKind() == VK_RValue); 16103 assert(E->getObjectKind() == OK_Ordinary); 16104 E->setType(DestType); 16105 16106 // Build the sub-expression as if it were an object of the pointee type. 16107 DestType = Ptr->getPointeeType(); 16108 ExprResult SubResult = Visit(E->getSubExpr()); 16109 if (SubResult.isInvalid()) return ExprError(); 16110 E->setSubExpr(SubResult.get()); 16111 return E; 16112 } 16113 16114 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16115 16116 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16117 16118 ExprResult VisitMemberExpr(MemberExpr *E) { 16119 return resolveDecl(E, E->getMemberDecl()); 16120 } 16121 16122 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16123 return resolveDecl(E, E->getDecl()); 16124 } 16125 }; 16126 } 16127 16128 /// Rebuilds a call expression which yielded __unknown_anytype. 16129 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16130 Expr *CalleeExpr = E->getCallee(); 16131 16132 enum FnKind { 16133 FK_MemberFunction, 16134 FK_FunctionPointer, 16135 FK_BlockPointer 16136 }; 16137 16138 FnKind Kind; 16139 QualType CalleeType = CalleeExpr->getType(); 16140 if (CalleeType == S.Context.BoundMemberTy) { 16141 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16142 Kind = FK_MemberFunction; 16143 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16144 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16145 CalleeType = Ptr->getPointeeType(); 16146 Kind = FK_FunctionPointer; 16147 } else { 16148 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16149 Kind = FK_BlockPointer; 16150 } 16151 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16152 16153 // Verify that this is a legal result type of a function. 16154 if (DestType->isArrayType() || DestType->isFunctionType()) { 16155 unsigned diagID = diag::err_func_returning_array_function; 16156 if (Kind == FK_BlockPointer) 16157 diagID = diag::err_block_returning_array_function; 16158 16159 S.Diag(E->getExprLoc(), diagID) 16160 << DestType->isFunctionType() << DestType; 16161 return ExprError(); 16162 } 16163 16164 // Otherwise, go ahead and set DestType as the call's result. 16165 E->setType(DestType.getNonLValueExprType(S.Context)); 16166 E->setValueKind(Expr::getValueKindForType(DestType)); 16167 assert(E->getObjectKind() == OK_Ordinary); 16168 16169 // Rebuild the function type, replacing the result type with DestType. 16170 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16171 if (Proto) { 16172 // __unknown_anytype(...) is a special case used by the debugger when 16173 // it has no idea what a function's signature is. 16174 // 16175 // We want to build this call essentially under the K&R 16176 // unprototyped rules, but making a FunctionNoProtoType in C++ 16177 // would foul up all sorts of assumptions. However, we cannot 16178 // simply pass all arguments as variadic arguments, nor can we 16179 // portably just call the function under a non-variadic type; see 16180 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16181 // However, it turns out that in practice it is generally safe to 16182 // call a function declared as "A foo(B,C,D);" under the prototype 16183 // "A foo(B,C,D,...);". The only known exception is with the 16184 // Windows ABI, where any variadic function is implicitly cdecl 16185 // regardless of its normal CC. Therefore we change the parameter 16186 // types to match the types of the arguments. 16187 // 16188 // This is a hack, but it is far superior to moving the 16189 // corresponding target-specific code from IR-gen to Sema/AST. 16190 16191 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16192 SmallVector<QualType, 8> ArgTypes; 16193 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16194 ArgTypes.reserve(E->getNumArgs()); 16195 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16196 Expr *Arg = E->getArg(i); 16197 QualType ArgType = Arg->getType(); 16198 if (E->isLValue()) { 16199 ArgType = S.Context.getLValueReferenceType(ArgType); 16200 } else if (E->isXValue()) { 16201 ArgType = S.Context.getRValueReferenceType(ArgType); 16202 } 16203 ArgTypes.push_back(ArgType); 16204 } 16205 ParamTypes = ArgTypes; 16206 } 16207 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16208 Proto->getExtProtoInfo()); 16209 } else { 16210 DestType = S.Context.getFunctionNoProtoType(DestType, 16211 FnType->getExtInfo()); 16212 } 16213 16214 // Rebuild the appropriate pointer-to-function type. 16215 switch (Kind) { 16216 case FK_MemberFunction: 16217 // Nothing to do. 16218 break; 16219 16220 case FK_FunctionPointer: 16221 DestType = S.Context.getPointerType(DestType); 16222 break; 16223 16224 case FK_BlockPointer: 16225 DestType = S.Context.getBlockPointerType(DestType); 16226 break; 16227 } 16228 16229 // Finally, we can recurse. 16230 ExprResult CalleeResult = Visit(CalleeExpr); 16231 if (!CalleeResult.isUsable()) return ExprError(); 16232 E->setCallee(CalleeResult.get()); 16233 16234 // Bind a temporary if necessary. 16235 return S.MaybeBindToTemporary(E); 16236 } 16237 16238 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16239 // Verify that this is a legal result type of a call. 16240 if (DestType->isArrayType() || DestType->isFunctionType()) { 16241 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16242 << DestType->isFunctionType() << DestType; 16243 return ExprError(); 16244 } 16245 16246 // Rewrite the method result type if available. 16247 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16248 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16249 Method->setReturnType(DestType); 16250 } 16251 16252 // Change the type of the message. 16253 E->setType(DestType.getNonReferenceType()); 16254 E->setValueKind(Expr::getValueKindForType(DestType)); 16255 16256 return S.MaybeBindToTemporary(E); 16257 } 16258 16259 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16260 // The only case we should ever see here is a function-to-pointer decay. 16261 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16262 assert(E->getValueKind() == VK_RValue); 16263 assert(E->getObjectKind() == OK_Ordinary); 16264 16265 E->setType(DestType); 16266 16267 // Rebuild the sub-expression as the pointee (function) type. 16268 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16269 16270 ExprResult Result = Visit(E->getSubExpr()); 16271 if (!Result.isUsable()) return ExprError(); 16272 16273 E->setSubExpr(Result.get()); 16274 return E; 16275 } else if (E->getCastKind() == CK_LValueToRValue) { 16276 assert(E->getValueKind() == VK_RValue); 16277 assert(E->getObjectKind() == OK_Ordinary); 16278 16279 assert(isa<BlockPointerType>(E->getType())); 16280 16281 E->setType(DestType); 16282 16283 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16284 DestType = S.Context.getLValueReferenceType(DestType); 16285 16286 ExprResult Result = Visit(E->getSubExpr()); 16287 if (!Result.isUsable()) return ExprError(); 16288 16289 E->setSubExpr(Result.get()); 16290 return E; 16291 } else { 16292 llvm_unreachable("Unhandled cast type!"); 16293 } 16294 } 16295 16296 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16297 ExprValueKind ValueKind = VK_LValue; 16298 QualType Type = DestType; 16299 16300 // We know how to make this work for certain kinds of decls: 16301 16302 // - functions 16303 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16304 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16305 DestType = Ptr->getPointeeType(); 16306 ExprResult Result = resolveDecl(E, VD); 16307 if (Result.isInvalid()) return ExprError(); 16308 return S.ImpCastExprToType(Result.get(), Type, 16309 CK_FunctionToPointerDecay, VK_RValue); 16310 } 16311 16312 if (!Type->isFunctionType()) { 16313 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16314 << VD << E->getSourceRange(); 16315 return ExprError(); 16316 } 16317 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16318 // We must match the FunctionDecl's type to the hack introduced in 16319 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16320 // type. See the lengthy commentary in that routine. 16321 QualType FDT = FD->getType(); 16322 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16323 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16324 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16325 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16326 SourceLocation Loc = FD->getLocation(); 16327 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16328 FD->getDeclContext(), 16329 Loc, Loc, FD->getNameInfo().getName(), 16330 DestType, FD->getTypeSourceInfo(), 16331 SC_None, false/*isInlineSpecified*/, 16332 FD->hasPrototype(), 16333 false/*isConstexprSpecified*/); 16334 16335 if (FD->getQualifier()) 16336 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16337 16338 SmallVector<ParmVarDecl*, 16> Params; 16339 for (const auto &AI : FT->param_types()) { 16340 ParmVarDecl *Param = 16341 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16342 Param->setScopeInfo(0, Params.size()); 16343 Params.push_back(Param); 16344 } 16345 NewFD->setParams(Params); 16346 DRE->setDecl(NewFD); 16347 VD = DRE->getDecl(); 16348 } 16349 } 16350 16351 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16352 if (MD->isInstance()) { 16353 ValueKind = VK_RValue; 16354 Type = S.Context.BoundMemberTy; 16355 } 16356 16357 // Function references aren't l-values in C. 16358 if (!S.getLangOpts().CPlusPlus) 16359 ValueKind = VK_RValue; 16360 16361 // - variables 16362 } else if (isa<VarDecl>(VD)) { 16363 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16364 Type = RefTy->getPointeeType(); 16365 } else if (Type->isFunctionType()) { 16366 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16367 << VD << E->getSourceRange(); 16368 return ExprError(); 16369 } 16370 16371 // - nothing else 16372 } else { 16373 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16374 << VD << E->getSourceRange(); 16375 return ExprError(); 16376 } 16377 16378 // Modifying the declaration like this is friendly to IR-gen but 16379 // also really dangerous. 16380 VD->setType(DestType); 16381 E->setType(Type); 16382 E->setValueKind(ValueKind); 16383 return E; 16384 } 16385 16386 /// Check a cast of an unknown-any type. We intentionally only 16387 /// trigger this for C-style casts. 16388 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16389 Expr *CastExpr, CastKind &CastKind, 16390 ExprValueKind &VK, CXXCastPath &Path) { 16391 // The type we're casting to must be either void or complete. 16392 if (!CastType->isVoidType() && 16393 RequireCompleteType(TypeRange.getBegin(), CastType, 16394 diag::err_typecheck_cast_to_incomplete)) 16395 return ExprError(); 16396 16397 // Rewrite the casted expression from scratch. 16398 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16399 if (!result.isUsable()) return ExprError(); 16400 16401 CastExpr = result.get(); 16402 VK = CastExpr->getValueKind(); 16403 CastKind = CK_NoOp; 16404 16405 return CastExpr; 16406 } 16407 16408 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16409 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16410 } 16411 16412 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16413 Expr *arg, QualType ¶mType) { 16414 // If the syntactic form of the argument is not an explicit cast of 16415 // any sort, just do default argument promotion. 16416 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16417 if (!castArg) { 16418 ExprResult result = DefaultArgumentPromotion(arg); 16419 if (result.isInvalid()) return ExprError(); 16420 paramType = result.get()->getType(); 16421 return result; 16422 } 16423 16424 // Otherwise, use the type that was written in the explicit cast. 16425 assert(!arg->hasPlaceholderType()); 16426 paramType = castArg->getTypeAsWritten(); 16427 16428 // Copy-initialize a parameter of that type. 16429 InitializedEntity entity = 16430 InitializedEntity::InitializeParameter(Context, paramType, 16431 /*consumed*/ false); 16432 return PerformCopyInitialization(entity, callLoc, arg); 16433 } 16434 16435 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16436 Expr *orig = E; 16437 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16438 while (true) { 16439 E = E->IgnoreParenImpCasts(); 16440 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16441 E = call->getCallee(); 16442 diagID = diag::err_uncasted_call_of_unknown_any; 16443 } else { 16444 break; 16445 } 16446 } 16447 16448 SourceLocation loc; 16449 NamedDecl *d; 16450 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16451 loc = ref->getLocation(); 16452 d = ref->getDecl(); 16453 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16454 loc = mem->getMemberLoc(); 16455 d = mem->getMemberDecl(); 16456 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16457 diagID = diag::err_uncasted_call_of_unknown_any; 16458 loc = msg->getSelectorStartLoc(); 16459 d = msg->getMethodDecl(); 16460 if (!d) { 16461 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16462 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16463 << orig->getSourceRange(); 16464 return ExprError(); 16465 } 16466 } else { 16467 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16468 << E->getSourceRange(); 16469 return ExprError(); 16470 } 16471 16472 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16473 16474 // Never recoverable. 16475 return ExprError(); 16476 } 16477 16478 /// Check for operands with placeholder types and complain if found. 16479 /// Returns ExprError() if there was an error and no recovery was possible. 16480 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16481 if (!getLangOpts().CPlusPlus) { 16482 // C cannot handle TypoExpr nodes on either side of a binop because it 16483 // doesn't handle dependent types properly, so make sure any TypoExprs have 16484 // been dealt with before checking the operands. 16485 ExprResult Result = CorrectDelayedTyposInExpr(E); 16486 if (!Result.isUsable()) return ExprError(); 16487 E = Result.get(); 16488 } 16489 16490 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16491 if (!placeholderType) return E; 16492 16493 switch (placeholderType->getKind()) { 16494 16495 // Overloaded expressions. 16496 case BuiltinType::Overload: { 16497 // Try to resolve a single function template specialization. 16498 // This is obligatory. 16499 ExprResult Result = E; 16500 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16501 return Result; 16502 16503 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16504 // leaves Result unchanged on failure. 16505 Result = E; 16506 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16507 return Result; 16508 16509 // If that failed, try to recover with a call. 16510 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16511 /*complain*/ true); 16512 return Result; 16513 } 16514 16515 // Bound member functions. 16516 case BuiltinType::BoundMember: { 16517 ExprResult result = E; 16518 const Expr *BME = E->IgnoreParens(); 16519 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16520 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16521 if (isa<CXXPseudoDestructorExpr>(BME)) { 16522 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16523 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16524 if (ME->getMemberNameInfo().getName().getNameKind() == 16525 DeclarationName::CXXDestructorName) 16526 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16527 } 16528 tryToRecoverWithCall(result, PD, 16529 /*complain*/ true); 16530 return result; 16531 } 16532 16533 // ARC unbridged casts. 16534 case BuiltinType::ARCUnbridgedCast: { 16535 Expr *realCast = stripARCUnbridgedCast(E); 16536 diagnoseARCUnbridgedCast(realCast); 16537 return realCast; 16538 } 16539 16540 // Expressions of unknown type. 16541 case BuiltinType::UnknownAny: 16542 return diagnoseUnknownAnyExpr(*this, E); 16543 16544 // Pseudo-objects. 16545 case BuiltinType::PseudoObject: 16546 return checkPseudoObjectRValue(E); 16547 16548 case BuiltinType::BuiltinFn: { 16549 // Accept __noop without parens by implicitly converting it to a call expr. 16550 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16551 if (DRE) { 16552 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16553 if (FD->getBuiltinID() == Builtin::BI__noop) { 16554 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16555 CK_BuiltinFnToFnPtr).get(); 16556 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16557 VK_RValue, SourceLocation()); 16558 } 16559 } 16560 16561 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16562 return ExprError(); 16563 } 16564 16565 // Expressions of unknown type. 16566 case BuiltinType::OMPArraySection: 16567 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16568 return ExprError(); 16569 16570 // Everything else should be impossible. 16571 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16572 case BuiltinType::Id: 16573 #include "clang/Basic/OpenCLImageTypes.def" 16574 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 16575 case BuiltinType::Id: 16576 #include "clang/Basic/OpenCLExtensionTypes.def" 16577 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16578 #define PLACEHOLDER_TYPE(Id, SingletonId) 16579 #include "clang/AST/BuiltinTypes.def" 16580 break; 16581 } 16582 16583 llvm_unreachable("invalid placeholder type!"); 16584 } 16585 16586 bool Sema::CheckCaseExpression(Expr *E) { 16587 if (E->isTypeDependent()) 16588 return true; 16589 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16590 return E->getType()->isIntegralOrEnumerationType(); 16591 return false; 16592 } 16593 16594 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16595 ExprResult 16596 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16597 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16598 "Unknown Objective-C Boolean value!"); 16599 QualType BoolT = Context.ObjCBuiltinBoolTy; 16600 if (!Context.getBOOLDecl()) { 16601 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16602 Sema::LookupOrdinaryName); 16603 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16604 NamedDecl *ND = Result.getFoundDecl(); 16605 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16606 Context.setBOOLDecl(TD); 16607 } 16608 } 16609 if (Context.getBOOLDecl()) 16610 BoolT = Context.getBOOLType(); 16611 return new (Context) 16612 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16613 } 16614 16615 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16616 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16617 SourceLocation RParen) { 16618 16619 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16620 16621 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16622 [&](const AvailabilitySpec &Spec) { 16623 return Spec.getPlatform() == Platform; 16624 }); 16625 16626 VersionTuple Version; 16627 if (Spec != AvailSpecs.end()) 16628 Version = Spec->getVersion(); 16629 16630 // The use of `@available` in the enclosing function should be analyzed to 16631 // warn when it's used inappropriately (i.e. not if(@available)). 16632 if (getCurFunctionOrMethodDecl()) 16633 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16634 else if (getCurBlock() || getCurLambda()) 16635 getCurFunction()->HasPotentialAvailabilityViolations = true; 16636 16637 return new (Context) 16638 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16639 } 16640