1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 83 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 84 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 85 if (DC && !DC->hasAttr<UnusedAttr>()) 86 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 87 } 88 } 89 } 90 91 /// \brief Emit a note explaining that this function is deleted. 92 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 93 assert(Decl->isDeleted()); 94 95 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 96 97 if (Method && Method->isDeleted() && Method->isDefaulted()) { 98 // If the method was explicitly defaulted, point at that declaration. 99 if (!Method->isImplicit()) 100 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 101 102 // Try to diagnose why this special member function was implicitly 103 // deleted. This might fail, if that reason no longer applies. 104 CXXSpecialMember CSM = getSpecialMember(Method); 105 if (CSM != CXXInvalid) 106 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 107 108 return; 109 } 110 111 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 112 if (Ctor && Ctor->isInheritingConstructor()) 113 return NoteDeletedInheritingConstructor(Ctor); 114 115 Diag(Decl->getLocation(), diag::note_availability_specified_here) 116 << Decl << true; 117 } 118 119 /// \brief Determine whether a FunctionDecl was ever declared with an 120 /// explicit storage class. 121 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 122 for (auto I : D->redecls()) { 123 if (I->getStorageClass() != SC_None) 124 return true; 125 } 126 return false; 127 } 128 129 /// \brief Check whether we're in an extern inline function and referring to a 130 /// variable or function with internal linkage (C11 6.7.4p3). 131 /// 132 /// This is only a warning because we used to silently accept this code, but 133 /// in many cases it will not behave correctly. This is not enabled in C++ mode 134 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 135 /// and so while there may still be user mistakes, most of the time we can't 136 /// prove that there are errors. 137 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 138 const NamedDecl *D, 139 SourceLocation Loc) { 140 // This is disabled under C++; there are too many ways for this to fire in 141 // contexts where the warning is a false positive, or where it is technically 142 // correct but benign. 143 if (S.getLangOpts().CPlusPlus) 144 return; 145 146 // Check if this is an inlined function or method. 147 FunctionDecl *Current = S.getCurFunctionDecl(); 148 if (!Current) 149 return; 150 if (!Current->isInlined()) 151 return; 152 if (!Current->isExternallyVisible()) 153 return; 154 155 // Check if the decl has internal linkage. 156 if (D->getFormalLinkage() != InternalLinkage) 157 return; 158 159 // Downgrade from ExtWarn to Extension if 160 // (1) the supposedly external inline function is in the main file, 161 // and probably won't be included anywhere else. 162 // (2) the thing we're referencing is a pure function. 163 // (3) the thing we're referencing is another inline function. 164 // This last can give us false negatives, but it's better than warning on 165 // wrappers for simple C library functions. 166 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 167 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 168 if (!DowngradeWarning && UsedFn) 169 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 170 171 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 172 : diag::ext_internal_in_extern_inline) 173 << /*IsVar=*/!UsedFn << D; 174 175 S.MaybeSuggestAddingStaticToDecl(Current); 176 177 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 178 << D; 179 } 180 181 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 182 const FunctionDecl *First = Cur->getFirstDecl(); 183 184 // Suggest "static" on the function, if possible. 185 if (!hasAnyExplicitStorageClass(First)) { 186 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 187 Diag(DeclBegin, diag::note_convert_inline_to_static) 188 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 189 } 190 } 191 192 /// \brief Determine whether the use of this declaration is valid, and 193 /// emit any corresponding diagnostics. 194 /// 195 /// This routine diagnoses various problems with referencing 196 /// declarations that can occur when using a declaration. For example, 197 /// it might warn if a deprecated or unavailable declaration is being 198 /// used, or produce an error (and return true) if a C++0x deleted 199 /// function is being used. 200 /// 201 /// \returns true if there was an error (this declaration cannot be 202 /// referenced), false otherwise. 203 /// 204 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 205 const ObjCInterfaceDecl *UnknownObjCClass, 206 bool ObjCPropertyAccess, 207 bool AvoidPartialAvailabilityChecks) { 208 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 209 // If there were any diagnostics suppressed by template argument deduction, 210 // emit them now. 211 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 212 if (Pos != SuppressedDiagnostics.end()) { 213 for (const PartialDiagnosticAt &Suppressed : Pos->second) 214 Diag(Suppressed.first, Suppressed.second); 215 216 // Clear out the list of suppressed diagnostics, so that we don't emit 217 // them again for this specialization. However, we don't obsolete this 218 // entry from the table, because we want to avoid ever emitting these 219 // diagnostics again. 220 Pos->second.clear(); 221 } 222 223 // C++ [basic.start.main]p3: 224 // The function 'main' shall not be used within a program. 225 if (cast<FunctionDecl>(D)->isMain()) 226 Diag(Loc, diag::ext_main_used); 227 } 228 229 // See if this is an auto-typed variable whose initializer we are parsing. 230 if (ParsingInitForAutoVars.count(D)) { 231 if (isa<BindingDecl>(D)) { 232 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 233 << D->getDeclName(); 234 } else { 235 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 236 << D->getDeclName() << cast<VarDecl>(D)->getType(); 237 } 238 return true; 239 } 240 241 // See if this is a deleted function. 242 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 243 if (FD->isDeleted()) { 244 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 245 if (Ctor && Ctor->isInheritingConstructor()) 246 Diag(Loc, diag::err_deleted_inherited_ctor_use) 247 << Ctor->getParent() 248 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 249 else 250 Diag(Loc, diag::err_deleted_function_use); 251 NoteDeletedFunction(FD); 252 return true; 253 } 254 255 // If the function has a deduced return type, and we can't deduce it, 256 // then we can't use it either. 257 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 258 DeduceReturnType(FD, Loc)) 259 return true; 260 261 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 262 return true; 263 } 264 265 auto getReferencedObjCProp = [](const NamedDecl *D) -> 266 const ObjCPropertyDecl * { 267 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 268 return MD->findPropertyDecl(); 269 return nullptr; 270 }; 271 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 272 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 273 return true; 274 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 275 return true; 276 } 277 278 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 279 // Only the variables omp_in and omp_out are allowed in the combiner. 280 // Only the variables omp_priv and omp_orig are allowed in the 281 // initializer-clause. 282 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 283 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 284 isa<VarDecl>(D)) { 285 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 286 << getCurFunction()->HasOMPDeclareReductionCombiner; 287 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 288 return true; 289 } 290 291 DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess, 292 AvoidPartialAvailabilityChecks); 293 294 DiagnoseUnusedOfDecl(*this, D, Loc); 295 296 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 297 298 return false; 299 } 300 301 /// \brief Retrieve the message suffix that should be added to a 302 /// diagnostic complaining about the given function being deleted or 303 /// unavailable. 304 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 305 std::string Message; 306 if (FD->getAvailability(&Message)) 307 return ": " + Message; 308 309 return std::string(); 310 } 311 312 /// DiagnoseSentinelCalls - This routine checks whether a call or 313 /// message-send is to a declaration with the sentinel attribute, and 314 /// if so, it checks that the requirements of the sentinel are 315 /// satisfied. 316 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 317 ArrayRef<Expr *> Args) { 318 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 319 if (!attr) 320 return; 321 322 // The number of formal parameters of the declaration. 323 unsigned numFormalParams; 324 325 // The kind of declaration. This is also an index into a %select in 326 // the diagnostic. 327 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 328 329 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 330 numFormalParams = MD->param_size(); 331 calleeType = CT_Method; 332 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 333 numFormalParams = FD->param_size(); 334 calleeType = CT_Function; 335 } else if (isa<VarDecl>(D)) { 336 QualType type = cast<ValueDecl>(D)->getType(); 337 const FunctionType *fn = nullptr; 338 if (const PointerType *ptr = type->getAs<PointerType>()) { 339 fn = ptr->getPointeeType()->getAs<FunctionType>(); 340 if (!fn) return; 341 calleeType = CT_Function; 342 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 343 fn = ptr->getPointeeType()->castAs<FunctionType>(); 344 calleeType = CT_Block; 345 } else { 346 return; 347 } 348 349 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 350 numFormalParams = proto->getNumParams(); 351 } else { 352 numFormalParams = 0; 353 } 354 } else { 355 return; 356 } 357 358 // "nullPos" is the number of formal parameters at the end which 359 // effectively count as part of the variadic arguments. This is 360 // useful if you would prefer to not have *any* formal parameters, 361 // but the language forces you to have at least one. 362 unsigned nullPos = attr->getNullPos(); 363 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 364 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 365 366 // The number of arguments which should follow the sentinel. 367 unsigned numArgsAfterSentinel = attr->getSentinel(); 368 369 // If there aren't enough arguments for all the formal parameters, 370 // the sentinel, and the args after the sentinel, complain. 371 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 372 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 373 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 374 return; 375 } 376 377 // Otherwise, find the sentinel expression. 378 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 379 if (!sentinelExpr) return; 380 if (sentinelExpr->isValueDependent()) return; 381 if (Context.isSentinelNullExpr(sentinelExpr)) return; 382 383 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 384 // or 'NULL' if those are actually defined in the context. Only use 385 // 'nil' for ObjC methods, where it's much more likely that the 386 // variadic arguments form a list of object pointers. 387 SourceLocation MissingNilLoc 388 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 389 std::string NullValue; 390 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 391 NullValue = "nil"; 392 else if (getLangOpts().CPlusPlus11) 393 NullValue = "nullptr"; 394 else if (PP.isMacroDefined("NULL")) 395 NullValue = "NULL"; 396 else 397 NullValue = "(void*) 0"; 398 399 if (MissingNilLoc.isInvalid()) 400 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 401 else 402 Diag(MissingNilLoc, diag::warn_missing_sentinel) 403 << int(calleeType) 404 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 405 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 406 } 407 408 SourceRange Sema::getExprRange(Expr *E) const { 409 return E ? E->getSourceRange() : SourceRange(); 410 } 411 412 //===----------------------------------------------------------------------===// 413 // Standard Promotions and Conversions 414 //===----------------------------------------------------------------------===// 415 416 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 417 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 418 // Handle any placeholder expressions which made it here. 419 if (E->getType()->isPlaceholderType()) { 420 ExprResult result = CheckPlaceholderExpr(E); 421 if (result.isInvalid()) return ExprError(); 422 E = result.get(); 423 } 424 425 QualType Ty = E->getType(); 426 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 427 428 if (Ty->isFunctionType()) { 429 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 430 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 431 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 432 return ExprError(); 433 434 E = ImpCastExprToType(E, Context.getPointerType(Ty), 435 CK_FunctionToPointerDecay).get(); 436 } else if (Ty->isArrayType()) { 437 // In C90 mode, arrays only promote to pointers if the array expression is 438 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 439 // type 'array of type' is converted to an expression that has type 'pointer 440 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 441 // that has type 'array of type' ...". The relevant change is "an lvalue" 442 // (C90) to "an expression" (C99). 443 // 444 // C++ 4.2p1: 445 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 446 // T" can be converted to an rvalue of type "pointer to T". 447 // 448 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 449 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 450 CK_ArrayToPointerDecay).get(); 451 } 452 return E; 453 } 454 455 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 456 // Check to see if we are dereferencing a null pointer. If so, 457 // and if not volatile-qualified, this is undefined behavior that the 458 // optimizer will delete, so warn about it. People sometimes try to use this 459 // to get a deterministic trap and are surprised by clang's behavior. This 460 // only handles the pattern "*null", which is a very syntactic check. 461 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 462 if (UO->getOpcode() == UO_Deref && 463 UO->getSubExpr()->IgnoreParenCasts()-> 464 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 465 !UO->getType().isVolatileQualified()) { 466 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 467 S.PDiag(diag::warn_indirection_through_null) 468 << UO->getSubExpr()->getSourceRange()); 469 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 470 S.PDiag(diag::note_indirection_through_null)); 471 } 472 } 473 474 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 475 SourceLocation AssignLoc, 476 const Expr* RHS) { 477 const ObjCIvarDecl *IV = OIRE->getDecl(); 478 if (!IV) 479 return; 480 481 DeclarationName MemberName = IV->getDeclName(); 482 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 483 if (!Member || !Member->isStr("isa")) 484 return; 485 486 const Expr *Base = OIRE->getBase(); 487 QualType BaseType = Base->getType(); 488 if (OIRE->isArrow()) 489 BaseType = BaseType->getPointeeType(); 490 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 491 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 492 ObjCInterfaceDecl *ClassDeclared = nullptr; 493 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 494 if (!ClassDeclared->getSuperClass() 495 && (*ClassDeclared->ivar_begin()) == IV) { 496 if (RHS) { 497 NamedDecl *ObjectSetClass = 498 S.LookupSingleName(S.TUScope, 499 &S.Context.Idents.get("object_setClass"), 500 SourceLocation(), S.LookupOrdinaryName); 501 if (ObjectSetClass) { 502 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 503 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 504 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 505 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 506 AssignLoc), ",") << 507 FixItHint::CreateInsertion(RHSLocEnd, ")"); 508 } 509 else 510 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 511 } else { 512 NamedDecl *ObjectGetClass = 513 S.LookupSingleName(S.TUScope, 514 &S.Context.Idents.get("object_getClass"), 515 SourceLocation(), S.LookupOrdinaryName); 516 if (ObjectGetClass) 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 518 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 519 FixItHint::CreateReplacement( 520 SourceRange(OIRE->getOpLoc(), 521 OIRE->getLocEnd()), ")"); 522 else 523 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 524 } 525 S.Diag(IV->getLocation(), diag::note_ivar_decl); 526 } 527 } 528 } 529 530 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 531 // Handle any placeholder expressions which made it here. 532 if (E->getType()->isPlaceholderType()) { 533 ExprResult result = CheckPlaceholderExpr(E); 534 if (result.isInvalid()) return ExprError(); 535 E = result.get(); 536 } 537 538 // C++ [conv.lval]p1: 539 // A glvalue of a non-function, non-array type T can be 540 // converted to a prvalue. 541 if (!E->isGLValue()) return E; 542 543 QualType T = E->getType(); 544 assert(!T.isNull() && "r-value conversion on typeless expression?"); 545 546 // We don't want to throw lvalue-to-rvalue casts on top of 547 // expressions of certain types in C++. 548 if (getLangOpts().CPlusPlus && 549 (E->getType() == Context.OverloadTy || 550 T->isDependentType() || 551 T->isRecordType())) 552 return E; 553 554 // The C standard is actually really unclear on this point, and 555 // DR106 tells us what the result should be but not why. It's 556 // generally best to say that void types just doesn't undergo 557 // lvalue-to-rvalue at all. Note that expressions of unqualified 558 // 'void' type are never l-values, but qualified void can be. 559 if (T->isVoidType()) 560 return E; 561 562 // OpenCL usually rejects direct accesses to values of 'half' type. 563 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 564 T->isHalfType()) { 565 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 566 << 0 << T; 567 return ExprError(); 568 } 569 570 CheckForNullPointerDereference(*this, E); 571 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 572 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 573 &Context.Idents.get("object_getClass"), 574 SourceLocation(), LookupOrdinaryName); 575 if (ObjectGetClass) 576 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 577 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 578 FixItHint::CreateReplacement( 579 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 580 else 581 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 582 } 583 else if (const ObjCIvarRefExpr *OIRE = 584 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 585 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 586 587 // C++ [conv.lval]p1: 588 // [...] If T is a non-class type, the type of the prvalue is the 589 // cv-unqualified version of T. Otherwise, the type of the 590 // rvalue is T. 591 // 592 // C99 6.3.2.1p2: 593 // If the lvalue has qualified type, the value has the unqualified 594 // version of the type of the lvalue; otherwise, the value has the 595 // type of the lvalue. 596 if (T.hasQualifiers()) 597 T = T.getUnqualifiedType(); 598 599 // Under the MS ABI, lock down the inheritance model now. 600 if (T->isMemberPointerType() && 601 Context.getTargetInfo().getCXXABI().isMicrosoft()) 602 (void)isCompleteType(E->getExprLoc(), T); 603 604 UpdateMarkingForLValueToRValue(E); 605 606 // Loading a __weak object implicitly retains the value, so we need a cleanup to 607 // balance that. 608 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 609 Cleanup.setExprNeedsCleanups(true); 610 611 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 612 nullptr, VK_RValue); 613 614 // C11 6.3.2.1p2: 615 // ... if the lvalue has atomic type, the value has the non-atomic version 616 // of the type of the lvalue ... 617 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 618 T = Atomic->getValueType().getUnqualifiedType(); 619 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 620 nullptr, VK_RValue); 621 } 622 623 return Res; 624 } 625 626 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 627 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 628 if (Res.isInvalid()) 629 return ExprError(); 630 Res = DefaultLvalueConversion(Res.get()); 631 if (Res.isInvalid()) 632 return ExprError(); 633 return Res; 634 } 635 636 /// CallExprUnaryConversions - a special case of an unary conversion 637 /// performed on a function designator of a call expression. 638 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 639 QualType Ty = E->getType(); 640 ExprResult Res = E; 641 // Only do implicit cast for a function type, but not for a pointer 642 // to function type. 643 if (Ty->isFunctionType()) { 644 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 645 CK_FunctionToPointerDecay).get(); 646 if (Res.isInvalid()) 647 return ExprError(); 648 } 649 Res = DefaultLvalueConversion(Res.get()); 650 if (Res.isInvalid()) 651 return ExprError(); 652 return Res.get(); 653 } 654 655 /// UsualUnaryConversions - Performs various conversions that are common to most 656 /// operators (C99 6.3). The conversions of array and function types are 657 /// sometimes suppressed. For example, the array->pointer conversion doesn't 658 /// apply if the array is an argument to the sizeof or address (&) operators. 659 /// In these instances, this routine should *not* be called. 660 ExprResult Sema::UsualUnaryConversions(Expr *E) { 661 // First, convert to an r-value. 662 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 663 if (Res.isInvalid()) 664 return ExprError(); 665 E = Res.get(); 666 667 QualType Ty = E->getType(); 668 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 669 670 // Half FP have to be promoted to float unless it is natively supported 671 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 672 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 673 674 // Try to perform integral promotions if the object has a theoretically 675 // promotable type. 676 if (Ty->isIntegralOrUnscopedEnumerationType()) { 677 // C99 6.3.1.1p2: 678 // 679 // The following may be used in an expression wherever an int or 680 // unsigned int may be used: 681 // - an object or expression with an integer type whose integer 682 // conversion rank is less than or equal to the rank of int 683 // and unsigned int. 684 // - A bit-field of type _Bool, int, signed int, or unsigned int. 685 // 686 // If an int can represent all values of the original type, the 687 // value is converted to an int; otherwise, it is converted to an 688 // unsigned int. These are called the integer promotions. All 689 // other types are unchanged by the integer promotions. 690 691 QualType PTy = Context.isPromotableBitField(E); 692 if (!PTy.isNull()) { 693 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 694 return E; 695 } 696 if (Ty->isPromotableIntegerType()) { 697 QualType PT = Context.getPromotedIntegerType(Ty); 698 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 699 return E; 700 } 701 } 702 return E; 703 } 704 705 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 706 /// do not have a prototype. Arguments that have type float or __fp16 707 /// are promoted to double. All other argument types are converted by 708 /// UsualUnaryConversions(). 709 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 710 QualType Ty = E->getType(); 711 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 712 713 ExprResult Res = UsualUnaryConversions(E); 714 if (Res.isInvalid()) 715 return ExprError(); 716 E = Res.get(); 717 718 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 719 // promote to double. 720 // Note that default argument promotion applies only to float (and 721 // half/fp16); it does not apply to _Float16. 722 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 723 if (BTy && (BTy->getKind() == BuiltinType::Half || 724 BTy->getKind() == BuiltinType::Float)) { 725 if (getLangOpts().OpenCL && 726 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 727 if (BTy->getKind() == BuiltinType::Half) { 728 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 729 } 730 } else { 731 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 732 } 733 } 734 735 // C++ performs lvalue-to-rvalue conversion as a default argument 736 // promotion, even on class types, but note: 737 // C++11 [conv.lval]p2: 738 // When an lvalue-to-rvalue conversion occurs in an unevaluated 739 // operand or a subexpression thereof the value contained in the 740 // referenced object is not accessed. Otherwise, if the glvalue 741 // has a class type, the conversion copy-initializes a temporary 742 // of type T from the glvalue and the result of the conversion 743 // is a prvalue for the temporary. 744 // FIXME: add some way to gate this entire thing for correctness in 745 // potentially potentially evaluated contexts. 746 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 747 ExprResult Temp = PerformCopyInitialization( 748 InitializedEntity::InitializeTemporary(E->getType()), 749 E->getExprLoc(), E); 750 if (Temp.isInvalid()) 751 return ExprError(); 752 E = Temp.get(); 753 } 754 755 return E; 756 } 757 758 /// Determine the degree of POD-ness for an expression. 759 /// Incomplete types are considered POD, since this check can be performed 760 /// when we're in an unevaluated context. 761 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 762 if (Ty->isIncompleteType()) { 763 // C++11 [expr.call]p7: 764 // After these conversions, if the argument does not have arithmetic, 765 // enumeration, pointer, pointer to member, or class type, the program 766 // is ill-formed. 767 // 768 // Since we've already performed array-to-pointer and function-to-pointer 769 // decay, the only such type in C++ is cv void. This also handles 770 // initializer lists as variadic arguments. 771 if (Ty->isVoidType()) 772 return VAK_Invalid; 773 774 if (Ty->isObjCObjectType()) 775 return VAK_Invalid; 776 return VAK_Valid; 777 } 778 779 if (Ty.isCXX98PODType(Context)) 780 return VAK_Valid; 781 782 // C++11 [expr.call]p7: 783 // Passing a potentially-evaluated argument of class type (Clause 9) 784 // having a non-trivial copy constructor, a non-trivial move constructor, 785 // or a non-trivial destructor, with no corresponding parameter, 786 // is conditionally-supported with implementation-defined semantics. 787 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 788 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 789 if (!Record->hasNonTrivialCopyConstructor() && 790 !Record->hasNonTrivialMoveConstructor() && 791 !Record->hasNonTrivialDestructor()) 792 return VAK_ValidInCXX11; 793 794 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 795 return VAK_Valid; 796 797 if (Ty->isObjCObjectType()) 798 return VAK_Invalid; 799 800 if (getLangOpts().MSVCCompat) 801 return VAK_MSVCUndefined; 802 803 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 804 // permitted to reject them. We should consider doing so. 805 return VAK_Undefined; 806 } 807 808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 809 // Don't allow one to pass an Objective-C interface to a vararg. 810 const QualType &Ty = E->getType(); 811 VarArgKind VAK = isValidVarArgType(Ty); 812 813 // Complain about passing non-POD types through varargs. 814 switch (VAK) { 815 case VAK_ValidInCXX11: 816 DiagRuntimeBehavior( 817 E->getLocStart(), nullptr, 818 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 819 << Ty << CT); 820 LLVM_FALLTHROUGH; 821 case VAK_Valid: 822 if (Ty->isRecordType()) { 823 // This is unlikely to be what the user intended. If the class has a 824 // 'c_str' member function, the user probably meant to call that. 825 DiagRuntimeBehavior(E->getLocStart(), nullptr, 826 PDiag(diag::warn_pass_class_arg_to_vararg) 827 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 828 } 829 break; 830 831 case VAK_Undefined: 832 case VAK_MSVCUndefined: 833 DiagRuntimeBehavior( 834 E->getLocStart(), nullptr, 835 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 836 << getLangOpts().CPlusPlus11 << Ty << CT); 837 break; 838 839 case VAK_Invalid: 840 if (Ty->isObjCObjectType()) 841 DiagRuntimeBehavior( 842 E->getLocStart(), nullptr, 843 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 844 << Ty << CT); 845 else 846 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 847 << isa<InitListExpr>(E) << Ty << CT; 848 break; 849 } 850 } 851 852 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 853 /// will create a trap if the resulting type is not a POD type. 854 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 855 FunctionDecl *FDecl) { 856 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 857 // Strip the unbridged-cast placeholder expression off, if applicable. 858 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 859 (CT == VariadicMethod || 860 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 861 E = stripARCUnbridgedCast(E); 862 863 // Otherwise, do normal placeholder checking. 864 } else { 865 ExprResult ExprRes = CheckPlaceholderExpr(E); 866 if (ExprRes.isInvalid()) 867 return ExprError(); 868 E = ExprRes.get(); 869 } 870 } 871 872 ExprResult ExprRes = DefaultArgumentPromotion(E); 873 if (ExprRes.isInvalid()) 874 return ExprError(); 875 E = ExprRes.get(); 876 877 // Diagnostics regarding non-POD argument types are 878 // emitted along with format string checking in Sema::CheckFunctionCall(). 879 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 880 // Turn this into a trap. 881 CXXScopeSpec SS; 882 SourceLocation TemplateKWLoc; 883 UnqualifiedId Name; 884 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 885 E->getLocStart()); 886 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 887 Name, true, false); 888 if (TrapFn.isInvalid()) 889 return ExprError(); 890 891 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 892 E->getLocStart(), None, 893 E->getLocEnd()); 894 if (Call.isInvalid()) 895 return ExprError(); 896 897 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 898 Call.get(), E); 899 if (Comma.isInvalid()) 900 return ExprError(); 901 return Comma.get(); 902 } 903 904 if (!getLangOpts().CPlusPlus && 905 RequireCompleteType(E->getExprLoc(), E->getType(), 906 diag::err_call_incomplete_argument)) 907 return ExprError(); 908 909 return E; 910 } 911 912 /// \brief Converts an integer to complex float type. Helper function of 913 /// UsualArithmeticConversions() 914 /// 915 /// \return false if the integer expression is an integer type and is 916 /// successfully converted to the complex type. 917 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 918 ExprResult &ComplexExpr, 919 QualType IntTy, 920 QualType ComplexTy, 921 bool SkipCast) { 922 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 923 if (SkipCast) return false; 924 if (IntTy->isIntegerType()) { 925 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 926 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 927 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 928 CK_FloatingRealToComplex); 929 } else { 930 assert(IntTy->isComplexIntegerType()); 931 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 932 CK_IntegralComplexToFloatingComplex); 933 } 934 return false; 935 } 936 937 /// \brief Handle arithmetic conversion with complex types. Helper function of 938 /// UsualArithmeticConversions() 939 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 940 ExprResult &RHS, QualType LHSType, 941 QualType RHSType, 942 bool IsCompAssign) { 943 // if we have an integer operand, the result is the complex type. 944 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 945 /*skipCast*/false)) 946 return LHSType; 947 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 948 /*skipCast*/IsCompAssign)) 949 return RHSType; 950 951 // This handles complex/complex, complex/float, or float/complex. 952 // When both operands are complex, the shorter operand is converted to the 953 // type of the longer, and that is the type of the result. This corresponds 954 // to what is done when combining two real floating-point operands. 955 // The fun begins when size promotion occur across type domains. 956 // From H&S 6.3.4: When one operand is complex and the other is a real 957 // floating-point type, the less precise type is converted, within it's 958 // real or complex domain, to the precision of the other type. For example, 959 // when combining a "long double" with a "double _Complex", the 960 // "double _Complex" is promoted to "long double _Complex". 961 962 // Compute the rank of the two types, regardless of whether they are complex. 963 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 964 965 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 966 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 967 QualType LHSElementType = 968 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 969 QualType RHSElementType = 970 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 971 972 QualType ResultType = S.Context.getComplexType(LHSElementType); 973 if (Order < 0) { 974 // Promote the precision of the LHS if not an assignment. 975 ResultType = S.Context.getComplexType(RHSElementType); 976 if (!IsCompAssign) { 977 if (LHSComplexType) 978 LHS = 979 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 980 else 981 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 982 } 983 } else if (Order > 0) { 984 // Promote the precision of the RHS. 985 if (RHSComplexType) 986 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 987 else 988 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 989 } 990 return ResultType; 991 } 992 993 /// \brief Handle arithmetic conversion from integer to float. Helper function 994 /// of UsualArithmeticConversions() 995 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 996 ExprResult &IntExpr, 997 QualType FloatTy, QualType IntTy, 998 bool ConvertFloat, bool ConvertInt) { 999 if (IntTy->isIntegerType()) { 1000 if (ConvertInt) 1001 // Convert intExpr to the lhs floating point type. 1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1003 CK_IntegralToFloating); 1004 return FloatTy; 1005 } 1006 1007 // Convert both sides to the appropriate complex float. 1008 assert(IntTy->isComplexIntegerType()); 1009 QualType result = S.Context.getComplexType(FloatTy); 1010 1011 // _Complex int -> _Complex float 1012 if (ConvertInt) 1013 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1014 CK_IntegralComplexToFloatingComplex); 1015 1016 // float -> _Complex float 1017 if (ConvertFloat) 1018 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1019 CK_FloatingRealToComplex); 1020 1021 return result; 1022 } 1023 1024 /// \brief Handle arithmethic conversion with floating point types. Helper 1025 /// function of UsualArithmeticConversions() 1026 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1027 ExprResult &RHS, QualType LHSType, 1028 QualType RHSType, bool IsCompAssign) { 1029 bool LHSFloat = LHSType->isRealFloatingType(); 1030 bool RHSFloat = RHSType->isRealFloatingType(); 1031 1032 // If we have two real floating types, convert the smaller operand 1033 // to the bigger result. 1034 if (LHSFloat && RHSFloat) { 1035 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1036 if (order > 0) { 1037 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1038 return LHSType; 1039 } 1040 1041 assert(order < 0 && "illegal float comparison"); 1042 if (!IsCompAssign) 1043 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1044 return RHSType; 1045 } 1046 1047 if (LHSFloat) { 1048 // Half FP has to be promoted to float unless it is natively supported 1049 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1050 LHSType = S.Context.FloatTy; 1051 1052 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1053 /*convertFloat=*/!IsCompAssign, 1054 /*convertInt=*/ true); 1055 } 1056 assert(RHSFloat); 1057 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1058 /*convertInt=*/ true, 1059 /*convertFloat=*/!IsCompAssign); 1060 } 1061 1062 /// \brief Diagnose attempts to convert between __float128 and long double if 1063 /// there is no support for such conversion. Helper function of 1064 /// UsualArithmeticConversions(). 1065 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1066 QualType RHSType) { 1067 /* No issue converting if at least one of the types is not a floating point 1068 type or the two types have the same rank. 1069 */ 1070 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1071 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1072 return false; 1073 1074 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1075 "The remaining types must be floating point types."); 1076 1077 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1078 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1079 1080 QualType LHSElemType = LHSComplex ? 1081 LHSComplex->getElementType() : LHSType; 1082 QualType RHSElemType = RHSComplex ? 1083 RHSComplex->getElementType() : RHSType; 1084 1085 // No issue if the two types have the same representation 1086 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1087 &S.Context.getFloatTypeSemantics(RHSElemType)) 1088 return false; 1089 1090 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1091 RHSElemType == S.Context.LongDoubleTy); 1092 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1093 RHSElemType == S.Context.Float128Ty); 1094 1095 // We've handled the situation where __float128 and long double have the same 1096 // representation. We allow all conversions for all possible long double types 1097 // except PPC's double double. 1098 return Float128AndLongDouble && 1099 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1100 &llvm::APFloat::PPCDoubleDouble()); 1101 } 1102 1103 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1104 1105 namespace { 1106 /// These helper callbacks are placed in an anonymous namespace to 1107 /// permit their use as function template parameters. 1108 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1109 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1110 } 1111 1112 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1113 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1114 CK_IntegralComplexCast); 1115 } 1116 } 1117 1118 /// \brief Handle integer arithmetic conversions. Helper function of 1119 /// UsualArithmeticConversions() 1120 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1121 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1122 ExprResult &RHS, QualType LHSType, 1123 QualType RHSType, bool IsCompAssign) { 1124 // The rules for this case are in C99 6.3.1.8 1125 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1126 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1127 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1128 if (LHSSigned == RHSSigned) { 1129 // Same signedness; use the higher-ranked type 1130 if (order >= 0) { 1131 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1132 return LHSType; 1133 } else if (!IsCompAssign) 1134 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1135 return RHSType; 1136 } else if (order != (LHSSigned ? 1 : -1)) { 1137 // The unsigned type has greater than or equal rank to the 1138 // signed type, so use the unsigned type 1139 if (RHSSigned) { 1140 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1141 return LHSType; 1142 } else if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1144 return RHSType; 1145 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1146 // The two types are different widths; if we are here, that 1147 // means the signed type is larger than the unsigned type, so 1148 // use the signed type. 1149 if (LHSSigned) { 1150 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1151 return LHSType; 1152 } else if (!IsCompAssign) 1153 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1154 return RHSType; 1155 } else { 1156 // The signed type is higher-ranked than the unsigned type, 1157 // but isn't actually any bigger (like unsigned int and long 1158 // on most 32-bit systems). Use the unsigned type corresponding 1159 // to the signed type. 1160 QualType result = 1161 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1162 RHS = (*doRHSCast)(S, RHS.get(), result); 1163 if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.get(), result); 1165 return result; 1166 } 1167 } 1168 1169 /// \brief Handle conversions with GCC complex int extension. Helper function 1170 /// of UsualArithmeticConversions() 1171 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1172 ExprResult &RHS, QualType LHSType, 1173 QualType RHSType, 1174 bool IsCompAssign) { 1175 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1176 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1177 1178 if (LHSComplexInt && RHSComplexInt) { 1179 QualType LHSEltType = LHSComplexInt->getElementType(); 1180 QualType RHSEltType = RHSComplexInt->getElementType(); 1181 QualType ScalarType = 1182 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1183 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1184 1185 return S.Context.getComplexType(ScalarType); 1186 } 1187 1188 if (LHSComplexInt) { 1189 QualType LHSEltType = LHSComplexInt->getElementType(); 1190 QualType ScalarType = 1191 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1192 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1193 QualType ComplexType = S.Context.getComplexType(ScalarType); 1194 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1195 CK_IntegralRealToComplex); 1196 1197 return ComplexType; 1198 } 1199 1200 assert(RHSComplexInt); 1201 1202 QualType RHSEltType = RHSComplexInt->getElementType(); 1203 QualType ScalarType = 1204 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1205 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1206 QualType ComplexType = S.Context.getComplexType(ScalarType); 1207 1208 if (!IsCompAssign) 1209 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1210 CK_IntegralRealToComplex); 1211 return ComplexType; 1212 } 1213 1214 /// UsualArithmeticConversions - Performs various conversions that are common to 1215 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1216 /// routine returns the first non-arithmetic type found. The client is 1217 /// responsible for emitting appropriate error diagnostics. 1218 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1219 bool IsCompAssign) { 1220 if (!IsCompAssign) { 1221 LHS = UsualUnaryConversions(LHS.get()); 1222 if (LHS.isInvalid()) 1223 return QualType(); 1224 } 1225 1226 RHS = UsualUnaryConversions(RHS.get()); 1227 if (RHS.isInvalid()) 1228 return QualType(); 1229 1230 // For conversion purposes, we ignore any qualifiers. 1231 // For example, "const float" and "float" are equivalent. 1232 QualType LHSType = 1233 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1234 QualType RHSType = 1235 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1236 1237 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1238 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1239 LHSType = AtomicLHS->getValueType(); 1240 1241 // If both types are identical, no conversion is needed. 1242 if (LHSType == RHSType) 1243 return LHSType; 1244 1245 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1246 // The caller can deal with this (e.g. pointer + int). 1247 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1248 return QualType(); 1249 1250 // Apply unary and bitfield promotions to the LHS's type. 1251 QualType LHSUnpromotedType = LHSType; 1252 if (LHSType->isPromotableIntegerType()) 1253 LHSType = Context.getPromotedIntegerType(LHSType); 1254 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1255 if (!LHSBitfieldPromoteTy.isNull()) 1256 LHSType = LHSBitfieldPromoteTy; 1257 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1258 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1259 1260 // If both types are identical, no conversion is needed. 1261 if (LHSType == RHSType) 1262 return LHSType; 1263 1264 // At this point, we have two different arithmetic types. 1265 1266 // Diagnose attempts to convert between __float128 and long double where 1267 // such conversions currently can't be handled. 1268 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1269 return QualType(); 1270 1271 // Handle complex types first (C99 6.3.1.8p1). 1272 if (LHSType->isComplexType() || RHSType->isComplexType()) 1273 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1274 IsCompAssign); 1275 1276 // Now handle "real" floating types (i.e. float, double, long double). 1277 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1278 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1279 IsCompAssign); 1280 1281 // Handle GCC complex int extension. 1282 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1283 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1284 IsCompAssign); 1285 1286 // Finally, we have two differing integer types. 1287 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1288 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1289 } 1290 1291 1292 //===----------------------------------------------------------------------===// 1293 // Semantic Analysis for various Expression Types 1294 //===----------------------------------------------------------------------===// 1295 1296 1297 ExprResult 1298 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1299 SourceLocation DefaultLoc, 1300 SourceLocation RParenLoc, 1301 Expr *ControllingExpr, 1302 ArrayRef<ParsedType> ArgTypes, 1303 ArrayRef<Expr *> ArgExprs) { 1304 unsigned NumAssocs = ArgTypes.size(); 1305 assert(NumAssocs == ArgExprs.size()); 1306 1307 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1308 for (unsigned i = 0; i < NumAssocs; ++i) { 1309 if (ArgTypes[i]) 1310 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1311 else 1312 Types[i] = nullptr; 1313 } 1314 1315 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1316 ControllingExpr, 1317 llvm::makeArrayRef(Types, NumAssocs), 1318 ArgExprs); 1319 delete [] Types; 1320 return ER; 1321 } 1322 1323 ExprResult 1324 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1325 SourceLocation DefaultLoc, 1326 SourceLocation RParenLoc, 1327 Expr *ControllingExpr, 1328 ArrayRef<TypeSourceInfo *> Types, 1329 ArrayRef<Expr *> Exprs) { 1330 unsigned NumAssocs = Types.size(); 1331 assert(NumAssocs == Exprs.size()); 1332 1333 // Decay and strip qualifiers for the controlling expression type, and handle 1334 // placeholder type replacement. See committee discussion from WG14 DR423. 1335 { 1336 EnterExpressionEvaluationContext Unevaluated( 1337 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1338 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1339 if (R.isInvalid()) 1340 return ExprError(); 1341 ControllingExpr = R.get(); 1342 } 1343 1344 // The controlling expression is an unevaluated operand, so side effects are 1345 // likely unintended. 1346 if (!inTemplateInstantiation() && 1347 ControllingExpr->HasSideEffects(Context, false)) 1348 Diag(ControllingExpr->getExprLoc(), 1349 diag::warn_side_effects_unevaluated_context); 1350 1351 bool TypeErrorFound = false, 1352 IsResultDependent = ControllingExpr->isTypeDependent(), 1353 ContainsUnexpandedParameterPack 1354 = ControllingExpr->containsUnexpandedParameterPack(); 1355 1356 for (unsigned i = 0; i < NumAssocs; ++i) { 1357 if (Exprs[i]->containsUnexpandedParameterPack()) 1358 ContainsUnexpandedParameterPack = true; 1359 1360 if (Types[i]) { 1361 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1362 ContainsUnexpandedParameterPack = true; 1363 1364 if (Types[i]->getType()->isDependentType()) { 1365 IsResultDependent = true; 1366 } else { 1367 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1368 // complete object type other than a variably modified type." 1369 unsigned D = 0; 1370 if (Types[i]->getType()->isIncompleteType()) 1371 D = diag::err_assoc_type_incomplete; 1372 else if (!Types[i]->getType()->isObjectType()) 1373 D = diag::err_assoc_type_nonobject; 1374 else if (Types[i]->getType()->isVariablyModifiedType()) 1375 D = diag::err_assoc_type_variably_modified; 1376 1377 if (D != 0) { 1378 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1379 << Types[i]->getTypeLoc().getSourceRange() 1380 << Types[i]->getType(); 1381 TypeErrorFound = true; 1382 } 1383 1384 // C11 6.5.1.1p2 "No two generic associations in the same generic 1385 // selection shall specify compatible types." 1386 for (unsigned j = i+1; j < NumAssocs; ++j) 1387 if (Types[j] && !Types[j]->getType()->isDependentType() && 1388 Context.typesAreCompatible(Types[i]->getType(), 1389 Types[j]->getType())) { 1390 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1391 diag::err_assoc_compatible_types) 1392 << Types[j]->getTypeLoc().getSourceRange() 1393 << Types[j]->getType() 1394 << Types[i]->getType(); 1395 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1396 diag::note_compat_assoc) 1397 << Types[i]->getTypeLoc().getSourceRange() 1398 << Types[i]->getType(); 1399 TypeErrorFound = true; 1400 } 1401 } 1402 } 1403 } 1404 if (TypeErrorFound) 1405 return ExprError(); 1406 1407 // If we determined that the generic selection is result-dependent, don't 1408 // try to compute the result expression. 1409 if (IsResultDependent) 1410 return new (Context) GenericSelectionExpr( 1411 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1412 ContainsUnexpandedParameterPack); 1413 1414 SmallVector<unsigned, 1> CompatIndices; 1415 unsigned DefaultIndex = -1U; 1416 for (unsigned i = 0; i < NumAssocs; ++i) { 1417 if (!Types[i]) 1418 DefaultIndex = i; 1419 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1420 Types[i]->getType())) 1421 CompatIndices.push_back(i); 1422 } 1423 1424 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1425 // type compatible with at most one of the types named in its generic 1426 // association list." 1427 if (CompatIndices.size() > 1) { 1428 // We strip parens here because the controlling expression is typically 1429 // parenthesized in macro definitions. 1430 ControllingExpr = ControllingExpr->IgnoreParens(); 1431 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1432 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1433 << (unsigned) CompatIndices.size(); 1434 for (unsigned I : CompatIndices) { 1435 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1436 diag::note_compat_assoc) 1437 << Types[I]->getTypeLoc().getSourceRange() 1438 << Types[I]->getType(); 1439 } 1440 return ExprError(); 1441 } 1442 1443 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1444 // its controlling expression shall have type compatible with exactly one of 1445 // the types named in its generic association list." 1446 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1447 // We strip parens here because the controlling expression is typically 1448 // parenthesized in macro definitions. 1449 ControllingExpr = ControllingExpr->IgnoreParens(); 1450 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1451 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1452 return ExprError(); 1453 } 1454 1455 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1456 // type name that is compatible with the type of the controlling expression, 1457 // then the result expression of the generic selection is the expression 1458 // in that generic association. Otherwise, the result expression of the 1459 // generic selection is the expression in the default generic association." 1460 unsigned ResultIndex = 1461 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1462 1463 return new (Context) GenericSelectionExpr( 1464 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1465 ContainsUnexpandedParameterPack, ResultIndex); 1466 } 1467 1468 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1469 /// location of the token and the offset of the ud-suffix within it. 1470 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1471 unsigned Offset) { 1472 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1473 S.getLangOpts()); 1474 } 1475 1476 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1477 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1478 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1479 IdentifierInfo *UDSuffix, 1480 SourceLocation UDSuffixLoc, 1481 ArrayRef<Expr*> Args, 1482 SourceLocation LitEndLoc) { 1483 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1484 1485 QualType ArgTy[2]; 1486 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1487 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1488 if (ArgTy[ArgIdx]->isArrayType()) 1489 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1490 } 1491 1492 DeclarationName OpName = 1493 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1494 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1495 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1496 1497 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1498 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1499 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1500 /*AllowStringTemplate*/ false, 1501 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1502 return ExprError(); 1503 1504 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1505 } 1506 1507 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1508 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1509 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1510 /// multiple tokens. However, the common case is that StringToks points to one 1511 /// string. 1512 /// 1513 ExprResult 1514 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1515 assert(!StringToks.empty() && "Must have at least one string!"); 1516 1517 StringLiteralParser Literal(StringToks, PP); 1518 if (Literal.hadError) 1519 return ExprError(); 1520 1521 SmallVector<SourceLocation, 4> StringTokLocs; 1522 for (const Token &Tok : StringToks) 1523 StringTokLocs.push_back(Tok.getLocation()); 1524 1525 QualType CharTy = Context.CharTy; 1526 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1527 if (Literal.isWide()) { 1528 CharTy = Context.getWideCharType(); 1529 Kind = StringLiteral::Wide; 1530 } else if (Literal.isUTF8()) { 1531 Kind = StringLiteral::UTF8; 1532 } else if (Literal.isUTF16()) { 1533 CharTy = Context.Char16Ty; 1534 Kind = StringLiteral::UTF16; 1535 } else if (Literal.isUTF32()) { 1536 CharTy = Context.Char32Ty; 1537 Kind = StringLiteral::UTF32; 1538 } else if (Literal.isPascal()) { 1539 CharTy = Context.UnsignedCharTy; 1540 } 1541 1542 QualType CharTyConst = CharTy; 1543 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1544 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1545 CharTyConst.addConst(); 1546 1547 // Get an array type for the string, according to C99 6.4.5. This includes 1548 // the nul terminator character as well as the string length for pascal 1549 // strings. 1550 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1551 llvm::APInt(32, Literal.GetNumStringChars()+1), 1552 ArrayType::Normal, 0); 1553 1554 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1555 if (getLangOpts().OpenCL) { 1556 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1557 } 1558 1559 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1560 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1561 Kind, Literal.Pascal, StrTy, 1562 &StringTokLocs[0], 1563 StringTokLocs.size()); 1564 if (Literal.getUDSuffix().empty()) 1565 return Lit; 1566 1567 // We're building a user-defined literal. 1568 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1569 SourceLocation UDSuffixLoc = 1570 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1571 Literal.getUDSuffixOffset()); 1572 1573 // Make sure we're allowed user-defined literals here. 1574 if (!UDLScope) 1575 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1576 1577 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1578 // operator "" X (str, len) 1579 QualType SizeType = Context.getSizeType(); 1580 1581 DeclarationName OpName = 1582 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1583 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1584 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1585 1586 QualType ArgTy[] = { 1587 Context.getArrayDecayedType(StrTy), SizeType 1588 }; 1589 1590 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1591 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1592 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1593 /*AllowStringTemplate*/ true, 1594 /*DiagnoseMissing*/ true)) { 1595 1596 case LOLR_Cooked: { 1597 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1598 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1599 StringTokLocs[0]); 1600 Expr *Args[] = { Lit, LenArg }; 1601 1602 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1603 } 1604 1605 case LOLR_StringTemplate: { 1606 TemplateArgumentListInfo ExplicitArgs; 1607 1608 unsigned CharBits = Context.getIntWidth(CharTy); 1609 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1610 llvm::APSInt Value(CharBits, CharIsUnsigned); 1611 1612 TemplateArgument TypeArg(CharTy); 1613 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1614 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1615 1616 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1617 Value = Lit->getCodeUnit(I); 1618 TemplateArgument Arg(Context, Value, CharTy); 1619 TemplateArgumentLocInfo ArgInfo; 1620 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1621 } 1622 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1623 &ExplicitArgs); 1624 } 1625 case LOLR_Raw: 1626 case LOLR_Template: 1627 case LOLR_ErrorNoDiagnostic: 1628 llvm_unreachable("unexpected literal operator lookup result"); 1629 case LOLR_Error: 1630 return ExprError(); 1631 } 1632 llvm_unreachable("unexpected literal operator lookup result"); 1633 } 1634 1635 ExprResult 1636 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1637 SourceLocation Loc, 1638 const CXXScopeSpec *SS) { 1639 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1640 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1641 } 1642 1643 /// BuildDeclRefExpr - Build an expression that references a 1644 /// declaration that does not require a closure capture. 1645 ExprResult 1646 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1647 const DeclarationNameInfo &NameInfo, 1648 const CXXScopeSpec *SS, NamedDecl *FoundD, 1649 const TemplateArgumentListInfo *TemplateArgs) { 1650 bool RefersToCapturedVariable = 1651 isa<VarDecl>(D) && 1652 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1653 1654 DeclRefExpr *E; 1655 if (isa<VarTemplateSpecializationDecl>(D)) { 1656 VarTemplateSpecializationDecl *VarSpec = 1657 cast<VarTemplateSpecializationDecl>(D); 1658 1659 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1660 : NestedNameSpecifierLoc(), 1661 VarSpec->getTemplateKeywordLoc(), D, 1662 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1663 FoundD, TemplateArgs); 1664 } else { 1665 assert(!TemplateArgs && "No template arguments for non-variable" 1666 " template specialization references"); 1667 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1668 : NestedNameSpecifierLoc(), 1669 SourceLocation(), D, RefersToCapturedVariable, 1670 NameInfo, Ty, VK, FoundD); 1671 } 1672 1673 MarkDeclRefReferenced(E); 1674 1675 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1676 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1677 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1678 recordUseOfEvaluatedWeak(E); 1679 1680 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1681 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1682 FD = IFD->getAnonField(); 1683 if (FD) { 1684 UnusedPrivateFields.remove(FD); 1685 // Just in case we're building an illegal pointer-to-member. 1686 if (FD->isBitField()) 1687 E->setObjectKind(OK_BitField); 1688 } 1689 1690 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1691 // designates a bit-field. 1692 if (auto *BD = dyn_cast<BindingDecl>(D)) 1693 if (auto *BE = BD->getBinding()) 1694 E->setObjectKind(BE->getObjectKind()); 1695 1696 return E; 1697 } 1698 1699 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1700 /// possibly a list of template arguments. 1701 /// 1702 /// If this produces template arguments, it is permitted to call 1703 /// DecomposeTemplateName. 1704 /// 1705 /// This actually loses a lot of source location information for 1706 /// non-standard name kinds; we should consider preserving that in 1707 /// some way. 1708 void 1709 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1710 TemplateArgumentListInfo &Buffer, 1711 DeclarationNameInfo &NameInfo, 1712 const TemplateArgumentListInfo *&TemplateArgs) { 1713 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1714 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1715 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1716 1717 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1718 Id.TemplateId->NumArgs); 1719 translateTemplateArguments(TemplateArgsPtr, Buffer); 1720 1721 TemplateName TName = Id.TemplateId->Template.get(); 1722 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1723 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1724 TemplateArgs = &Buffer; 1725 } else { 1726 NameInfo = GetNameFromUnqualifiedId(Id); 1727 TemplateArgs = nullptr; 1728 } 1729 } 1730 1731 static void emitEmptyLookupTypoDiagnostic( 1732 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1733 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1734 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1735 DeclContext *Ctx = 1736 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1737 if (!TC) { 1738 // Emit a special diagnostic for failed member lookups. 1739 // FIXME: computing the declaration context might fail here (?) 1740 if (Ctx) 1741 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1742 << SS.getRange(); 1743 else 1744 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1745 return; 1746 } 1747 1748 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1749 bool DroppedSpecifier = 1750 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1751 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1752 ? diag::note_implicit_param_decl 1753 : diag::note_previous_decl; 1754 if (!Ctx) 1755 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1756 SemaRef.PDiag(NoteID)); 1757 else 1758 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1759 << Typo << Ctx << DroppedSpecifier 1760 << SS.getRange(), 1761 SemaRef.PDiag(NoteID)); 1762 } 1763 1764 /// Diagnose an empty lookup. 1765 /// 1766 /// \return false if new lookup candidates were found 1767 bool 1768 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1769 std::unique_ptr<CorrectionCandidateCallback> CCC, 1770 TemplateArgumentListInfo *ExplicitTemplateArgs, 1771 ArrayRef<Expr *> Args, TypoExpr **Out) { 1772 DeclarationName Name = R.getLookupName(); 1773 1774 unsigned diagnostic = diag::err_undeclared_var_use; 1775 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1776 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1777 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1778 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1779 diagnostic = diag::err_undeclared_use; 1780 diagnostic_suggest = diag::err_undeclared_use_suggest; 1781 } 1782 1783 // If the original lookup was an unqualified lookup, fake an 1784 // unqualified lookup. This is useful when (for example) the 1785 // original lookup would not have found something because it was a 1786 // dependent name. 1787 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1788 while (DC) { 1789 if (isa<CXXRecordDecl>(DC)) { 1790 LookupQualifiedName(R, DC); 1791 1792 if (!R.empty()) { 1793 // Don't give errors about ambiguities in this lookup. 1794 R.suppressDiagnostics(); 1795 1796 // During a default argument instantiation the CurContext points 1797 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1798 // function parameter list, hence add an explicit check. 1799 bool isDefaultArgument = 1800 !CodeSynthesisContexts.empty() && 1801 CodeSynthesisContexts.back().Kind == 1802 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1803 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1804 bool isInstance = CurMethod && 1805 CurMethod->isInstance() && 1806 DC == CurMethod->getParent() && !isDefaultArgument; 1807 1808 // Give a code modification hint to insert 'this->'. 1809 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1810 // Actually quite difficult! 1811 if (getLangOpts().MSVCCompat) 1812 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1813 if (isInstance) { 1814 Diag(R.getNameLoc(), diagnostic) << Name 1815 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1816 CheckCXXThisCapture(R.getNameLoc()); 1817 } else { 1818 Diag(R.getNameLoc(), diagnostic) << Name; 1819 } 1820 1821 // Do we really want to note all of these? 1822 for (NamedDecl *D : R) 1823 Diag(D->getLocation(), diag::note_dependent_var_use); 1824 1825 // Return true if we are inside a default argument instantiation 1826 // and the found name refers to an instance member function, otherwise 1827 // the function calling DiagnoseEmptyLookup will try to create an 1828 // implicit member call and this is wrong for default argument. 1829 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1830 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1831 return true; 1832 } 1833 1834 // Tell the callee to try to recover. 1835 return false; 1836 } 1837 1838 R.clear(); 1839 } 1840 1841 // In Microsoft mode, if we are performing lookup from within a friend 1842 // function definition declared at class scope then we must set 1843 // DC to the lexical parent to be able to search into the parent 1844 // class. 1845 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1846 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1847 DC->getLexicalParent()->isRecord()) 1848 DC = DC->getLexicalParent(); 1849 else 1850 DC = DC->getParent(); 1851 } 1852 1853 // We didn't find anything, so try to correct for a typo. 1854 TypoCorrection Corrected; 1855 if (S && Out) { 1856 SourceLocation TypoLoc = R.getNameLoc(); 1857 assert(!ExplicitTemplateArgs && 1858 "Diagnosing an empty lookup with explicit template args!"); 1859 *Out = CorrectTypoDelayed( 1860 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1861 [=](const TypoCorrection &TC) { 1862 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1863 diagnostic, diagnostic_suggest); 1864 }, 1865 nullptr, CTK_ErrorRecovery); 1866 if (*Out) 1867 return true; 1868 } else if (S && (Corrected = 1869 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1870 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1871 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1872 bool DroppedSpecifier = 1873 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1874 R.setLookupName(Corrected.getCorrection()); 1875 1876 bool AcceptableWithRecovery = false; 1877 bool AcceptableWithoutRecovery = false; 1878 NamedDecl *ND = Corrected.getFoundDecl(); 1879 if (ND) { 1880 if (Corrected.isOverloaded()) { 1881 OverloadCandidateSet OCS(R.getNameLoc(), 1882 OverloadCandidateSet::CSK_Normal); 1883 OverloadCandidateSet::iterator Best; 1884 for (NamedDecl *CD : Corrected) { 1885 if (FunctionTemplateDecl *FTD = 1886 dyn_cast<FunctionTemplateDecl>(CD)) 1887 AddTemplateOverloadCandidate( 1888 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1889 Args, OCS); 1890 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1891 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1892 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1893 Args, OCS); 1894 } 1895 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1896 case OR_Success: 1897 ND = Best->FoundDecl; 1898 Corrected.setCorrectionDecl(ND); 1899 break; 1900 default: 1901 // FIXME: Arbitrarily pick the first declaration for the note. 1902 Corrected.setCorrectionDecl(ND); 1903 break; 1904 } 1905 } 1906 R.addDecl(ND); 1907 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1908 CXXRecordDecl *Record = nullptr; 1909 if (Corrected.getCorrectionSpecifier()) { 1910 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1911 Record = Ty->getAsCXXRecordDecl(); 1912 } 1913 if (!Record) 1914 Record = cast<CXXRecordDecl>( 1915 ND->getDeclContext()->getRedeclContext()); 1916 R.setNamingClass(Record); 1917 } 1918 1919 auto *UnderlyingND = ND->getUnderlyingDecl(); 1920 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1921 isa<FunctionTemplateDecl>(UnderlyingND); 1922 // FIXME: If we ended up with a typo for a type name or 1923 // Objective-C class name, we're in trouble because the parser 1924 // is in the wrong place to recover. Suggest the typo 1925 // correction, but don't make it a fix-it since we're not going 1926 // to recover well anyway. 1927 AcceptableWithoutRecovery = 1928 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1929 } else { 1930 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1931 // because we aren't able to recover. 1932 AcceptableWithoutRecovery = true; 1933 } 1934 1935 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1936 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1937 ? diag::note_implicit_param_decl 1938 : diag::note_previous_decl; 1939 if (SS.isEmpty()) 1940 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1941 PDiag(NoteID), AcceptableWithRecovery); 1942 else 1943 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1944 << Name << computeDeclContext(SS, false) 1945 << DroppedSpecifier << SS.getRange(), 1946 PDiag(NoteID), AcceptableWithRecovery); 1947 1948 // Tell the callee whether to try to recover. 1949 return !AcceptableWithRecovery; 1950 } 1951 } 1952 R.clear(); 1953 1954 // Emit a special diagnostic for failed member lookups. 1955 // FIXME: computing the declaration context might fail here (?) 1956 if (!SS.isEmpty()) { 1957 Diag(R.getNameLoc(), diag::err_no_member) 1958 << Name << computeDeclContext(SS, false) 1959 << SS.getRange(); 1960 return true; 1961 } 1962 1963 // Give up, we can't recover. 1964 Diag(R.getNameLoc(), diagnostic) << Name; 1965 return true; 1966 } 1967 1968 /// In Microsoft mode, if we are inside a template class whose parent class has 1969 /// dependent base classes, and we can't resolve an unqualified identifier, then 1970 /// assume the identifier is a member of a dependent base class. We can only 1971 /// recover successfully in static methods, instance methods, and other contexts 1972 /// where 'this' is available. This doesn't precisely match MSVC's 1973 /// instantiation model, but it's close enough. 1974 static Expr * 1975 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1976 DeclarationNameInfo &NameInfo, 1977 SourceLocation TemplateKWLoc, 1978 const TemplateArgumentListInfo *TemplateArgs) { 1979 // Only try to recover from lookup into dependent bases in static methods or 1980 // contexts where 'this' is available. 1981 QualType ThisType = S.getCurrentThisType(); 1982 const CXXRecordDecl *RD = nullptr; 1983 if (!ThisType.isNull()) 1984 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1985 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1986 RD = MD->getParent(); 1987 if (!RD || !RD->hasAnyDependentBases()) 1988 return nullptr; 1989 1990 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1991 // is available, suggest inserting 'this->' as a fixit. 1992 SourceLocation Loc = NameInfo.getLoc(); 1993 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1994 DB << NameInfo.getName() << RD; 1995 1996 if (!ThisType.isNull()) { 1997 DB << FixItHint::CreateInsertion(Loc, "this->"); 1998 return CXXDependentScopeMemberExpr::Create( 1999 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2000 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2001 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2002 } 2003 2004 // Synthesize a fake NNS that points to the derived class. This will 2005 // perform name lookup during template instantiation. 2006 CXXScopeSpec SS; 2007 auto *NNS = 2008 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2009 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2010 return DependentScopeDeclRefExpr::Create( 2011 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2012 TemplateArgs); 2013 } 2014 2015 ExprResult 2016 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2017 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2018 bool HasTrailingLParen, bool IsAddressOfOperand, 2019 std::unique_ptr<CorrectionCandidateCallback> CCC, 2020 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2021 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2022 "cannot be direct & operand and have a trailing lparen"); 2023 if (SS.isInvalid()) 2024 return ExprError(); 2025 2026 TemplateArgumentListInfo TemplateArgsBuffer; 2027 2028 // Decompose the UnqualifiedId into the following data. 2029 DeclarationNameInfo NameInfo; 2030 const TemplateArgumentListInfo *TemplateArgs; 2031 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2032 2033 DeclarationName Name = NameInfo.getName(); 2034 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2035 SourceLocation NameLoc = NameInfo.getLoc(); 2036 2037 if (II && II->isEditorPlaceholder()) { 2038 // FIXME: When typed placeholders are supported we can create a typed 2039 // placeholder expression node. 2040 return ExprError(); 2041 } 2042 2043 // C++ [temp.dep.expr]p3: 2044 // An id-expression is type-dependent if it contains: 2045 // -- an identifier that was declared with a dependent type, 2046 // (note: handled after lookup) 2047 // -- a template-id that is dependent, 2048 // (note: handled in BuildTemplateIdExpr) 2049 // -- a conversion-function-id that specifies a dependent type, 2050 // -- a nested-name-specifier that contains a class-name that 2051 // names a dependent type. 2052 // Determine whether this is a member of an unknown specialization; 2053 // we need to handle these differently. 2054 bool DependentID = false; 2055 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2056 Name.getCXXNameType()->isDependentType()) { 2057 DependentID = true; 2058 } else if (SS.isSet()) { 2059 if (DeclContext *DC = computeDeclContext(SS, false)) { 2060 if (RequireCompleteDeclContext(SS, DC)) 2061 return ExprError(); 2062 } else { 2063 DependentID = true; 2064 } 2065 } 2066 2067 if (DependentID) 2068 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2069 IsAddressOfOperand, TemplateArgs); 2070 2071 // Perform the required lookup. 2072 LookupResult R(*this, NameInfo, 2073 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2074 ? LookupObjCImplicitSelfParam 2075 : LookupOrdinaryName); 2076 if (TemplateArgs) { 2077 // Lookup the template name again to correctly establish the context in 2078 // which it was found. This is really unfortunate as we already did the 2079 // lookup to determine that it was a template name in the first place. If 2080 // this becomes a performance hit, we can work harder to preserve those 2081 // results until we get here but it's likely not worth it. 2082 bool MemberOfUnknownSpecialization; 2083 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2084 MemberOfUnknownSpecialization); 2085 2086 if (MemberOfUnknownSpecialization || 2087 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2088 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2089 IsAddressOfOperand, TemplateArgs); 2090 } else { 2091 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2092 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2093 2094 // If the result might be in a dependent base class, this is a dependent 2095 // id-expression. 2096 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2097 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2098 IsAddressOfOperand, TemplateArgs); 2099 2100 // If this reference is in an Objective-C method, then we need to do 2101 // some special Objective-C lookup, too. 2102 if (IvarLookupFollowUp) { 2103 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2104 if (E.isInvalid()) 2105 return ExprError(); 2106 2107 if (Expr *Ex = E.getAs<Expr>()) 2108 return Ex; 2109 } 2110 } 2111 2112 if (R.isAmbiguous()) 2113 return ExprError(); 2114 2115 // This could be an implicitly declared function reference (legal in C90, 2116 // extension in C99, forbidden in C++). 2117 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2118 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2119 if (D) R.addDecl(D); 2120 } 2121 2122 // Determine whether this name might be a candidate for 2123 // argument-dependent lookup. 2124 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2125 2126 if (R.empty() && !ADL) { 2127 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2128 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2129 TemplateKWLoc, TemplateArgs)) 2130 return E; 2131 } 2132 2133 // Don't diagnose an empty lookup for inline assembly. 2134 if (IsInlineAsmIdentifier) 2135 return ExprError(); 2136 2137 // If this name wasn't predeclared and if this is not a function 2138 // call, diagnose the problem. 2139 TypoExpr *TE = nullptr; 2140 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2141 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2142 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2143 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2144 "Typo correction callback misconfigured"); 2145 if (CCC) { 2146 // Make sure the callback knows what the typo being diagnosed is. 2147 CCC->setTypoName(II); 2148 if (SS.isValid()) 2149 CCC->setTypoNNS(SS.getScopeRep()); 2150 } 2151 if (DiagnoseEmptyLookup(S, SS, R, 2152 CCC ? std::move(CCC) : std::move(DefaultValidator), 2153 nullptr, None, &TE)) { 2154 if (TE && KeywordReplacement) { 2155 auto &State = getTypoExprState(TE); 2156 auto BestTC = State.Consumer->getNextCorrection(); 2157 if (BestTC.isKeyword()) { 2158 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2159 if (State.DiagHandler) 2160 State.DiagHandler(BestTC); 2161 KeywordReplacement->startToken(); 2162 KeywordReplacement->setKind(II->getTokenID()); 2163 KeywordReplacement->setIdentifierInfo(II); 2164 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2165 // Clean up the state associated with the TypoExpr, since it has 2166 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2167 clearDelayedTypo(TE); 2168 // Signal that a correction to a keyword was performed by returning a 2169 // valid-but-null ExprResult. 2170 return (Expr*)nullptr; 2171 } 2172 State.Consumer->resetCorrectionStream(); 2173 } 2174 return TE ? TE : ExprError(); 2175 } 2176 2177 assert(!R.empty() && 2178 "DiagnoseEmptyLookup returned false but added no results"); 2179 2180 // If we found an Objective-C instance variable, let 2181 // LookupInObjCMethod build the appropriate expression to 2182 // reference the ivar. 2183 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2184 R.clear(); 2185 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2186 // In a hopelessly buggy code, Objective-C instance variable 2187 // lookup fails and no expression will be built to reference it. 2188 if (!E.isInvalid() && !E.get()) 2189 return ExprError(); 2190 return E; 2191 } 2192 } 2193 2194 // This is guaranteed from this point on. 2195 assert(!R.empty() || ADL); 2196 2197 // Check whether this might be a C++ implicit instance member access. 2198 // C++ [class.mfct.non-static]p3: 2199 // When an id-expression that is not part of a class member access 2200 // syntax and not used to form a pointer to member is used in the 2201 // body of a non-static member function of class X, if name lookup 2202 // resolves the name in the id-expression to a non-static non-type 2203 // member of some class C, the id-expression is transformed into a 2204 // class member access expression using (*this) as the 2205 // postfix-expression to the left of the . operator. 2206 // 2207 // But we don't actually need to do this for '&' operands if R 2208 // resolved to a function or overloaded function set, because the 2209 // expression is ill-formed if it actually works out to be a 2210 // non-static member function: 2211 // 2212 // C++ [expr.ref]p4: 2213 // Otherwise, if E1.E2 refers to a non-static member function. . . 2214 // [t]he expression can be used only as the left-hand operand of a 2215 // member function call. 2216 // 2217 // There are other safeguards against such uses, but it's important 2218 // to get this right here so that we don't end up making a 2219 // spuriously dependent expression if we're inside a dependent 2220 // instance method. 2221 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2222 bool MightBeImplicitMember; 2223 if (!IsAddressOfOperand) 2224 MightBeImplicitMember = true; 2225 else if (!SS.isEmpty()) 2226 MightBeImplicitMember = false; 2227 else if (R.isOverloadedResult()) 2228 MightBeImplicitMember = false; 2229 else if (R.isUnresolvableResult()) 2230 MightBeImplicitMember = true; 2231 else 2232 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2233 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2234 isa<MSPropertyDecl>(R.getFoundDecl()); 2235 2236 if (MightBeImplicitMember) 2237 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2238 R, TemplateArgs, S); 2239 } 2240 2241 if (TemplateArgs || TemplateKWLoc.isValid()) { 2242 2243 // In C++1y, if this is a variable template id, then check it 2244 // in BuildTemplateIdExpr(). 2245 // The single lookup result must be a variable template declaration. 2246 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2247 Id.TemplateId->Kind == TNK_Var_template) { 2248 assert(R.getAsSingle<VarTemplateDecl>() && 2249 "There should only be one declaration found."); 2250 } 2251 2252 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2253 } 2254 2255 return BuildDeclarationNameExpr(SS, R, ADL); 2256 } 2257 2258 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2259 /// declaration name, generally during template instantiation. 2260 /// There's a large number of things which don't need to be done along 2261 /// this path. 2262 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2263 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2264 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2265 DeclContext *DC = computeDeclContext(SS, false); 2266 if (!DC) 2267 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2268 NameInfo, /*TemplateArgs=*/nullptr); 2269 2270 if (RequireCompleteDeclContext(SS, DC)) 2271 return ExprError(); 2272 2273 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2274 LookupQualifiedName(R, DC); 2275 2276 if (R.isAmbiguous()) 2277 return ExprError(); 2278 2279 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2280 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2281 NameInfo, /*TemplateArgs=*/nullptr); 2282 2283 if (R.empty()) { 2284 Diag(NameInfo.getLoc(), diag::err_no_member) 2285 << NameInfo.getName() << DC << SS.getRange(); 2286 return ExprError(); 2287 } 2288 2289 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2290 // Diagnose a missing typename if this resolved unambiguously to a type in 2291 // a dependent context. If we can recover with a type, downgrade this to 2292 // a warning in Microsoft compatibility mode. 2293 unsigned DiagID = diag::err_typename_missing; 2294 if (RecoveryTSI && getLangOpts().MSVCCompat) 2295 DiagID = diag::ext_typename_missing; 2296 SourceLocation Loc = SS.getBeginLoc(); 2297 auto D = Diag(Loc, DiagID); 2298 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2299 << SourceRange(Loc, NameInfo.getEndLoc()); 2300 2301 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2302 // context. 2303 if (!RecoveryTSI) 2304 return ExprError(); 2305 2306 // Only issue the fixit if we're prepared to recover. 2307 D << FixItHint::CreateInsertion(Loc, "typename "); 2308 2309 // Recover by pretending this was an elaborated type. 2310 QualType Ty = Context.getTypeDeclType(TD); 2311 TypeLocBuilder TLB; 2312 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2313 2314 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2315 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2316 QTL.setElaboratedKeywordLoc(SourceLocation()); 2317 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2318 2319 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2320 2321 return ExprEmpty(); 2322 } 2323 2324 // Defend against this resolving to an implicit member access. We usually 2325 // won't get here if this might be a legitimate a class member (we end up in 2326 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2327 // a pointer-to-member or in an unevaluated context in C++11. 2328 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2329 return BuildPossibleImplicitMemberExpr(SS, 2330 /*TemplateKWLoc=*/SourceLocation(), 2331 R, /*TemplateArgs=*/nullptr, S); 2332 2333 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2334 } 2335 2336 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2337 /// detected that we're currently inside an ObjC method. Perform some 2338 /// additional lookup. 2339 /// 2340 /// Ideally, most of this would be done by lookup, but there's 2341 /// actually quite a lot of extra work involved. 2342 /// 2343 /// Returns a null sentinel to indicate trivial success. 2344 ExprResult 2345 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2346 IdentifierInfo *II, bool AllowBuiltinCreation) { 2347 SourceLocation Loc = Lookup.getNameLoc(); 2348 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2349 2350 // Check for error condition which is already reported. 2351 if (!CurMethod) 2352 return ExprError(); 2353 2354 // There are two cases to handle here. 1) scoped lookup could have failed, 2355 // in which case we should look for an ivar. 2) scoped lookup could have 2356 // found a decl, but that decl is outside the current instance method (i.e. 2357 // a global variable). In these two cases, we do a lookup for an ivar with 2358 // this name, if the lookup sucedes, we replace it our current decl. 2359 2360 // If we're in a class method, we don't normally want to look for 2361 // ivars. But if we don't find anything else, and there's an 2362 // ivar, that's an error. 2363 bool IsClassMethod = CurMethod->isClassMethod(); 2364 2365 bool LookForIvars; 2366 if (Lookup.empty()) 2367 LookForIvars = true; 2368 else if (IsClassMethod) 2369 LookForIvars = false; 2370 else 2371 LookForIvars = (Lookup.isSingleResult() && 2372 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2373 ObjCInterfaceDecl *IFace = nullptr; 2374 if (LookForIvars) { 2375 IFace = CurMethod->getClassInterface(); 2376 ObjCInterfaceDecl *ClassDeclared; 2377 ObjCIvarDecl *IV = nullptr; 2378 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2379 // Diagnose using an ivar in a class method. 2380 if (IsClassMethod) 2381 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2382 << IV->getDeclName()); 2383 2384 // If we're referencing an invalid decl, just return this as a silent 2385 // error node. The error diagnostic was already emitted on the decl. 2386 if (IV->isInvalidDecl()) 2387 return ExprError(); 2388 2389 // Check if referencing a field with __attribute__((deprecated)). 2390 if (DiagnoseUseOfDecl(IV, Loc)) 2391 return ExprError(); 2392 2393 // Diagnose the use of an ivar outside of the declaring class. 2394 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2395 !declaresSameEntity(ClassDeclared, IFace) && 2396 !getLangOpts().DebuggerSupport) 2397 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2398 2399 // FIXME: This should use a new expr for a direct reference, don't 2400 // turn this into Self->ivar, just return a BareIVarExpr or something. 2401 IdentifierInfo &II = Context.Idents.get("self"); 2402 UnqualifiedId SelfName; 2403 SelfName.setIdentifier(&II, SourceLocation()); 2404 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2405 CXXScopeSpec SelfScopeSpec; 2406 SourceLocation TemplateKWLoc; 2407 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2408 SelfName, false, false); 2409 if (SelfExpr.isInvalid()) 2410 return ExprError(); 2411 2412 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2413 if (SelfExpr.isInvalid()) 2414 return ExprError(); 2415 2416 MarkAnyDeclReferenced(Loc, IV, true); 2417 2418 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2419 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2420 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2421 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2422 2423 ObjCIvarRefExpr *Result = new (Context) 2424 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2425 IV->getLocation(), SelfExpr.get(), true, true); 2426 2427 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2428 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2429 recordUseOfEvaluatedWeak(Result); 2430 } 2431 if (getLangOpts().ObjCAutoRefCount) { 2432 if (CurContext->isClosure()) 2433 Diag(Loc, diag::warn_implicitly_retains_self) 2434 << FixItHint::CreateInsertion(Loc, "self->"); 2435 } 2436 2437 return Result; 2438 } 2439 } else if (CurMethod->isInstanceMethod()) { 2440 // We should warn if a local variable hides an ivar. 2441 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2442 ObjCInterfaceDecl *ClassDeclared; 2443 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2444 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2445 declaresSameEntity(IFace, ClassDeclared)) 2446 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2447 } 2448 } 2449 } else if (Lookup.isSingleResult() && 2450 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2451 // If accessing a stand-alone ivar in a class method, this is an error. 2452 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2453 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2454 << IV->getDeclName()); 2455 } 2456 2457 if (Lookup.empty() && II && AllowBuiltinCreation) { 2458 // FIXME. Consolidate this with similar code in LookupName. 2459 if (unsigned BuiltinID = II->getBuiltinID()) { 2460 if (!(getLangOpts().CPlusPlus && 2461 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2462 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2463 S, Lookup.isForRedeclaration(), 2464 Lookup.getNameLoc()); 2465 if (D) Lookup.addDecl(D); 2466 } 2467 } 2468 } 2469 // Sentinel value saying that we didn't do anything special. 2470 return ExprResult((Expr *)nullptr); 2471 } 2472 2473 /// \brief Cast a base object to a member's actual type. 2474 /// 2475 /// Logically this happens in three phases: 2476 /// 2477 /// * First we cast from the base type to the naming class. 2478 /// The naming class is the class into which we were looking 2479 /// when we found the member; it's the qualifier type if a 2480 /// qualifier was provided, and otherwise it's the base type. 2481 /// 2482 /// * Next we cast from the naming class to the declaring class. 2483 /// If the member we found was brought into a class's scope by 2484 /// a using declaration, this is that class; otherwise it's 2485 /// the class declaring the member. 2486 /// 2487 /// * Finally we cast from the declaring class to the "true" 2488 /// declaring class of the member. This conversion does not 2489 /// obey access control. 2490 ExprResult 2491 Sema::PerformObjectMemberConversion(Expr *From, 2492 NestedNameSpecifier *Qualifier, 2493 NamedDecl *FoundDecl, 2494 NamedDecl *Member) { 2495 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2496 if (!RD) 2497 return From; 2498 2499 QualType DestRecordType; 2500 QualType DestType; 2501 QualType FromRecordType; 2502 QualType FromType = From->getType(); 2503 bool PointerConversions = false; 2504 if (isa<FieldDecl>(Member)) { 2505 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2506 2507 if (FromType->getAs<PointerType>()) { 2508 DestType = Context.getPointerType(DestRecordType); 2509 FromRecordType = FromType->getPointeeType(); 2510 PointerConversions = true; 2511 } else { 2512 DestType = DestRecordType; 2513 FromRecordType = FromType; 2514 } 2515 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2516 if (Method->isStatic()) 2517 return From; 2518 2519 DestType = Method->getThisType(Context); 2520 DestRecordType = DestType->getPointeeType(); 2521 2522 if (FromType->getAs<PointerType>()) { 2523 FromRecordType = FromType->getPointeeType(); 2524 PointerConversions = true; 2525 } else { 2526 FromRecordType = FromType; 2527 DestType = DestRecordType; 2528 } 2529 } else { 2530 // No conversion necessary. 2531 return From; 2532 } 2533 2534 if (DestType->isDependentType() || FromType->isDependentType()) 2535 return From; 2536 2537 // If the unqualified types are the same, no conversion is necessary. 2538 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2539 return From; 2540 2541 SourceRange FromRange = From->getSourceRange(); 2542 SourceLocation FromLoc = FromRange.getBegin(); 2543 2544 ExprValueKind VK = From->getValueKind(); 2545 2546 // C++ [class.member.lookup]p8: 2547 // [...] Ambiguities can often be resolved by qualifying a name with its 2548 // class name. 2549 // 2550 // If the member was a qualified name and the qualified referred to a 2551 // specific base subobject type, we'll cast to that intermediate type 2552 // first and then to the object in which the member is declared. That allows 2553 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2554 // 2555 // class Base { public: int x; }; 2556 // class Derived1 : public Base { }; 2557 // class Derived2 : public Base { }; 2558 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2559 // 2560 // void VeryDerived::f() { 2561 // x = 17; // error: ambiguous base subobjects 2562 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2563 // } 2564 if (Qualifier && Qualifier->getAsType()) { 2565 QualType QType = QualType(Qualifier->getAsType(), 0); 2566 assert(QType->isRecordType() && "lookup done with non-record type"); 2567 2568 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2569 2570 // In C++98, the qualifier type doesn't actually have to be a base 2571 // type of the object type, in which case we just ignore it. 2572 // Otherwise build the appropriate casts. 2573 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2574 CXXCastPath BasePath; 2575 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2576 FromLoc, FromRange, &BasePath)) 2577 return ExprError(); 2578 2579 if (PointerConversions) 2580 QType = Context.getPointerType(QType); 2581 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2582 VK, &BasePath).get(); 2583 2584 FromType = QType; 2585 FromRecordType = QRecordType; 2586 2587 // If the qualifier type was the same as the destination type, 2588 // we're done. 2589 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2590 return From; 2591 } 2592 } 2593 2594 bool IgnoreAccess = false; 2595 2596 // If we actually found the member through a using declaration, cast 2597 // down to the using declaration's type. 2598 // 2599 // Pointer equality is fine here because only one declaration of a 2600 // class ever has member declarations. 2601 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2602 assert(isa<UsingShadowDecl>(FoundDecl)); 2603 QualType URecordType = Context.getTypeDeclType( 2604 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2605 2606 // We only need to do this if the naming-class to declaring-class 2607 // conversion is non-trivial. 2608 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2609 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2610 CXXCastPath BasePath; 2611 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2612 FromLoc, FromRange, &BasePath)) 2613 return ExprError(); 2614 2615 QualType UType = URecordType; 2616 if (PointerConversions) 2617 UType = Context.getPointerType(UType); 2618 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2619 VK, &BasePath).get(); 2620 FromType = UType; 2621 FromRecordType = URecordType; 2622 } 2623 2624 // We don't do access control for the conversion from the 2625 // declaring class to the true declaring class. 2626 IgnoreAccess = true; 2627 } 2628 2629 CXXCastPath BasePath; 2630 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2631 FromLoc, FromRange, &BasePath, 2632 IgnoreAccess)) 2633 return ExprError(); 2634 2635 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2636 VK, &BasePath); 2637 } 2638 2639 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2640 const LookupResult &R, 2641 bool HasTrailingLParen) { 2642 // Only when used directly as the postfix-expression of a call. 2643 if (!HasTrailingLParen) 2644 return false; 2645 2646 // Never if a scope specifier was provided. 2647 if (SS.isSet()) 2648 return false; 2649 2650 // Only in C++ or ObjC++. 2651 if (!getLangOpts().CPlusPlus) 2652 return false; 2653 2654 // Turn off ADL when we find certain kinds of declarations during 2655 // normal lookup: 2656 for (NamedDecl *D : R) { 2657 // C++0x [basic.lookup.argdep]p3: 2658 // -- a declaration of a class member 2659 // Since using decls preserve this property, we check this on the 2660 // original decl. 2661 if (D->isCXXClassMember()) 2662 return false; 2663 2664 // C++0x [basic.lookup.argdep]p3: 2665 // -- a block-scope function declaration that is not a 2666 // using-declaration 2667 // NOTE: we also trigger this for function templates (in fact, we 2668 // don't check the decl type at all, since all other decl types 2669 // turn off ADL anyway). 2670 if (isa<UsingShadowDecl>(D)) 2671 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2672 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2673 return false; 2674 2675 // C++0x [basic.lookup.argdep]p3: 2676 // -- a declaration that is neither a function or a function 2677 // template 2678 // And also for builtin functions. 2679 if (isa<FunctionDecl>(D)) { 2680 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2681 2682 // But also builtin functions. 2683 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2684 return false; 2685 } else if (!isa<FunctionTemplateDecl>(D)) 2686 return false; 2687 } 2688 2689 return true; 2690 } 2691 2692 2693 /// Diagnoses obvious problems with the use of the given declaration 2694 /// as an expression. This is only actually called for lookups that 2695 /// were not overloaded, and it doesn't promise that the declaration 2696 /// will in fact be used. 2697 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2698 if (D->isInvalidDecl()) 2699 return true; 2700 2701 if (isa<TypedefNameDecl>(D)) { 2702 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2703 return true; 2704 } 2705 2706 if (isa<ObjCInterfaceDecl>(D)) { 2707 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2708 return true; 2709 } 2710 2711 if (isa<NamespaceDecl>(D)) { 2712 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2713 return true; 2714 } 2715 2716 return false; 2717 } 2718 2719 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2720 LookupResult &R, bool NeedsADL, 2721 bool AcceptInvalidDecl) { 2722 // If this is a single, fully-resolved result and we don't need ADL, 2723 // just build an ordinary singleton decl ref. 2724 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2725 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2726 R.getRepresentativeDecl(), nullptr, 2727 AcceptInvalidDecl); 2728 2729 // We only need to check the declaration if there's exactly one 2730 // result, because in the overloaded case the results can only be 2731 // functions and function templates. 2732 if (R.isSingleResult() && 2733 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2734 return ExprError(); 2735 2736 // Otherwise, just build an unresolved lookup expression. Suppress 2737 // any lookup-related diagnostics; we'll hash these out later, when 2738 // we've picked a target. 2739 R.suppressDiagnostics(); 2740 2741 UnresolvedLookupExpr *ULE 2742 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2743 SS.getWithLocInContext(Context), 2744 R.getLookupNameInfo(), 2745 NeedsADL, R.isOverloadedResult(), 2746 R.begin(), R.end()); 2747 2748 return ULE; 2749 } 2750 2751 static void 2752 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2753 ValueDecl *var, DeclContext *DC); 2754 2755 /// \brief Complete semantic analysis for a reference to the given declaration. 2756 ExprResult Sema::BuildDeclarationNameExpr( 2757 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2758 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2759 bool AcceptInvalidDecl) { 2760 assert(D && "Cannot refer to a NULL declaration"); 2761 assert(!isa<FunctionTemplateDecl>(D) && 2762 "Cannot refer unambiguously to a function template"); 2763 2764 SourceLocation Loc = NameInfo.getLoc(); 2765 if (CheckDeclInExpr(*this, Loc, D)) 2766 return ExprError(); 2767 2768 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2769 // Specifically diagnose references to class templates that are missing 2770 // a template argument list. 2771 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2772 << Template << SS.getRange(); 2773 Diag(Template->getLocation(), diag::note_template_decl_here); 2774 return ExprError(); 2775 } 2776 2777 // Make sure that we're referring to a value. 2778 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2779 if (!VD) { 2780 Diag(Loc, diag::err_ref_non_value) 2781 << D << SS.getRange(); 2782 Diag(D->getLocation(), diag::note_declared_at); 2783 return ExprError(); 2784 } 2785 2786 // Check whether this declaration can be used. Note that we suppress 2787 // this check when we're going to perform argument-dependent lookup 2788 // on this function name, because this might not be the function 2789 // that overload resolution actually selects. 2790 if (DiagnoseUseOfDecl(VD, Loc)) 2791 return ExprError(); 2792 2793 // Only create DeclRefExpr's for valid Decl's. 2794 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2795 return ExprError(); 2796 2797 // Handle members of anonymous structs and unions. If we got here, 2798 // and the reference is to a class member indirect field, then this 2799 // must be the subject of a pointer-to-member expression. 2800 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2801 if (!indirectField->isCXXClassMember()) 2802 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2803 indirectField); 2804 2805 { 2806 QualType type = VD->getType(); 2807 if (type.isNull()) 2808 return ExprError(); 2809 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2810 // C++ [except.spec]p17: 2811 // An exception-specification is considered to be needed when: 2812 // - in an expression, the function is the unique lookup result or 2813 // the selected member of a set of overloaded functions. 2814 ResolveExceptionSpec(Loc, FPT); 2815 type = VD->getType(); 2816 } 2817 ExprValueKind valueKind = VK_RValue; 2818 2819 switch (D->getKind()) { 2820 // Ignore all the non-ValueDecl kinds. 2821 #define ABSTRACT_DECL(kind) 2822 #define VALUE(type, base) 2823 #define DECL(type, base) \ 2824 case Decl::type: 2825 #include "clang/AST/DeclNodes.inc" 2826 llvm_unreachable("invalid value decl kind"); 2827 2828 // These shouldn't make it here. 2829 case Decl::ObjCAtDefsField: 2830 case Decl::ObjCIvar: 2831 llvm_unreachable("forming non-member reference to ivar?"); 2832 2833 // Enum constants are always r-values and never references. 2834 // Unresolved using declarations are dependent. 2835 case Decl::EnumConstant: 2836 case Decl::UnresolvedUsingValue: 2837 case Decl::OMPDeclareReduction: 2838 valueKind = VK_RValue; 2839 break; 2840 2841 // Fields and indirect fields that got here must be for 2842 // pointer-to-member expressions; we just call them l-values for 2843 // internal consistency, because this subexpression doesn't really 2844 // exist in the high-level semantics. 2845 case Decl::Field: 2846 case Decl::IndirectField: 2847 assert(getLangOpts().CPlusPlus && 2848 "building reference to field in C?"); 2849 2850 // These can't have reference type in well-formed programs, but 2851 // for internal consistency we do this anyway. 2852 type = type.getNonReferenceType(); 2853 valueKind = VK_LValue; 2854 break; 2855 2856 // Non-type template parameters are either l-values or r-values 2857 // depending on the type. 2858 case Decl::NonTypeTemplateParm: { 2859 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2860 type = reftype->getPointeeType(); 2861 valueKind = VK_LValue; // even if the parameter is an r-value reference 2862 break; 2863 } 2864 2865 // For non-references, we need to strip qualifiers just in case 2866 // the template parameter was declared as 'const int' or whatever. 2867 valueKind = VK_RValue; 2868 type = type.getUnqualifiedType(); 2869 break; 2870 } 2871 2872 case Decl::Var: 2873 case Decl::VarTemplateSpecialization: 2874 case Decl::VarTemplatePartialSpecialization: 2875 case Decl::Decomposition: 2876 case Decl::OMPCapturedExpr: 2877 // In C, "extern void blah;" is valid and is an r-value. 2878 if (!getLangOpts().CPlusPlus && 2879 !type.hasQualifiers() && 2880 type->isVoidType()) { 2881 valueKind = VK_RValue; 2882 break; 2883 } 2884 LLVM_FALLTHROUGH; 2885 2886 case Decl::ImplicitParam: 2887 case Decl::ParmVar: { 2888 // These are always l-values. 2889 valueKind = VK_LValue; 2890 type = type.getNonReferenceType(); 2891 2892 // FIXME: Does the addition of const really only apply in 2893 // potentially-evaluated contexts? Since the variable isn't actually 2894 // captured in an unevaluated context, it seems that the answer is no. 2895 if (!isUnevaluatedContext()) { 2896 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2897 if (!CapturedType.isNull()) 2898 type = CapturedType; 2899 } 2900 2901 break; 2902 } 2903 2904 case Decl::Binding: { 2905 // These are always lvalues. 2906 valueKind = VK_LValue; 2907 type = type.getNonReferenceType(); 2908 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2909 // decides how that's supposed to work. 2910 auto *BD = cast<BindingDecl>(VD); 2911 if (BD->getDeclContext()->isFunctionOrMethod() && 2912 BD->getDeclContext() != CurContext) 2913 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2914 break; 2915 } 2916 2917 case Decl::Function: { 2918 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2919 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2920 type = Context.BuiltinFnTy; 2921 valueKind = VK_RValue; 2922 break; 2923 } 2924 } 2925 2926 const FunctionType *fty = type->castAs<FunctionType>(); 2927 2928 // If we're referring to a function with an __unknown_anytype 2929 // result type, make the entire expression __unknown_anytype. 2930 if (fty->getReturnType() == Context.UnknownAnyTy) { 2931 type = Context.UnknownAnyTy; 2932 valueKind = VK_RValue; 2933 break; 2934 } 2935 2936 // Functions are l-values in C++. 2937 if (getLangOpts().CPlusPlus) { 2938 valueKind = VK_LValue; 2939 break; 2940 } 2941 2942 // C99 DR 316 says that, if a function type comes from a 2943 // function definition (without a prototype), that type is only 2944 // used for checking compatibility. Therefore, when referencing 2945 // the function, we pretend that we don't have the full function 2946 // type. 2947 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2948 isa<FunctionProtoType>(fty)) 2949 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2950 fty->getExtInfo()); 2951 2952 // Functions are r-values in C. 2953 valueKind = VK_RValue; 2954 break; 2955 } 2956 2957 case Decl::CXXDeductionGuide: 2958 llvm_unreachable("building reference to deduction guide"); 2959 2960 case Decl::MSProperty: 2961 valueKind = VK_LValue; 2962 break; 2963 2964 case Decl::CXXMethod: 2965 // If we're referring to a method with an __unknown_anytype 2966 // result type, make the entire expression __unknown_anytype. 2967 // This should only be possible with a type written directly. 2968 if (const FunctionProtoType *proto 2969 = dyn_cast<FunctionProtoType>(VD->getType())) 2970 if (proto->getReturnType() == Context.UnknownAnyTy) { 2971 type = Context.UnknownAnyTy; 2972 valueKind = VK_RValue; 2973 break; 2974 } 2975 2976 // C++ methods are l-values if static, r-values if non-static. 2977 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2978 valueKind = VK_LValue; 2979 break; 2980 } 2981 LLVM_FALLTHROUGH; 2982 2983 case Decl::CXXConversion: 2984 case Decl::CXXDestructor: 2985 case Decl::CXXConstructor: 2986 valueKind = VK_RValue; 2987 break; 2988 } 2989 2990 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2991 TemplateArgs); 2992 } 2993 } 2994 2995 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2996 SmallString<32> &Target) { 2997 Target.resize(CharByteWidth * (Source.size() + 1)); 2998 char *ResultPtr = &Target[0]; 2999 const llvm::UTF8 *ErrorPtr; 3000 bool success = 3001 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3002 (void)success; 3003 assert(success); 3004 Target.resize(ResultPtr - &Target[0]); 3005 } 3006 3007 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3008 PredefinedExpr::IdentType IT) { 3009 // Pick the current block, lambda, captured statement or function. 3010 Decl *currentDecl = nullptr; 3011 if (const BlockScopeInfo *BSI = getCurBlock()) 3012 currentDecl = BSI->TheDecl; 3013 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3014 currentDecl = LSI->CallOperator; 3015 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3016 currentDecl = CSI->TheCapturedDecl; 3017 else 3018 currentDecl = getCurFunctionOrMethodDecl(); 3019 3020 if (!currentDecl) { 3021 Diag(Loc, diag::ext_predef_outside_function); 3022 currentDecl = Context.getTranslationUnitDecl(); 3023 } 3024 3025 QualType ResTy; 3026 StringLiteral *SL = nullptr; 3027 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3028 ResTy = Context.DependentTy; 3029 else { 3030 // Pre-defined identifiers are of type char[x], where x is the length of 3031 // the string. 3032 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3033 unsigned Length = Str.length(); 3034 3035 llvm::APInt LengthI(32, Length + 1); 3036 if (IT == PredefinedExpr::LFunction) { 3037 ResTy = Context.WideCharTy.withConst(); 3038 SmallString<32> RawChars; 3039 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3040 Str, RawChars); 3041 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3042 /*IndexTypeQuals*/ 0); 3043 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3044 /*Pascal*/ false, ResTy, Loc); 3045 } else { 3046 ResTy = Context.CharTy.withConst(); 3047 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3048 /*IndexTypeQuals*/ 0); 3049 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3050 /*Pascal*/ false, ResTy, Loc); 3051 } 3052 } 3053 3054 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3055 } 3056 3057 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3058 PredefinedExpr::IdentType IT; 3059 3060 switch (Kind) { 3061 default: llvm_unreachable("Unknown simple primary expr!"); 3062 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3063 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3064 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3065 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3066 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3067 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3068 } 3069 3070 return BuildPredefinedExpr(Loc, IT); 3071 } 3072 3073 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3074 SmallString<16> CharBuffer; 3075 bool Invalid = false; 3076 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3077 if (Invalid) 3078 return ExprError(); 3079 3080 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3081 PP, Tok.getKind()); 3082 if (Literal.hadError()) 3083 return ExprError(); 3084 3085 QualType Ty; 3086 if (Literal.isWide()) 3087 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3088 else if (Literal.isUTF16()) 3089 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3090 else if (Literal.isUTF32()) 3091 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3092 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3093 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3094 else 3095 Ty = Context.CharTy; // 'x' -> char in C++ 3096 3097 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3098 if (Literal.isWide()) 3099 Kind = CharacterLiteral::Wide; 3100 else if (Literal.isUTF16()) 3101 Kind = CharacterLiteral::UTF16; 3102 else if (Literal.isUTF32()) 3103 Kind = CharacterLiteral::UTF32; 3104 else if (Literal.isUTF8()) 3105 Kind = CharacterLiteral::UTF8; 3106 3107 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3108 Tok.getLocation()); 3109 3110 if (Literal.getUDSuffix().empty()) 3111 return Lit; 3112 3113 // We're building a user-defined literal. 3114 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3115 SourceLocation UDSuffixLoc = 3116 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3117 3118 // Make sure we're allowed user-defined literals here. 3119 if (!UDLScope) 3120 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3121 3122 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3123 // operator "" X (ch) 3124 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3125 Lit, Tok.getLocation()); 3126 } 3127 3128 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3129 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3130 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3131 Context.IntTy, Loc); 3132 } 3133 3134 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3135 QualType Ty, SourceLocation Loc) { 3136 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3137 3138 using llvm::APFloat; 3139 APFloat Val(Format); 3140 3141 APFloat::opStatus result = Literal.GetFloatValue(Val); 3142 3143 // Overflow is always an error, but underflow is only an error if 3144 // we underflowed to zero (APFloat reports denormals as underflow). 3145 if ((result & APFloat::opOverflow) || 3146 ((result & APFloat::opUnderflow) && Val.isZero())) { 3147 unsigned diagnostic; 3148 SmallString<20> buffer; 3149 if (result & APFloat::opOverflow) { 3150 diagnostic = diag::warn_float_overflow; 3151 APFloat::getLargest(Format).toString(buffer); 3152 } else { 3153 diagnostic = diag::warn_float_underflow; 3154 APFloat::getSmallest(Format).toString(buffer); 3155 } 3156 3157 S.Diag(Loc, diagnostic) 3158 << Ty 3159 << StringRef(buffer.data(), buffer.size()); 3160 } 3161 3162 bool isExact = (result == APFloat::opOK); 3163 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3164 } 3165 3166 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3167 assert(E && "Invalid expression"); 3168 3169 if (E->isValueDependent()) 3170 return false; 3171 3172 QualType QT = E->getType(); 3173 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3174 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3175 return true; 3176 } 3177 3178 llvm::APSInt ValueAPS; 3179 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3180 3181 if (R.isInvalid()) 3182 return true; 3183 3184 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3185 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3186 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3187 << ValueAPS.toString(10) << ValueIsPositive; 3188 return true; 3189 } 3190 3191 return false; 3192 } 3193 3194 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3195 // Fast path for a single digit (which is quite common). A single digit 3196 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3197 if (Tok.getLength() == 1) { 3198 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3199 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3200 } 3201 3202 SmallString<128> SpellingBuffer; 3203 // NumericLiteralParser wants to overread by one character. Add padding to 3204 // the buffer in case the token is copied to the buffer. If getSpelling() 3205 // returns a StringRef to the memory buffer, it should have a null char at 3206 // the EOF, so it is also safe. 3207 SpellingBuffer.resize(Tok.getLength() + 1); 3208 3209 // Get the spelling of the token, which eliminates trigraphs, etc. 3210 bool Invalid = false; 3211 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3212 if (Invalid) 3213 return ExprError(); 3214 3215 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3216 if (Literal.hadError) 3217 return ExprError(); 3218 3219 if (Literal.hasUDSuffix()) { 3220 // We're building a user-defined literal. 3221 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3222 SourceLocation UDSuffixLoc = 3223 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3224 3225 // Make sure we're allowed user-defined literals here. 3226 if (!UDLScope) 3227 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3228 3229 QualType CookedTy; 3230 if (Literal.isFloatingLiteral()) { 3231 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3232 // long double, the literal is treated as a call of the form 3233 // operator "" X (f L) 3234 CookedTy = Context.LongDoubleTy; 3235 } else { 3236 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3237 // unsigned long long, the literal is treated as a call of the form 3238 // operator "" X (n ULL) 3239 CookedTy = Context.UnsignedLongLongTy; 3240 } 3241 3242 DeclarationName OpName = 3243 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3244 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3245 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3246 3247 SourceLocation TokLoc = Tok.getLocation(); 3248 3249 // Perform literal operator lookup to determine if we're building a raw 3250 // literal or a cooked one. 3251 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3252 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3253 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3254 /*AllowStringTemplate*/ false, 3255 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3256 case LOLR_ErrorNoDiagnostic: 3257 // Lookup failure for imaginary constants isn't fatal, there's still the 3258 // GNU extension producing _Complex types. 3259 break; 3260 case LOLR_Error: 3261 return ExprError(); 3262 case LOLR_Cooked: { 3263 Expr *Lit; 3264 if (Literal.isFloatingLiteral()) { 3265 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3266 } else { 3267 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3268 if (Literal.GetIntegerValue(ResultVal)) 3269 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3270 << /* Unsigned */ 1; 3271 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3272 Tok.getLocation()); 3273 } 3274 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3275 } 3276 3277 case LOLR_Raw: { 3278 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3279 // literal is treated as a call of the form 3280 // operator "" X ("n") 3281 unsigned Length = Literal.getUDSuffixOffset(); 3282 QualType StrTy = Context.getConstantArrayType( 3283 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3284 ArrayType::Normal, 0); 3285 Expr *Lit = StringLiteral::Create( 3286 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3287 /*Pascal*/false, StrTy, &TokLoc, 1); 3288 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3289 } 3290 3291 case LOLR_Template: { 3292 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3293 // template), L is treated as a call fo the form 3294 // operator "" X <'c1', 'c2', ... 'ck'>() 3295 // where n is the source character sequence c1 c2 ... ck. 3296 TemplateArgumentListInfo ExplicitArgs; 3297 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3298 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3299 llvm::APSInt Value(CharBits, CharIsUnsigned); 3300 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3301 Value = TokSpelling[I]; 3302 TemplateArgument Arg(Context, Value, Context.CharTy); 3303 TemplateArgumentLocInfo ArgInfo; 3304 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3305 } 3306 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3307 &ExplicitArgs); 3308 } 3309 case LOLR_StringTemplate: 3310 llvm_unreachable("unexpected literal operator lookup result"); 3311 } 3312 } 3313 3314 Expr *Res; 3315 3316 if (Literal.isFloatingLiteral()) { 3317 QualType Ty; 3318 if (Literal.isHalf){ 3319 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3320 Ty = Context.HalfTy; 3321 else { 3322 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3323 return ExprError(); 3324 } 3325 } else if (Literal.isFloat) 3326 Ty = Context.FloatTy; 3327 else if (Literal.isLong) 3328 Ty = Context.LongDoubleTy; 3329 else if (Literal.isFloat16) 3330 Ty = Context.Float16Ty; 3331 else if (Literal.isFloat128) 3332 Ty = Context.Float128Ty; 3333 else 3334 Ty = Context.DoubleTy; 3335 3336 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3337 3338 if (Ty == Context.DoubleTy) { 3339 if (getLangOpts().SinglePrecisionConstants) { 3340 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3341 if (BTy->getKind() != BuiltinType::Float) { 3342 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3343 } 3344 } else if (getLangOpts().OpenCL && 3345 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3346 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3347 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3348 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3349 } 3350 } 3351 } else if (!Literal.isIntegerLiteral()) { 3352 return ExprError(); 3353 } else { 3354 QualType Ty; 3355 3356 // 'long long' is a C99 or C++11 feature. 3357 if (!getLangOpts().C99 && Literal.isLongLong) { 3358 if (getLangOpts().CPlusPlus) 3359 Diag(Tok.getLocation(), 3360 getLangOpts().CPlusPlus11 ? 3361 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3362 else 3363 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3364 } 3365 3366 // Get the value in the widest-possible width. 3367 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3368 llvm::APInt ResultVal(MaxWidth, 0); 3369 3370 if (Literal.GetIntegerValue(ResultVal)) { 3371 // If this value didn't fit into uintmax_t, error and force to ull. 3372 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3373 << /* Unsigned */ 1; 3374 Ty = Context.UnsignedLongLongTy; 3375 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3376 "long long is not intmax_t?"); 3377 } else { 3378 // If this value fits into a ULL, try to figure out what else it fits into 3379 // according to the rules of C99 6.4.4.1p5. 3380 3381 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3382 // be an unsigned int. 3383 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3384 3385 // Check from smallest to largest, picking the smallest type we can. 3386 unsigned Width = 0; 3387 3388 // Microsoft specific integer suffixes are explicitly sized. 3389 if (Literal.MicrosoftInteger) { 3390 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3391 Width = 8; 3392 Ty = Context.CharTy; 3393 } else { 3394 Width = Literal.MicrosoftInteger; 3395 Ty = Context.getIntTypeForBitwidth(Width, 3396 /*Signed=*/!Literal.isUnsigned); 3397 } 3398 } 3399 3400 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3401 // Are int/unsigned possibilities? 3402 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3403 3404 // Does it fit in a unsigned int? 3405 if (ResultVal.isIntN(IntSize)) { 3406 // Does it fit in a signed int? 3407 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3408 Ty = Context.IntTy; 3409 else if (AllowUnsigned) 3410 Ty = Context.UnsignedIntTy; 3411 Width = IntSize; 3412 } 3413 } 3414 3415 // Are long/unsigned long possibilities? 3416 if (Ty.isNull() && !Literal.isLongLong) { 3417 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3418 3419 // Does it fit in a unsigned long? 3420 if (ResultVal.isIntN(LongSize)) { 3421 // Does it fit in a signed long? 3422 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3423 Ty = Context.LongTy; 3424 else if (AllowUnsigned) 3425 Ty = Context.UnsignedLongTy; 3426 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3427 // is compatible. 3428 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3429 const unsigned LongLongSize = 3430 Context.getTargetInfo().getLongLongWidth(); 3431 Diag(Tok.getLocation(), 3432 getLangOpts().CPlusPlus 3433 ? Literal.isLong 3434 ? diag::warn_old_implicitly_unsigned_long_cxx 3435 : /*C++98 UB*/ diag:: 3436 ext_old_implicitly_unsigned_long_cxx 3437 : diag::warn_old_implicitly_unsigned_long) 3438 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3439 : /*will be ill-formed*/ 1); 3440 Ty = Context.UnsignedLongTy; 3441 } 3442 Width = LongSize; 3443 } 3444 } 3445 3446 // Check long long if needed. 3447 if (Ty.isNull()) { 3448 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3449 3450 // Does it fit in a unsigned long long? 3451 if (ResultVal.isIntN(LongLongSize)) { 3452 // Does it fit in a signed long long? 3453 // To be compatible with MSVC, hex integer literals ending with the 3454 // LL or i64 suffix are always signed in Microsoft mode. 3455 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3456 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3457 Ty = Context.LongLongTy; 3458 else if (AllowUnsigned) 3459 Ty = Context.UnsignedLongLongTy; 3460 Width = LongLongSize; 3461 } 3462 } 3463 3464 // If we still couldn't decide a type, we probably have something that 3465 // does not fit in a signed long long, but has no U suffix. 3466 if (Ty.isNull()) { 3467 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3468 Ty = Context.UnsignedLongLongTy; 3469 Width = Context.getTargetInfo().getLongLongWidth(); 3470 } 3471 3472 if (ResultVal.getBitWidth() != Width) 3473 ResultVal = ResultVal.trunc(Width); 3474 } 3475 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3476 } 3477 3478 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3479 if (Literal.isImaginary) { 3480 Res = new (Context) ImaginaryLiteral(Res, 3481 Context.getComplexType(Res->getType())); 3482 3483 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3484 } 3485 return Res; 3486 } 3487 3488 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3489 assert(E && "ActOnParenExpr() missing expr"); 3490 return new (Context) ParenExpr(L, R, E); 3491 } 3492 3493 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3494 SourceLocation Loc, 3495 SourceRange ArgRange) { 3496 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3497 // scalar or vector data type argument..." 3498 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3499 // type (C99 6.2.5p18) or void. 3500 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3501 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3502 << T << ArgRange; 3503 return true; 3504 } 3505 3506 assert((T->isVoidType() || !T->isIncompleteType()) && 3507 "Scalar types should always be complete"); 3508 return false; 3509 } 3510 3511 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3512 SourceLocation Loc, 3513 SourceRange ArgRange, 3514 UnaryExprOrTypeTrait TraitKind) { 3515 // Invalid types must be hard errors for SFINAE in C++. 3516 if (S.LangOpts.CPlusPlus) 3517 return true; 3518 3519 // C99 6.5.3.4p1: 3520 if (T->isFunctionType() && 3521 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3522 // sizeof(function)/alignof(function) is allowed as an extension. 3523 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3524 << TraitKind << ArgRange; 3525 return false; 3526 } 3527 3528 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3529 // this is an error (OpenCL v1.1 s6.3.k) 3530 if (T->isVoidType()) { 3531 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3532 : diag::ext_sizeof_alignof_void_type; 3533 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3534 return false; 3535 } 3536 3537 return true; 3538 } 3539 3540 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3541 SourceLocation Loc, 3542 SourceRange ArgRange, 3543 UnaryExprOrTypeTrait TraitKind) { 3544 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3545 // runtime doesn't allow it. 3546 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3547 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3548 << T << (TraitKind == UETT_SizeOf) 3549 << ArgRange; 3550 return true; 3551 } 3552 3553 return false; 3554 } 3555 3556 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3557 /// pointer type is equal to T) and emit a warning if it is. 3558 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3559 Expr *E) { 3560 // Don't warn if the operation changed the type. 3561 if (T != E->getType()) 3562 return; 3563 3564 // Now look for array decays. 3565 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3566 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3567 return; 3568 3569 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3570 << ICE->getType() 3571 << ICE->getSubExpr()->getType(); 3572 } 3573 3574 /// \brief Check the constraints on expression operands to unary type expression 3575 /// and type traits. 3576 /// 3577 /// Completes any types necessary and validates the constraints on the operand 3578 /// expression. The logic mostly mirrors the type-based overload, but may modify 3579 /// the expression as it completes the type for that expression through template 3580 /// instantiation, etc. 3581 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3582 UnaryExprOrTypeTrait ExprKind) { 3583 QualType ExprTy = E->getType(); 3584 assert(!ExprTy->isReferenceType()); 3585 3586 if (ExprKind == UETT_VecStep) 3587 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3588 E->getSourceRange()); 3589 3590 // Whitelist some types as extensions 3591 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3592 E->getSourceRange(), ExprKind)) 3593 return false; 3594 3595 // 'alignof' applied to an expression only requires the base element type of 3596 // the expression to be complete. 'sizeof' requires the expression's type to 3597 // be complete (and will attempt to complete it if it's an array of unknown 3598 // bound). 3599 if (ExprKind == UETT_AlignOf) { 3600 if (RequireCompleteType(E->getExprLoc(), 3601 Context.getBaseElementType(E->getType()), 3602 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3603 E->getSourceRange())) 3604 return true; 3605 } else { 3606 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3607 ExprKind, E->getSourceRange())) 3608 return true; 3609 } 3610 3611 // Completing the expression's type may have changed it. 3612 ExprTy = E->getType(); 3613 assert(!ExprTy->isReferenceType()); 3614 3615 if (ExprTy->isFunctionType()) { 3616 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3617 << ExprKind << E->getSourceRange(); 3618 return true; 3619 } 3620 3621 // The operand for sizeof and alignof is in an unevaluated expression context, 3622 // so side effects could result in unintended consequences. 3623 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3624 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3625 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3626 3627 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3628 E->getSourceRange(), ExprKind)) 3629 return true; 3630 3631 if (ExprKind == UETT_SizeOf) { 3632 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3633 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3634 QualType OType = PVD->getOriginalType(); 3635 QualType Type = PVD->getType(); 3636 if (Type->isPointerType() && OType->isArrayType()) { 3637 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3638 << Type << OType; 3639 Diag(PVD->getLocation(), diag::note_declared_at); 3640 } 3641 } 3642 } 3643 3644 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3645 // decays into a pointer and returns an unintended result. This is most 3646 // likely a typo for "sizeof(array) op x". 3647 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3648 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3649 BO->getLHS()); 3650 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3651 BO->getRHS()); 3652 } 3653 } 3654 3655 return false; 3656 } 3657 3658 /// \brief Check the constraints on operands to unary expression and type 3659 /// traits. 3660 /// 3661 /// This will complete any types necessary, and validate the various constraints 3662 /// on those operands. 3663 /// 3664 /// The UsualUnaryConversions() function is *not* called by this routine. 3665 /// C99 6.3.2.1p[2-4] all state: 3666 /// Except when it is the operand of the sizeof operator ... 3667 /// 3668 /// C++ [expr.sizeof]p4 3669 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3670 /// standard conversions are not applied to the operand of sizeof. 3671 /// 3672 /// This policy is followed for all of the unary trait expressions. 3673 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3674 SourceLocation OpLoc, 3675 SourceRange ExprRange, 3676 UnaryExprOrTypeTrait ExprKind) { 3677 if (ExprType->isDependentType()) 3678 return false; 3679 3680 // C++ [expr.sizeof]p2: 3681 // When applied to a reference or a reference type, the result 3682 // is the size of the referenced type. 3683 // C++11 [expr.alignof]p3: 3684 // When alignof is applied to a reference type, the result 3685 // shall be the alignment of the referenced type. 3686 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3687 ExprType = Ref->getPointeeType(); 3688 3689 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3690 // When alignof or _Alignof is applied to an array type, the result 3691 // is the alignment of the element type. 3692 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3693 ExprType = Context.getBaseElementType(ExprType); 3694 3695 if (ExprKind == UETT_VecStep) 3696 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3697 3698 // Whitelist some types as extensions 3699 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3700 ExprKind)) 3701 return false; 3702 3703 if (RequireCompleteType(OpLoc, ExprType, 3704 diag::err_sizeof_alignof_incomplete_type, 3705 ExprKind, ExprRange)) 3706 return true; 3707 3708 if (ExprType->isFunctionType()) { 3709 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3710 << ExprKind << ExprRange; 3711 return true; 3712 } 3713 3714 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3715 ExprKind)) 3716 return true; 3717 3718 return false; 3719 } 3720 3721 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3722 E = E->IgnoreParens(); 3723 3724 // Cannot know anything else if the expression is dependent. 3725 if (E->isTypeDependent()) 3726 return false; 3727 3728 if (E->getObjectKind() == OK_BitField) { 3729 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3730 << 1 << E->getSourceRange(); 3731 return true; 3732 } 3733 3734 ValueDecl *D = nullptr; 3735 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3736 D = DRE->getDecl(); 3737 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3738 D = ME->getMemberDecl(); 3739 } 3740 3741 // If it's a field, require the containing struct to have a 3742 // complete definition so that we can compute the layout. 3743 // 3744 // This can happen in C++11 onwards, either by naming the member 3745 // in a way that is not transformed into a member access expression 3746 // (in an unevaluated operand, for instance), or by naming the member 3747 // in a trailing-return-type. 3748 // 3749 // For the record, since __alignof__ on expressions is a GCC 3750 // extension, GCC seems to permit this but always gives the 3751 // nonsensical answer 0. 3752 // 3753 // We don't really need the layout here --- we could instead just 3754 // directly check for all the appropriate alignment-lowing 3755 // attributes --- but that would require duplicating a lot of 3756 // logic that just isn't worth duplicating for such a marginal 3757 // use-case. 3758 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3759 // Fast path this check, since we at least know the record has a 3760 // definition if we can find a member of it. 3761 if (!FD->getParent()->isCompleteDefinition()) { 3762 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3763 << E->getSourceRange(); 3764 return true; 3765 } 3766 3767 // Otherwise, if it's a field, and the field doesn't have 3768 // reference type, then it must have a complete type (or be a 3769 // flexible array member, which we explicitly want to 3770 // white-list anyway), which makes the following checks trivial. 3771 if (!FD->getType()->isReferenceType()) 3772 return false; 3773 } 3774 3775 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3776 } 3777 3778 bool Sema::CheckVecStepExpr(Expr *E) { 3779 E = E->IgnoreParens(); 3780 3781 // Cannot know anything else if the expression is dependent. 3782 if (E->isTypeDependent()) 3783 return false; 3784 3785 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3786 } 3787 3788 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3789 CapturingScopeInfo *CSI) { 3790 assert(T->isVariablyModifiedType()); 3791 assert(CSI != nullptr); 3792 3793 // We're going to walk down into the type and look for VLA expressions. 3794 do { 3795 const Type *Ty = T.getTypePtr(); 3796 switch (Ty->getTypeClass()) { 3797 #define TYPE(Class, Base) 3798 #define ABSTRACT_TYPE(Class, Base) 3799 #define NON_CANONICAL_TYPE(Class, Base) 3800 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3801 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3802 #include "clang/AST/TypeNodes.def" 3803 T = QualType(); 3804 break; 3805 // These types are never variably-modified. 3806 case Type::Builtin: 3807 case Type::Complex: 3808 case Type::Vector: 3809 case Type::ExtVector: 3810 case Type::Record: 3811 case Type::Enum: 3812 case Type::Elaborated: 3813 case Type::TemplateSpecialization: 3814 case Type::ObjCObject: 3815 case Type::ObjCInterface: 3816 case Type::ObjCObjectPointer: 3817 case Type::ObjCTypeParam: 3818 case Type::Pipe: 3819 llvm_unreachable("type class is never variably-modified!"); 3820 case Type::Adjusted: 3821 T = cast<AdjustedType>(Ty)->getOriginalType(); 3822 break; 3823 case Type::Decayed: 3824 T = cast<DecayedType>(Ty)->getPointeeType(); 3825 break; 3826 case Type::Pointer: 3827 T = cast<PointerType>(Ty)->getPointeeType(); 3828 break; 3829 case Type::BlockPointer: 3830 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3831 break; 3832 case Type::LValueReference: 3833 case Type::RValueReference: 3834 T = cast<ReferenceType>(Ty)->getPointeeType(); 3835 break; 3836 case Type::MemberPointer: 3837 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3838 break; 3839 case Type::ConstantArray: 3840 case Type::IncompleteArray: 3841 // Losing element qualification here is fine. 3842 T = cast<ArrayType>(Ty)->getElementType(); 3843 break; 3844 case Type::VariableArray: { 3845 // Losing element qualification here is fine. 3846 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3847 3848 // Unknown size indication requires no size computation. 3849 // Otherwise, evaluate and record it. 3850 if (auto Size = VAT->getSizeExpr()) { 3851 if (!CSI->isVLATypeCaptured(VAT)) { 3852 RecordDecl *CapRecord = nullptr; 3853 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3854 CapRecord = LSI->Lambda; 3855 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3856 CapRecord = CRSI->TheRecordDecl; 3857 } 3858 if (CapRecord) { 3859 auto ExprLoc = Size->getExprLoc(); 3860 auto SizeType = Context.getSizeType(); 3861 // Build the non-static data member. 3862 auto Field = 3863 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3864 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3865 /*BW*/ nullptr, /*Mutable*/ false, 3866 /*InitStyle*/ ICIS_NoInit); 3867 Field->setImplicit(true); 3868 Field->setAccess(AS_private); 3869 Field->setCapturedVLAType(VAT); 3870 CapRecord->addDecl(Field); 3871 3872 CSI->addVLATypeCapture(ExprLoc, SizeType); 3873 } 3874 } 3875 } 3876 T = VAT->getElementType(); 3877 break; 3878 } 3879 case Type::FunctionProto: 3880 case Type::FunctionNoProto: 3881 T = cast<FunctionType>(Ty)->getReturnType(); 3882 break; 3883 case Type::Paren: 3884 case Type::TypeOf: 3885 case Type::UnaryTransform: 3886 case Type::Attributed: 3887 case Type::SubstTemplateTypeParm: 3888 case Type::PackExpansion: 3889 // Keep walking after single level desugaring. 3890 T = T.getSingleStepDesugaredType(Context); 3891 break; 3892 case Type::Typedef: 3893 T = cast<TypedefType>(Ty)->desugar(); 3894 break; 3895 case Type::Decltype: 3896 T = cast<DecltypeType>(Ty)->desugar(); 3897 break; 3898 case Type::Auto: 3899 case Type::DeducedTemplateSpecialization: 3900 T = cast<DeducedType>(Ty)->getDeducedType(); 3901 break; 3902 case Type::TypeOfExpr: 3903 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3904 break; 3905 case Type::Atomic: 3906 T = cast<AtomicType>(Ty)->getValueType(); 3907 break; 3908 } 3909 } while (!T.isNull() && T->isVariablyModifiedType()); 3910 } 3911 3912 /// \brief Build a sizeof or alignof expression given a type operand. 3913 ExprResult 3914 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3915 SourceLocation OpLoc, 3916 UnaryExprOrTypeTrait ExprKind, 3917 SourceRange R) { 3918 if (!TInfo) 3919 return ExprError(); 3920 3921 QualType T = TInfo->getType(); 3922 3923 if (!T->isDependentType() && 3924 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3925 return ExprError(); 3926 3927 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3928 if (auto *TT = T->getAs<TypedefType>()) { 3929 for (auto I = FunctionScopes.rbegin(), 3930 E = std::prev(FunctionScopes.rend()); 3931 I != E; ++I) { 3932 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3933 if (CSI == nullptr) 3934 break; 3935 DeclContext *DC = nullptr; 3936 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3937 DC = LSI->CallOperator; 3938 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3939 DC = CRSI->TheCapturedDecl; 3940 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3941 DC = BSI->TheDecl; 3942 if (DC) { 3943 if (DC->containsDecl(TT->getDecl())) 3944 break; 3945 captureVariablyModifiedType(Context, T, CSI); 3946 } 3947 } 3948 } 3949 } 3950 3951 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3952 return new (Context) UnaryExprOrTypeTraitExpr( 3953 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3954 } 3955 3956 /// \brief Build a sizeof or alignof expression given an expression 3957 /// operand. 3958 ExprResult 3959 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3960 UnaryExprOrTypeTrait ExprKind) { 3961 ExprResult PE = CheckPlaceholderExpr(E); 3962 if (PE.isInvalid()) 3963 return ExprError(); 3964 3965 E = PE.get(); 3966 3967 // Verify that the operand is valid. 3968 bool isInvalid = false; 3969 if (E->isTypeDependent()) { 3970 // Delay type-checking for type-dependent expressions. 3971 } else if (ExprKind == UETT_AlignOf) { 3972 isInvalid = CheckAlignOfExpr(*this, E); 3973 } else if (ExprKind == UETT_VecStep) { 3974 isInvalid = CheckVecStepExpr(E); 3975 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3976 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3977 isInvalid = true; 3978 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3979 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3980 isInvalid = true; 3981 } else { 3982 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3983 } 3984 3985 if (isInvalid) 3986 return ExprError(); 3987 3988 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3989 PE = TransformToPotentiallyEvaluated(E); 3990 if (PE.isInvalid()) return ExprError(); 3991 E = PE.get(); 3992 } 3993 3994 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3995 return new (Context) UnaryExprOrTypeTraitExpr( 3996 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3997 } 3998 3999 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4000 /// expr and the same for @c alignof and @c __alignof 4001 /// Note that the ArgRange is invalid if isType is false. 4002 ExprResult 4003 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4004 UnaryExprOrTypeTrait ExprKind, bool IsType, 4005 void *TyOrEx, SourceRange ArgRange) { 4006 // If error parsing type, ignore. 4007 if (!TyOrEx) return ExprError(); 4008 4009 if (IsType) { 4010 TypeSourceInfo *TInfo; 4011 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4012 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4013 } 4014 4015 Expr *ArgEx = (Expr *)TyOrEx; 4016 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4017 return Result; 4018 } 4019 4020 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4021 bool IsReal) { 4022 if (V.get()->isTypeDependent()) 4023 return S.Context.DependentTy; 4024 4025 // _Real and _Imag are only l-values for normal l-values. 4026 if (V.get()->getObjectKind() != OK_Ordinary) { 4027 V = S.DefaultLvalueConversion(V.get()); 4028 if (V.isInvalid()) 4029 return QualType(); 4030 } 4031 4032 // These operators return the element type of a complex type. 4033 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4034 return CT->getElementType(); 4035 4036 // Otherwise they pass through real integer and floating point types here. 4037 if (V.get()->getType()->isArithmeticType()) 4038 return V.get()->getType(); 4039 4040 // Test for placeholders. 4041 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4042 if (PR.isInvalid()) return QualType(); 4043 if (PR.get() != V.get()) { 4044 V = PR; 4045 return CheckRealImagOperand(S, V, Loc, IsReal); 4046 } 4047 4048 // Reject anything else. 4049 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4050 << (IsReal ? "__real" : "__imag"); 4051 return QualType(); 4052 } 4053 4054 4055 4056 ExprResult 4057 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4058 tok::TokenKind Kind, Expr *Input) { 4059 UnaryOperatorKind Opc; 4060 switch (Kind) { 4061 default: llvm_unreachable("Unknown unary op!"); 4062 case tok::plusplus: Opc = UO_PostInc; break; 4063 case tok::minusminus: Opc = UO_PostDec; break; 4064 } 4065 4066 // Since this might is a postfix expression, get rid of ParenListExprs. 4067 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4068 if (Result.isInvalid()) return ExprError(); 4069 Input = Result.get(); 4070 4071 return BuildUnaryOp(S, OpLoc, Opc, Input); 4072 } 4073 4074 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4075 /// 4076 /// \return true on error 4077 static bool checkArithmeticOnObjCPointer(Sema &S, 4078 SourceLocation opLoc, 4079 Expr *op) { 4080 assert(op->getType()->isObjCObjectPointerType()); 4081 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4082 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4083 return false; 4084 4085 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4086 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4087 << op->getSourceRange(); 4088 return true; 4089 } 4090 4091 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4092 auto *BaseNoParens = Base->IgnoreParens(); 4093 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4094 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4095 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4096 } 4097 4098 ExprResult 4099 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4100 Expr *idx, SourceLocation rbLoc) { 4101 if (base && !base->getType().isNull() && 4102 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4103 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4104 /*Length=*/nullptr, rbLoc); 4105 4106 // Since this might be a postfix expression, get rid of ParenListExprs. 4107 if (isa<ParenListExpr>(base)) { 4108 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4109 if (result.isInvalid()) return ExprError(); 4110 base = result.get(); 4111 } 4112 4113 // Handle any non-overload placeholder types in the base and index 4114 // expressions. We can't handle overloads here because the other 4115 // operand might be an overloadable type, in which case the overload 4116 // resolution for the operator overload should get the first crack 4117 // at the overload. 4118 bool IsMSPropertySubscript = false; 4119 if (base->getType()->isNonOverloadPlaceholderType()) { 4120 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4121 if (!IsMSPropertySubscript) { 4122 ExprResult result = CheckPlaceholderExpr(base); 4123 if (result.isInvalid()) 4124 return ExprError(); 4125 base = result.get(); 4126 } 4127 } 4128 if (idx->getType()->isNonOverloadPlaceholderType()) { 4129 ExprResult result = CheckPlaceholderExpr(idx); 4130 if (result.isInvalid()) return ExprError(); 4131 idx = result.get(); 4132 } 4133 4134 // Build an unanalyzed expression if either operand is type-dependent. 4135 if (getLangOpts().CPlusPlus && 4136 (base->isTypeDependent() || idx->isTypeDependent())) { 4137 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4138 VK_LValue, OK_Ordinary, rbLoc); 4139 } 4140 4141 // MSDN, property (C++) 4142 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4143 // This attribute can also be used in the declaration of an empty array in a 4144 // class or structure definition. For example: 4145 // __declspec(property(get=GetX, put=PutX)) int x[]; 4146 // The above statement indicates that x[] can be used with one or more array 4147 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4148 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4149 if (IsMSPropertySubscript) { 4150 // Build MS property subscript expression if base is MS property reference 4151 // or MS property subscript. 4152 return new (Context) MSPropertySubscriptExpr( 4153 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4154 } 4155 4156 // Use C++ overloaded-operator rules if either operand has record 4157 // type. The spec says to do this if either type is *overloadable*, 4158 // but enum types can't declare subscript operators or conversion 4159 // operators, so there's nothing interesting for overload resolution 4160 // to do if there aren't any record types involved. 4161 // 4162 // ObjC pointers have their own subscripting logic that is not tied 4163 // to overload resolution and so should not take this path. 4164 if (getLangOpts().CPlusPlus && 4165 (base->getType()->isRecordType() || 4166 (!base->getType()->isObjCObjectPointerType() && 4167 idx->getType()->isRecordType()))) { 4168 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4169 } 4170 4171 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4172 } 4173 4174 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4175 Expr *LowerBound, 4176 SourceLocation ColonLoc, Expr *Length, 4177 SourceLocation RBLoc) { 4178 if (Base->getType()->isPlaceholderType() && 4179 !Base->getType()->isSpecificPlaceholderType( 4180 BuiltinType::OMPArraySection)) { 4181 ExprResult Result = CheckPlaceholderExpr(Base); 4182 if (Result.isInvalid()) 4183 return ExprError(); 4184 Base = Result.get(); 4185 } 4186 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4187 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4188 if (Result.isInvalid()) 4189 return ExprError(); 4190 Result = DefaultLvalueConversion(Result.get()); 4191 if (Result.isInvalid()) 4192 return ExprError(); 4193 LowerBound = Result.get(); 4194 } 4195 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4196 ExprResult Result = CheckPlaceholderExpr(Length); 4197 if (Result.isInvalid()) 4198 return ExprError(); 4199 Result = DefaultLvalueConversion(Result.get()); 4200 if (Result.isInvalid()) 4201 return ExprError(); 4202 Length = Result.get(); 4203 } 4204 4205 // Build an unanalyzed expression if either operand is type-dependent. 4206 if (Base->isTypeDependent() || 4207 (LowerBound && 4208 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4209 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4210 return new (Context) 4211 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4212 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4213 } 4214 4215 // Perform default conversions. 4216 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4217 QualType ResultTy; 4218 if (OriginalTy->isAnyPointerType()) { 4219 ResultTy = OriginalTy->getPointeeType(); 4220 } else if (OriginalTy->isArrayType()) { 4221 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4222 } else { 4223 return ExprError( 4224 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4225 << Base->getSourceRange()); 4226 } 4227 // C99 6.5.2.1p1 4228 if (LowerBound) { 4229 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4230 LowerBound); 4231 if (Res.isInvalid()) 4232 return ExprError(Diag(LowerBound->getExprLoc(), 4233 diag::err_omp_typecheck_section_not_integer) 4234 << 0 << LowerBound->getSourceRange()); 4235 LowerBound = Res.get(); 4236 4237 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4238 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4239 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4240 << 0 << LowerBound->getSourceRange(); 4241 } 4242 if (Length) { 4243 auto Res = 4244 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4245 if (Res.isInvalid()) 4246 return ExprError(Diag(Length->getExprLoc(), 4247 diag::err_omp_typecheck_section_not_integer) 4248 << 1 << Length->getSourceRange()); 4249 Length = Res.get(); 4250 4251 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4252 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4253 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4254 << 1 << Length->getSourceRange(); 4255 } 4256 4257 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4258 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4259 // type. Note that functions are not objects, and that (in C99 parlance) 4260 // incomplete types are not object types. 4261 if (ResultTy->isFunctionType()) { 4262 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4263 << ResultTy << Base->getSourceRange(); 4264 return ExprError(); 4265 } 4266 4267 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4268 diag::err_omp_section_incomplete_type, Base)) 4269 return ExprError(); 4270 4271 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4272 llvm::APSInt LowerBoundValue; 4273 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4274 // OpenMP 4.5, [2.4 Array Sections] 4275 // The array section must be a subset of the original array. 4276 if (LowerBoundValue.isNegative()) { 4277 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4278 << LowerBound->getSourceRange(); 4279 return ExprError(); 4280 } 4281 } 4282 } 4283 4284 if (Length) { 4285 llvm::APSInt LengthValue; 4286 if (Length->EvaluateAsInt(LengthValue, Context)) { 4287 // OpenMP 4.5, [2.4 Array Sections] 4288 // The length must evaluate to non-negative integers. 4289 if (LengthValue.isNegative()) { 4290 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4291 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4292 << Length->getSourceRange(); 4293 return ExprError(); 4294 } 4295 } 4296 } else if (ColonLoc.isValid() && 4297 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4298 !OriginalTy->isVariableArrayType()))) { 4299 // OpenMP 4.5, [2.4 Array Sections] 4300 // When the size of the array dimension is not known, the length must be 4301 // specified explicitly. 4302 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4303 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4304 return ExprError(); 4305 } 4306 4307 if (!Base->getType()->isSpecificPlaceholderType( 4308 BuiltinType::OMPArraySection)) { 4309 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4310 if (Result.isInvalid()) 4311 return ExprError(); 4312 Base = Result.get(); 4313 } 4314 return new (Context) 4315 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4316 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4317 } 4318 4319 ExprResult 4320 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4321 Expr *Idx, SourceLocation RLoc) { 4322 Expr *LHSExp = Base; 4323 Expr *RHSExp = Idx; 4324 4325 ExprValueKind VK = VK_LValue; 4326 ExprObjectKind OK = OK_Ordinary; 4327 4328 // Per C++ core issue 1213, the result is an xvalue if either operand is 4329 // a non-lvalue array, and an lvalue otherwise. 4330 if (getLangOpts().CPlusPlus11 && 4331 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4332 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4333 VK = VK_XValue; 4334 4335 // Perform default conversions. 4336 if (!LHSExp->getType()->getAs<VectorType>()) { 4337 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4338 if (Result.isInvalid()) 4339 return ExprError(); 4340 LHSExp = Result.get(); 4341 } 4342 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4343 if (Result.isInvalid()) 4344 return ExprError(); 4345 RHSExp = Result.get(); 4346 4347 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4348 4349 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4350 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4351 // in the subscript position. As a result, we need to derive the array base 4352 // and index from the expression types. 4353 Expr *BaseExpr, *IndexExpr; 4354 QualType ResultType; 4355 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4356 BaseExpr = LHSExp; 4357 IndexExpr = RHSExp; 4358 ResultType = Context.DependentTy; 4359 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4360 BaseExpr = LHSExp; 4361 IndexExpr = RHSExp; 4362 ResultType = PTy->getPointeeType(); 4363 } else if (const ObjCObjectPointerType *PTy = 4364 LHSTy->getAs<ObjCObjectPointerType>()) { 4365 BaseExpr = LHSExp; 4366 IndexExpr = RHSExp; 4367 4368 // Use custom logic if this should be the pseudo-object subscript 4369 // expression. 4370 if (!LangOpts.isSubscriptPointerArithmetic()) 4371 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4372 nullptr); 4373 4374 ResultType = PTy->getPointeeType(); 4375 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4376 // Handle the uncommon case of "123[Ptr]". 4377 BaseExpr = RHSExp; 4378 IndexExpr = LHSExp; 4379 ResultType = PTy->getPointeeType(); 4380 } else if (const ObjCObjectPointerType *PTy = 4381 RHSTy->getAs<ObjCObjectPointerType>()) { 4382 // Handle the uncommon case of "123[Ptr]". 4383 BaseExpr = RHSExp; 4384 IndexExpr = LHSExp; 4385 ResultType = PTy->getPointeeType(); 4386 if (!LangOpts.isSubscriptPointerArithmetic()) { 4387 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4388 << ResultType << BaseExpr->getSourceRange(); 4389 return ExprError(); 4390 } 4391 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4392 BaseExpr = LHSExp; // vectors: V[123] 4393 IndexExpr = RHSExp; 4394 VK = LHSExp->getValueKind(); 4395 if (VK != VK_RValue) 4396 OK = OK_VectorComponent; 4397 4398 ResultType = VTy->getElementType(); 4399 QualType BaseType = BaseExpr->getType(); 4400 Qualifiers BaseQuals = BaseType.getQualifiers(); 4401 Qualifiers MemberQuals = ResultType.getQualifiers(); 4402 Qualifiers Combined = BaseQuals + MemberQuals; 4403 if (Combined != MemberQuals) 4404 ResultType = Context.getQualifiedType(ResultType, Combined); 4405 } else if (LHSTy->isArrayType()) { 4406 // If we see an array that wasn't promoted by 4407 // DefaultFunctionArrayLvalueConversion, it must be an array that 4408 // wasn't promoted because of the C90 rule that doesn't 4409 // allow promoting non-lvalue arrays. Warn, then 4410 // force the promotion here. 4411 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4412 LHSExp->getSourceRange(); 4413 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4414 CK_ArrayToPointerDecay).get(); 4415 LHSTy = LHSExp->getType(); 4416 4417 BaseExpr = LHSExp; 4418 IndexExpr = RHSExp; 4419 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4420 } else if (RHSTy->isArrayType()) { 4421 // Same as previous, except for 123[f().a] case 4422 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4423 RHSExp->getSourceRange(); 4424 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4425 CK_ArrayToPointerDecay).get(); 4426 RHSTy = RHSExp->getType(); 4427 4428 BaseExpr = RHSExp; 4429 IndexExpr = LHSExp; 4430 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4431 } else { 4432 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4433 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4434 } 4435 // C99 6.5.2.1p1 4436 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4437 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4438 << IndexExpr->getSourceRange()); 4439 4440 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4441 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4442 && !IndexExpr->isTypeDependent()) 4443 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4444 4445 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4446 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4447 // type. Note that Functions are not objects, and that (in C99 parlance) 4448 // incomplete types are not object types. 4449 if (ResultType->isFunctionType()) { 4450 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4451 << ResultType << BaseExpr->getSourceRange(); 4452 return ExprError(); 4453 } 4454 4455 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4456 // GNU extension: subscripting on pointer to void 4457 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4458 << BaseExpr->getSourceRange(); 4459 4460 // C forbids expressions of unqualified void type from being l-values. 4461 // See IsCForbiddenLValueType. 4462 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4463 } else if (!ResultType->isDependentType() && 4464 RequireCompleteType(LLoc, ResultType, 4465 diag::err_subscript_incomplete_type, BaseExpr)) 4466 return ExprError(); 4467 4468 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4469 !ResultType.isCForbiddenLValueType()); 4470 4471 return new (Context) 4472 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4473 } 4474 4475 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4476 ParmVarDecl *Param) { 4477 if (Param->hasUnparsedDefaultArg()) { 4478 Diag(CallLoc, 4479 diag::err_use_of_default_argument_to_function_declared_later) << 4480 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4481 Diag(UnparsedDefaultArgLocs[Param], 4482 diag::note_default_argument_declared_here); 4483 return true; 4484 } 4485 4486 if (Param->hasUninstantiatedDefaultArg()) { 4487 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4488 4489 EnterExpressionEvaluationContext EvalContext( 4490 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4491 4492 // Instantiate the expression. 4493 // 4494 // FIXME: Pass in a correct Pattern argument, otherwise 4495 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4496 // 4497 // template<typename T> 4498 // struct A { 4499 // static int FooImpl(); 4500 // 4501 // template<typename Tp> 4502 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4503 // // template argument list [[T], [Tp]], should be [[Tp]]. 4504 // friend A<Tp> Foo(int a); 4505 // }; 4506 // 4507 // template<typename T> 4508 // A<T> Foo(int a = A<T>::FooImpl()); 4509 MultiLevelTemplateArgumentList MutiLevelArgList 4510 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4511 4512 InstantiatingTemplate Inst(*this, CallLoc, Param, 4513 MutiLevelArgList.getInnermost()); 4514 if (Inst.isInvalid()) 4515 return true; 4516 if (Inst.isAlreadyInstantiating()) { 4517 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4518 Param->setInvalidDecl(); 4519 return true; 4520 } 4521 4522 ExprResult Result; 4523 { 4524 // C++ [dcl.fct.default]p5: 4525 // The names in the [default argument] expression are bound, and 4526 // the semantic constraints are checked, at the point where the 4527 // default argument expression appears. 4528 ContextRAII SavedContext(*this, FD); 4529 LocalInstantiationScope Local(*this); 4530 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4531 /*DirectInit*/false); 4532 } 4533 if (Result.isInvalid()) 4534 return true; 4535 4536 // Check the expression as an initializer for the parameter. 4537 InitializedEntity Entity 4538 = InitializedEntity::InitializeParameter(Context, Param); 4539 InitializationKind Kind 4540 = InitializationKind::CreateCopy(Param->getLocation(), 4541 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4542 Expr *ResultE = Result.getAs<Expr>(); 4543 4544 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4545 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4546 if (Result.isInvalid()) 4547 return true; 4548 4549 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4550 Param->getOuterLocStart()); 4551 if (Result.isInvalid()) 4552 return true; 4553 4554 // Remember the instantiated default argument. 4555 Param->setDefaultArg(Result.getAs<Expr>()); 4556 if (ASTMutationListener *L = getASTMutationListener()) { 4557 L->DefaultArgumentInstantiated(Param); 4558 } 4559 } 4560 4561 // If the default argument expression is not set yet, we are building it now. 4562 if (!Param->hasInit()) { 4563 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4564 Param->setInvalidDecl(); 4565 return true; 4566 } 4567 4568 // If the default expression creates temporaries, we need to 4569 // push them to the current stack of expression temporaries so they'll 4570 // be properly destroyed. 4571 // FIXME: We should really be rebuilding the default argument with new 4572 // bound temporaries; see the comment in PR5810. 4573 // We don't need to do that with block decls, though, because 4574 // blocks in default argument expression can never capture anything. 4575 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4576 // Set the "needs cleanups" bit regardless of whether there are 4577 // any explicit objects. 4578 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4579 4580 // Append all the objects to the cleanup list. Right now, this 4581 // should always be a no-op, because blocks in default argument 4582 // expressions should never be able to capture anything. 4583 assert(!Init->getNumObjects() && 4584 "default argument expression has capturing blocks?"); 4585 } 4586 4587 // We already type-checked the argument, so we know it works. 4588 // Just mark all of the declarations in this potentially-evaluated expression 4589 // as being "referenced". 4590 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4591 /*SkipLocalVariables=*/true); 4592 return false; 4593 } 4594 4595 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4596 FunctionDecl *FD, ParmVarDecl *Param) { 4597 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4598 return ExprError(); 4599 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4600 } 4601 4602 Sema::VariadicCallType 4603 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4604 Expr *Fn) { 4605 if (Proto && Proto->isVariadic()) { 4606 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4607 return VariadicConstructor; 4608 else if (Fn && Fn->getType()->isBlockPointerType()) 4609 return VariadicBlock; 4610 else if (FDecl) { 4611 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4612 if (Method->isInstance()) 4613 return VariadicMethod; 4614 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4615 return VariadicMethod; 4616 return VariadicFunction; 4617 } 4618 return VariadicDoesNotApply; 4619 } 4620 4621 namespace { 4622 class FunctionCallCCC : public FunctionCallFilterCCC { 4623 public: 4624 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4625 unsigned NumArgs, MemberExpr *ME) 4626 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4627 FunctionName(FuncName) {} 4628 4629 bool ValidateCandidate(const TypoCorrection &candidate) override { 4630 if (!candidate.getCorrectionSpecifier() || 4631 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4632 return false; 4633 } 4634 4635 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4636 } 4637 4638 private: 4639 const IdentifierInfo *const FunctionName; 4640 }; 4641 } 4642 4643 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4644 FunctionDecl *FDecl, 4645 ArrayRef<Expr *> Args) { 4646 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4647 DeclarationName FuncName = FDecl->getDeclName(); 4648 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4649 4650 if (TypoCorrection Corrected = S.CorrectTypo( 4651 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4652 S.getScopeForContext(S.CurContext), nullptr, 4653 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4654 Args.size(), ME), 4655 Sema::CTK_ErrorRecovery)) { 4656 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4657 if (Corrected.isOverloaded()) { 4658 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4659 OverloadCandidateSet::iterator Best; 4660 for (NamedDecl *CD : Corrected) { 4661 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4662 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4663 OCS); 4664 } 4665 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4666 case OR_Success: 4667 ND = Best->FoundDecl; 4668 Corrected.setCorrectionDecl(ND); 4669 break; 4670 default: 4671 break; 4672 } 4673 } 4674 ND = ND->getUnderlyingDecl(); 4675 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4676 return Corrected; 4677 } 4678 } 4679 return TypoCorrection(); 4680 } 4681 4682 /// ConvertArgumentsForCall - Converts the arguments specified in 4683 /// Args/NumArgs to the parameter types of the function FDecl with 4684 /// function prototype Proto. Call is the call expression itself, and 4685 /// Fn is the function expression. For a C++ member function, this 4686 /// routine does not attempt to convert the object argument. Returns 4687 /// true if the call is ill-formed. 4688 bool 4689 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4690 FunctionDecl *FDecl, 4691 const FunctionProtoType *Proto, 4692 ArrayRef<Expr *> Args, 4693 SourceLocation RParenLoc, 4694 bool IsExecConfig) { 4695 // Bail out early if calling a builtin with custom typechecking. 4696 if (FDecl) 4697 if (unsigned ID = FDecl->getBuiltinID()) 4698 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4699 return false; 4700 4701 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4702 // assignment, to the types of the corresponding parameter, ... 4703 unsigned NumParams = Proto->getNumParams(); 4704 bool Invalid = false; 4705 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4706 unsigned FnKind = Fn->getType()->isBlockPointerType() 4707 ? 1 /* block */ 4708 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4709 : 0 /* function */); 4710 4711 // If too few arguments are available (and we don't have default 4712 // arguments for the remaining parameters), don't make the call. 4713 if (Args.size() < NumParams) { 4714 if (Args.size() < MinArgs) { 4715 TypoCorrection TC; 4716 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4717 unsigned diag_id = 4718 MinArgs == NumParams && !Proto->isVariadic() 4719 ? diag::err_typecheck_call_too_few_args_suggest 4720 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4721 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4722 << static_cast<unsigned>(Args.size()) 4723 << TC.getCorrectionRange()); 4724 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4725 Diag(RParenLoc, 4726 MinArgs == NumParams && !Proto->isVariadic() 4727 ? diag::err_typecheck_call_too_few_args_one 4728 : diag::err_typecheck_call_too_few_args_at_least_one) 4729 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4730 else 4731 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4732 ? diag::err_typecheck_call_too_few_args 4733 : diag::err_typecheck_call_too_few_args_at_least) 4734 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4735 << Fn->getSourceRange(); 4736 4737 // Emit the location of the prototype. 4738 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4739 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4740 << FDecl; 4741 4742 return true; 4743 } 4744 Call->setNumArgs(Context, NumParams); 4745 } 4746 4747 // If too many are passed and not variadic, error on the extras and drop 4748 // them. 4749 if (Args.size() > NumParams) { 4750 if (!Proto->isVariadic()) { 4751 TypoCorrection TC; 4752 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4753 unsigned diag_id = 4754 MinArgs == NumParams && !Proto->isVariadic() 4755 ? diag::err_typecheck_call_too_many_args_suggest 4756 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4757 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4758 << static_cast<unsigned>(Args.size()) 4759 << TC.getCorrectionRange()); 4760 } else if (NumParams == 1 && FDecl && 4761 FDecl->getParamDecl(0)->getDeclName()) 4762 Diag(Args[NumParams]->getLocStart(), 4763 MinArgs == NumParams 4764 ? diag::err_typecheck_call_too_many_args_one 4765 : diag::err_typecheck_call_too_many_args_at_most_one) 4766 << FnKind << FDecl->getParamDecl(0) 4767 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4768 << SourceRange(Args[NumParams]->getLocStart(), 4769 Args.back()->getLocEnd()); 4770 else 4771 Diag(Args[NumParams]->getLocStart(), 4772 MinArgs == NumParams 4773 ? diag::err_typecheck_call_too_many_args 4774 : diag::err_typecheck_call_too_many_args_at_most) 4775 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4776 << Fn->getSourceRange() 4777 << SourceRange(Args[NumParams]->getLocStart(), 4778 Args.back()->getLocEnd()); 4779 4780 // Emit the location of the prototype. 4781 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4782 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4783 << FDecl; 4784 4785 // This deletes the extra arguments. 4786 Call->setNumArgs(Context, NumParams); 4787 return true; 4788 } 4789 } 4790 SmallVector<Expr *, 8> AllArgs; 4791 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4792 4793 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4794 Proto, 0, Args, AllArgs, CallType); 4795 if (Invalid) 4796 return true; 4797 unsigned TotalNumArgs = AllArgs.size(); 4798 for (unsigned i = 0; i < TotalNumArgs; ++i) 4799 Call->setArg(i, AllArgs[i]); 4800 4801 return false; 4802 } 4803 4804 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4805 const FunctionProtoType *Proto, 4806 unsigned FirstParam, ArrayRef<Expr *> Args, 4807 SmallVectorImpl<Expr *> &AllArgs, 4808 VariadicCallType CallType, bool AllowExplicit, 4809 bool IsListInitialization) { 4810 unsigned NumParams = Proto->getNumParams(); 4811 bool Invalid = false; 4812 size_t ArgIx = 0; 4813 // Continue to check argument types (even if we have too few/many args). 4814 for (unsigned i = FirstParam; i < NumParams; i++) { 4815 QualType ProtoArgType = Proto->getParamType(i); 4816 4817 Expr *Arg; 4818 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4819 if (ArgIx < Args.size()) { 4820 Arg = Args[ArgIx++]; 4821 4822 if (RequireCompleteType(Arg->getLocStart(), 4823 ProtoArgType, 4824 diag::err_call_incomplete_argument, Arg)) 4825 return true; 4826 4827 // Strip the unbridged-cast placeholder expression off, if applicable. 4828 bool CFAudited = false; 4829 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4830 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4831 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4832 Arg = stripARCUnbridgedCast(Arg); 4833 else if (getLangOpts().ObjCAutoRefCount && 4834 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4835 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4836 CFAudited = true; 4837 4838 InitializedEntity Entity = 4839 Param ? InitializedEntity::InitializeParameter(Context, Param, 4840 ProtoArgType) 4841 : InitializedEntity::InitializeParameter( 4842 Context, ProtoArgType, Proto->isParamConsumed(i)); 4843 4844 // Remember that parameter belongs to a CF audited API. 4845 if (CFAudited) 4846 Entity.setParameterCFAudited(); 4847 4848 ExprResult ArgE = PerformCopyInitialization( 4849 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4850 if (ArgE.isInvalid()) 4851 return true; 4852 4853 Arg = ArgE.getAs<Expr>(); 4854 } else { 4855 assert(Param && "can't use default arguments without a known callee"); 4856 4857 ExprResult ArgExpr = 4858 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4859 if (ArgExpr.isInvalid()) 4860 return true; 4861 4862 Arg = ArgExpr.getAs<Expr>(); 4863 } 4864 4865 // Check for array bounds violations for each argument to the call. This 4866 // check only triggers warnings when the argument isn't a more complex Expr 4867 // with its own checking, such as a BinaryOperator. 4868 CheckArrayAccess(Arg); 4869 4870 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4871 CheckStaticArrayArgument(CallLoc, Param, Arg); 4872 4873 AllArgs.push_back(Arg); 4874 } 4875 4876 // If this is a variadic call, handle args passed through "...". 4877 if (CallType != VariadicDoesNotApply) { 4878 // Assume that extern "C" functions with variadic arguments that 4879 // return __unknown_anytype aren't *really* variadic. 4880 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4881 FDecl->isExternC()) { 4882 for (Expr *A : Args.slice(ArgIx)) { 4883 QualType paramType; // ignored 4884 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4885 Invalid |= arg.isInvalid(); 4886 AllArgs.push_back(arg.get()); 4887 } 4888 4889 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4890 } else { 4891 for (Expr *A : Args.slice(ArgIx)) { 4892 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4893 Invalid |= Arg.isInvalid(); 4894 AllArgs.push_back(Arg.get()); 4895 } 4896 } 4897 4898 // Check for array bounds violations. 4899 for (Expr *A : Args.slice(ArgIx)) 4900 CheckArrayAccess(A); 4901 } 4902 return Invalid; 4903 } 4904 4905 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4906 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4907 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4908 TL = DTL.getOriginalLoc(); 4909 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4910 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4911 << ATL.getLocalSourceRange(); 4912 } 4913 4914 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4915 /// array parameter, check that it is non-null, and that if it is formed by 4916 /// array-to-pointer decay, the underlying array is sufficiently large. 4917 /// 4918 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4919 /// array type derivation, then for each call to the function, the value of the 4920 /// corresponding actual argument shall provide access to the first element of 4921 /// an array with at least as many elements as specified by the size expression. 4922 void 4923 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4924 ParmVarDecl *Param, 4925 const Expr *ArgExpr) { 4926 // Static array parameters are not supported in C++. 4927 if (!Param || getLangOpts().CPlusPlus) 4928 return; 4929 4930 QualType OrigTy = Param->getOriginalType(); 4931 4932 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4933 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4934 return; 4935 4936 if (ArgExpr->isNullPointerConstant(Context, 4937 Expr::NPC_NeverValueDependent)) { 4938 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4939 DiagnoseCalleeStaticArrayParam(*this, Param); 4940 return; 4941 } 4942 4943 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4944 if (!CAT) 4945 return; 4946 4947 const ConstantArrayType *ArgCAT = 4948 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4949 if (!ArgCAT) 4950 return; 4951 4952 if (ArgCAT->getSize().ult(CAT->getSize())) { 4953 Diag(CallLoc, diag::warn_static_array_too_small) 4954 << ArgExpr->getSourceRange() 4955 << (unsigned) ArgCAT->getSize().getZExtValue() 4956 << (unsigned) CAT->getSize().getZExtValue(); 4957 DiagnoseCalleeStaticArrayParam(*this, Param); 4958 } 4959 } 4960 4961 /// Given a function expression of unknown-any type, try to rebuild it 4962 /// to have a function type. 4963 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4964 4965 /// Is the given type a placeholder that we need to lower out 4966 /// immediately during argument processing? 4967 static bool isPlaceholderToRemoveAsArg(QualType type) { 4968 // Placeholders are never sugared. 4969 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4970 if (!placeholder) return false; 4971 4972 switch (placeholder->getKind()) { 4973 // Ignore all the non-placeholder types. 4974 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4975 case BuiltinType::Id: 4976 #include "clang/Basic/OpenCLImageTypes.def" 4977 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4978 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4979 #include "clang/AST/BuiltinTypes.def" 4980 return false; 4981 4982 // We cannot lower out overload sets; they might validly be resolved 4983 // by the call machinery. 4984 case BuiltinType::Overload: 4985 return false; 4986 4987 // Unbridged casts in ARC can be handled in some call positions and 4988 // should be left in place. 4989 case BuiltinType::ARCUnbridgedCast: 4990 return false; 4991 4992 // Pseudo-objects should be converted as soon as possible. 4993 case BuiltinType::PseudoObject: 4994 return true; 4995 4996 // The debugger mode could theoretically but currently does not try 4997 // to resolve unknown-typed arguments based on known parameter types. 4998 case BuiltinType::UnknownAny: 4999 return true; 5000 5001 // These are always invalid as call arguments and should be reported. 5002 case BuiltinType::BoundMember: 5003 case BuiltinType::BuiltinFn: 5004 case BuiltinType::OMPArraySection: 5005 return true; 5006 5007 } 5008 llvm_unreachable("bad builtin type kind"); 5009 } 5010 5011 /// Check an argument list for placeholders that we won't try to 5012 /// handle later. 5013 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5014 // Apply this processing to all the arguments at once instead of 5015 // dying at the first failure. 5016 bool hasInvalid = false; 5017 for (size_t i = 0, e = args.size(); i != e; i++) { 5018 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5019 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5020 if (result.isInvalid()) hasInvalid = true; 5021 else args[i] = result.get(); 5022 } else if (hasInvalid) { 5023 (void)S.CorrectDelayedTyposInExpr(args[i]); 5024 } 5025 } 5026 return hasInvalid; 5027 } 5028 5029 /// If a builtin function has a pointer argument with no explicit address 5030 /// space, then it should be able to accept a pointer to any address 5031 /// space as input. In order to do this, we need to replace the 5032 /// standard builtin declaration with one that uses the same address space 5033 /// as the call. 5034 /// 5035 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5036 /// it does not contain any pointer arguments without 5037 /// an address space qualifer. Otherwise the rewritten 5038 /// FunctionDecl is returned. 5039 /// TODO: Handle pointer return types. 5040 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5041 const FunctionDecl *FDecl, 5042 MultiExprArg ArgExprs) { 5043 5044 QualType DeclType = FDecl->getType(); 5045 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5046 5047 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5048 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5049 return nullptr; 5050 5051 bool NeedsNewDecl = false; 5052 unsigned i = 0; 5053 SmallVector<QualType, 8> OverloadParams; 5054 5055 for (QualType ParamType : FT->param_types()) { 5056 5057 // Convert array arguments to pointer to simplify type lookup. 5058 ExprResult ArgRes = 5059 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5060 if (ArgRes.isInvalid()) 5061 return nullptr; 5062 Expr *Arg = ArgRes.get(); 5063 QualType ArgType = Arg->getType(); 5064 if (!ParamType->isPointerType() || 5065 ParamType.getQualifiers().hasAddressSpace() || 5066 !ArgType->isPointerType() || 5067 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5068 OverloadParams.push_back(ParamType); 5069 continue; 5070 } 5071 5072 NeedsNewDecl = true; 5073 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5074 5075 QualType PointeeType = ParamType->getPointeeType(); 5076 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5077 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5078 } 5079 5080 if (!NeedsNewDecl) 5081 return nullptr; 5082 5083 FunctionProtoType::ExtProtoInfo EPI; 5084 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5085 OverloadParams, EPI); 5086 DeclContext *Parent = Context.getTranslationUnitDecl(); 5087 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5088 FDecl->getLocation(), 5089 FDecl->getLocation(), 5090 FDecl->getIdentifier(), 5091 OverloadTy, 5092 /*TInfo=*/nullptr, 5093 SC_Extern, false, 5094 /*hasPrototype=*/true); 5095 SmallVector<ParmVarDecl*, 16> Params; 5096 FT = cast<FunctionProtoType>(OverloadTy); 5097 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5098 QualType ParamType = FT->getParamType(i); 5099 ParmVarDecl *Parm = 5100 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5101 SourceLocation(), nullptr, ParamType, 5102 /*TInfo=*/nullptr, SC_None, nullptr); 5103 Parm->setScopeInfo(0, i); 5104 Params.push_back(Parm); 5105 } 5106 OverloadDecl->setParams(Params); 5107 return OverloadDecl; 5108 } 5109 5110 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5111 FunctionDecl *Callee, 5112 MultiExprArg ArgExprs) { 5113 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5114 // similar attributes) really don't like it when functions are called with an 5115 // invalid number of args. 5116 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5117 /*PartialOverloading=*/false) && 5118 !Callee->isVariadic()) 5119 return; 5120 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5121 return; 5122 5123 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5124 S.Diag(Fn->getLocStart(), 5125 isa<CXXMethodDecl>(Callee) 5126 ? diag::err_ovl_no_viable_member_function_in_call 5127 : diag::err_ovl_no_viable_function_in_call) 5128 << Callee << Callee->getSourceRange(); 5129 S.Diag(Callee->getLocation(), 5130 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5131 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5132 return; 5133 } 5134 } 5135 5136 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5137 const UnresolvedMemberExpr *const UME, Sema &S) { 5138 5139 const auto GetFunctionLevelDCIfCXXClass = 5140 [](Sema &S) -> const CXXRecordDecl * { 5141 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5142 if (!DC || !DC->getParent()) 5143 return nullptr; 5144 5145 // If the call to some member function was made from within a member 5146 // function body 'M' return return 'M's parent. 5147 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5148 return MD->getParent()->getCanonicalDecl(); 5149 // else the call was made from within a default member initializer of a 5150 // class, so return the class. 5151 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5152 return RD->getCanonicalDecl(); 5153 return nullptr; 5154 }; 5155 // If our DeclContext is neither a member function nor a class (in the 5156 // case of a lambda in a default member initializer), we can't have an 5157 // enclosing 'this'. 5158 5159 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5160 if (!CurParentClass) 5161 return false; 5162 5163 // The naming class for implicit member functions call is the class in which 5164 // name lookup starts. 5165 const CXXRecordDecl *const NamingClass = 5166 UME->getNamingClass()->getCanonicalDecl(); 5167 assert(NamingClass && "Must have naming class even for implicit access"); 5168 5169 // If the unresolved member functions were found in a 'naming class' that is 5170 // related (either the same or derived from) to the class that contains the 5171 // member function that itself contained the implicit member access. 5172 5173 return CurParentClass == NamingClass || 5174 CurParentClass->isDerivedFrom(NamingClass); 5175 } 5176 5177 static void 5178 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5179 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5180 5181 if (!UME) 5182 return; 5183 5184 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5185 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5186 // already been captured, or if this is an implicit member function call (if 5187 // it isn't, an attempt to capture 'this' should already have been made). 5188 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5189 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5190 return; 5191 5192 // Check if the naming class in which the unresolved members were found is 5193 // related (same as or is a base of) to the enclosing class. 5194 5195 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5196 return; 5197 5198 5199 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5200 // If the enclosing function is not dependent, then this lambda is 5201 // capture ready, so if we can capture this, do so. 5202 if (!EnclosingFunctionCtx->isDependentContext()) { 5203 // If the current lambda and all enclosing lambdas can capture 'this' - 5204 // then go ahead and capture 'this' (since our unresolved overload set 5205 // contains at least one non-static member function). 5206 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5207 S.CheckCXXThisCapture(CallLoc); 5208 } else if (S.CurContext->isDependentContext()) { 5209 // ... since this is an implicit member reference, that might potentially 5210 // involve a 'this' capture, mark 'this' for potential capture in 5211 // enclosing lambdas. 5212 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5213 CurLSI->addPotentialThisCapture(CallLoc); 5214 } 5215 } 5216 5217 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5218 /// This provides the location of the left/right parens and a list of comma 5219 /// locations. 5220 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5221 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5222 Expr *ExecConfig, bool IsExecConfig) { 5223 // Since this might be a postfix expression, get rid of ParenListExprs. 5224 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5225 if (Result.isInvalid()) return ExprError(); 5226 Fn = Result.get(); 5227 5228 if (checkArgsForPlaceholders(*this, ArgExprs)) 5229 return ExprError(); 5230 5231 if (getLangOpts().CPlusPlus) { 5232 // If this is a pseudo-destructor expression, build the call immediately. 5233 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5234 if (!ArgExprs.empty()) { 5235 // Pseudo-destructor calls should not have any arguments. 5236 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5237 << FixItHint::CreateRemoval( 5238 SourceRange(ArgExprs.front()->getLocStart(), 5239 ArgExprs.back()->getLocEnd())); 5240 } 5241 5242 return new (Context) 5243 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5244 } 5245 if (Fn->getType() == Context.PseudoObjectTy) { 5246 ExprResult result = CheckPlaceholderExpr(Fn); 5247 if (result.isInvalid()) return ExprError(); 5248 Fn = result.get(); 5249 } 5250 5251 // Determine whether this is a dependent call inside a C++ template, 5252 // in which case we won't do any semantic analysis now. 5253 bool Dependent = false; 5254 if (Fn->isTypeDependent()) 5255 Dependent = true; 5256 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5257 Dependent = true; 5258 5259 if (Dependent) { 5260 if (ExecConfig) { 5261 return new (Context) CUDAKernelCallExpr( 5262 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5263 Context.DependentTy, VK_RValue, RParenLoc); 5264 } else { 5265 5266 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5267 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5268 Fn->getLocStart()); 5269 5270 return new (Context) CallExpr( 5271 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5272 } 5273 } 5274 5275 // Determine whether this is a call to an object (C++ [over.call.object]). 5276 if (Fn->getType()->isRecordType()) 5277 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5278 RParenLoc); 5279 5280 if (Fn->getType() == Context.UnknownAnyTy) { 5281 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5282 if (result.isInvalid()) return ExprError(); 5283 Fn = result.get(); 5284 } 5285 5286 if (Fn->getType() == Context.BoundMemberTy) { 5287 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5288 RParenLoc); 5289 } 5290 } 5291 5292 // Check for overloaded calls. This can happen even in C due to extensions. 5293 if (Fn->getType() == Context.OverloadTy) { 5294 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5295 5296 // We aren't supposed to apply this logic if there's an '&' involved. 5297 if (!find.HasFormOfMemberPointer) { 5298 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5299 return new (Context) CallExpr( 5300 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5301 OverloadExpr *ovl = find.Expression; 5302 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5303 return BuildOverloadedCallExpr( 5304 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5305 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5306 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5307 RParenLoc); 5308 } 5309 } 5310 5311 // If we're directly calling a function, get the appropriate declaration. 5312 if (Fn->getType() == Context.UnknownAnyTy) { 5313 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5314 if (result.isInvalid()) return ExprError(); 5315 Fn = result.get(); 5316 } 5317 5318 Expr *NakedFn = Fn->IgnoreParens(); 5319 5320 bool CallingNDeclIndirectly = false; 5321 NamedDecl *NDecl = nullptr; 5322 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5323 if (UnOp->getOpcode() == UO_AddrOf) { 5324 CallingNDeclIndirectly = true; 5325 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5326 } 5327 } 5328 5329 if (isa<DeclRefExpr>(NakedFn)) { 5330 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5331 5332 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5333 if (FDecl && FDecl->getBuiltinID()) { 5334 // Rewrite the function decl for this builtin by replacing parameters 5335 // with no explicit address space with the address space of the arguments 5336 // in ArgExprs. 5337 if ((FDecl = 5338 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5339 NDecl = FDecl; 5340 Fn = DeclRefExpr::Create( 5341 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5342 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5343 } 5344 } 5345 } else if (isa<MemberExpr>(NakedFn)) 5346 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5347 5348 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5349 if (CallingNDeclIndirectly && 5350 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5351 Fn->getLocStart())) 5352 return ExprError(); 5353 5354 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5355 return ExprError(); 5356 5357 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5358 } 5359 5360 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5361 ExecConfig, IsExecConfig); 5362 } 5363 5364 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5365 /// 5366 /// __builtin_astype( value, dst type ) 5367 /// 5368 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5369 SourceLocation BuiltinLoc, 5370 SourceLocation RParenLoc) { 5371 ExprValueKind VK = VK_RValue; 5372 ExprObjectKind OK = OK_Ordinary; 5373 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5374 QualType SrcTy = E->getType(); 5375 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5376 return ExprError(Diag(BuiltinLoc, 5377 diag::err_invalid_astype_of_different_size) 5378 << DstTy 5379 << SrcTy 5380 << E->getSourceRange()); 5381 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5382 } 5383 5384 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5385 /// provided arguments. 5386 /// 5387 /// __builtin_convertvector( value, dst type ) 5388 /// 5389 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5390 SourceLocation BuiltinLoc, 5391 SourceLocation RParenLoc) { 5392 TypeSourceInfo *TInfo; 5393 GetTypeFromParser(ParsedDestTy, &TInfo); 5394 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5395 } 5396 5397 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5398 /// i.e. an expression not of \p OverloadTy. The expression should 5399 /// unary-convert to an expression of function-pointer or 5400 /// block-pointer type. 5401 /// 5402 /// \param NDecl the declaration being called, if available 5403 ExprResult 5404 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5405 SourceLocation LParenLoc, 5406 ArrayRef<Expr *> Args, 5407 SourceLocation RParenLoc, 5408 Expr *Config, bool IsExecConfig) { 5409 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5410 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5411 5412 // Functions with 'interrupt' attribute cannot be called directly. 5413 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5414 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5415 return ExprError(); 5416 } 5417 5418 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5419 // so there's some risk when calling out to non-interrupt handler functions 5420 // that the callee might not preserve them. This is easy to diagnose here, 5421 // but can be very challenging to debug. 5422 if (auto *Caller = getCurFunctionDecl()) 5423 if (Caller->hasAttr<ARMInterruptAttr>()) { 5424 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5425 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5426 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5427 } 5428 5429 // Promote the function operand. 5430 // We special-case function promotion here because we only allow promoting 5431 // builtin functions to function pointers in the callee of a call. 5432 ExprResult Result; 5433 if (BuiltinID && 5434 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5435 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5436 CK_BuiltinFnToFnPtr).get(); 5437 } else { 5438 Result = CallExprUnaryConversions(Fn); 5439 } 5440 if (Result.isInvalid()) 5441 return ExprError(); 5442 Fn = Result.get(); 5443 5444 // Make the call expr early, before semantic checks. This guarantees cleanup 5445 // of arguments and function on error. 5446 CallExpr *TheCall; 5447 if (Config) 5448 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5449 cast<CallExpr>(Config), Args, 5450 Context.BoolTy, VK_RValue, 5451 RParenLoc); 5452 else 5453 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5454 VK_RValue, RParenLoc); 5455 5456 if (!getLangOpts().CPlusPlus) { 5457 // C cannot always handle TypoExpr nodes in builtin calls and direct 5458 // function calls as their argument checking don't necessarily handle 5459 // dependent types properly, so make sure any TypoExprs have been 5460 // dealt with. 5461 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5462 if (!Result.isUsable()) return ExprError(); 5463 TheCall = dyn_cast<CallExpr>(Result.get()); 5464 if (!TheCall) return Result; 5465 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5466 } 5467 5468 // Bail out early if calling a builtin with custom typechecking. 5469 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5470 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5471 5472 retry: 5473 const FunctionType *FuncT; 5474 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5475 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5476 // have type pointer to function". 5477 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5478 if (!FuncT) 5479 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5480 << Fn->getType() << Fn->getSourceRange()); 5481 } else if (const BlockPointerType *BPT = 5482 Fn->getType()->getAs<BlockPointerType>()) { 5483 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5484 } else { 5485 // Handle calls to expressions of unknown-any type. 5486 if (Fn->getType() == Context.UnknownAnyTy) { 5487 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5488 if (rewrite.isInvalid()) return ExprError(); 5489 Fn = rewrite.get(); 5490 TheCall->setCallee(Fn); 5491 goto retry; 5492 } 5493 5494 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5495 << Fn->getType() << Fn->getSourceRange()); 5496 } 5497 5498 if (getLangOpts().CUDA) { 5499 if (Config) { 5500 // CUDA: Kernel calls must be to global functions 5501 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5502 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5503 << FDecl->getName() << Fn->getSourceRange()); 5504 5505 // CUDA: Kernel function must have 'void' return type 5506 if (!FuncT->getReturnType()->isVoidType()) 5507 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5508 << Fn->getType() << Fn->getSourceRange()); 5509 } else { 5510 // CUDA: Calls to global functions must be configured 5511 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5512 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5513 << FDecl->getName() << Fn->getSourceRange()); 5514 } 5515 } 5516 5517 // Check for a valid return type 5518 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5519 FDecl)) 5520 return ExprError(); 5521 5522 // We know the result type of the call, set it. 5523 TheCall->setType(FuncT->getCallResultType(Context)); 5524 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5525 5526 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5527 if (Proto) { 5528 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5529 IsExecConfig)) 5530 return ExprError(); 5531 } else { 5532 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5533 5534 if (FDecl) { 5535 // Check if we have too few/too many template arguments, based 5536 // on our knowledge of the function definition. 5537 const FunctionDecl *Def = nullptr; 5538 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5539 Proto = Def->getType()->getAs<FunctionProtoType>(); 5540 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5541 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5542 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5543 } 5544 5545 // If the function we're calling isn't a function prototype, but we have 5546 // a function prototype from a prior declaratiom, use that prototype. 5547 if (!FDecl->hasPrototype()) 5548 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5549 } 5550 5551 // Promote the arguments (C99 6.5.2.2p6). 5552 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5553 Expr *Arg = Args[i]; 5554 5555 if (Proto && i < Proto->getNumParams()) { 5556 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5557 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5558 ExprResult ArgE = 5559 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5560 if (ArgE.isInvalid()) 5561 return true; 5562 5563 Arg = ArgE.getAs<Expr>(); 5564 5565 } else { 5566 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5567 5568 if (ArgE.isInvalid()) 5569 return true; 5570 5571 Arg = ArgE.getAs<Expr>(); 5572 } 5573 5574 if (RequireCompleteType(Arg->getLocStart(), 5575 Arg->getType(), 5576 diag::err_call_incomplete_argument, Arg)) 5577 return ExprError(); 5578 5579 TheCall->setArg(i, Arg); 5580 } 5581 } 5582 5583 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5584 if (!Method->isStatic()) 5585 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5586 << Fn->getSourceRange()); 5587 5588 // Check for sentinels 5589 if (NDecl) 5590 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5591 5592 // Do special checking on direct calls to functions. 5593 if (FDecl) { 5594 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5595 return ExprError(); 5596 5597 if (BuiltinID) 5598 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5599 } else if (NDecl) { 5600 if (CheckPointerCall(NDecl, TheCall, Proto)) 5601 return ExprError(); 5602 } else { 5603 if (CheckOtherCall(TheCall, Proto)) 5604 return ExprError(); 5605 } 5606 5607 return MaybeBindToTemporary(TheCall); 5608 } 5609 5610 ExprResult 5611 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5612 SourceLocation RParenLoc, Expr *InitExpr) { 5613 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5614 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5615 5616 TypeSourceInfo *TInfo; 5617 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5618 if (!TInfo) 5619 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5620 5621 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5622 } 5623 5624 ExprResult 5625 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5626 SourceLocation RParenLoc, Expr *LiteralExpr) { 5627 QualType literalType = TInfo->getType(); 5628 5629 if (literalType->isArrayType()) { 5630 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5631 diag::err_illegal_decl_array_incomplete_type, 5632 SourceRange(LParenLoc, 5633 LiteralExpr->getSourceRange().getEnd()))) 5634 return ExprError(); 5635 if (literalType->isVariableArrayType()) 5636 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5637 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5638 } else if (!literalType->isDependentType() && 5639 RequireCompleteType(LParenLoc, literalType, 5640 diag::err_typecheck_decl_incomplete_type, 5641 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5642 return ExprError(); 5643 5644 InitializedEntity Entity 5645 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5646 InitializationKind Kind 5647 = InitializationKind::CreateCStyleCast(LParenLoc, 5648 SourceRange(LParenLoc, RParenLoc), 5649 /*InitList=*/true); 5650 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5651 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5652 &literalType); 5653 if (Result.isInvalid()) 5654 return ExprError(); 5655 LiteralExpr = Result.get(); 5656 5657 bool isFileScope = !CurContext->isFunctionOrMethod(); 5658 if (isFileScope && 5659 !LiteralExpr->isTypeDependent() && 5660 !LiteralExpr->isValueDependent() && 5661 !literalType->isDependentType()) { // 6.5.2.5p3 5662 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5663 return ExprError(); 5664 } 5665 5666 // In C, compound literals are l-values for some reason. 5667 // For GCC compatibility, in C++, file-scope array compound literals with 5668 // constant initializers are also l-values, and compound literals are 5669 // otherwise prvalues. 5670 // 5671 // (GCC also treats C++ list-initialized file-scope array prvalues with 5672 // constant initializers as l-values, but that's non-conforming, so we don't 5673 // follow it there.) 5674 // 5675 // FIXME: It would be better to handle the lvalue cases as materializing and 5676 // lifetime-extending a temporary object, but our materialized temporaries 5677 // representation only supports lifetime extension from a variable, not "out 5678 // of thin air". 5679 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5680 // is bound to the result of applying array-to-pointer decay to the compound 5681 // literal. 5682 // FIXME: GCC supports compound literals of reference type, which should 5683 // obviously have a value kind derived from the kind of reference involved. 5684 ExprValueKind VK = 5685 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5686 ? VK_RValue 5687 : VK_LValue; 5688 5689 return MaybeBindToTemporary( 5690 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5691 VK, LiteralExpr, isFileScope)); 5692 } 5693 5694 ExprResult 5695 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5696 SourceLocation RBraceLoc) { 5697 // Immediately handle non-overload placeholders. Overloads can be 5698 // resolved contextually, but everything else here can't. 5699 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5700 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5701 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5702 5703 // Ignore failures; dropping the entire initializer list because 5704 // of one failure would be terrible for indexing/etc. 5705 if (result.isInvalid()) continue; 5706 5707 InitArgList[I] = result.get(); 5708 } 5709 } 5710 5711 // Semantic analysis for initializers is done by ActOnDeclarator() and 5712 // CheckInitializer() - it requires knowledge of the object being intialized. 5713 5714 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5715 RBraceLoc); 5716 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5717 return E; 5718 } 5719 5720 /// Do an explicit extend of the given block pointer if we're in ARC. 5721 void Sema::maybeExtendBlockObject(ExprResult &E) { 5722 assert(E.get()->getType()->isBlockPointerType()); 5723 assert(E.get()->isRValue()); 5724 5725 // Only do this in an r-value context. 5726 if (!getLangOpts().ObjCAutoRefCount) return; 5727 5728 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5729 CK_ARCExtendBlockObject, E.get(), 5730 /*base path*/ nullptr, VK_RValue); 5731 Cleanup.setExprNeedsCleanups(true); 5732 } 5733 5734 /// Prepare a conversion of the given expression to an ObjC object 5735 /// pointer type. 5736 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5737 QualType type = E.get()->getType(); 5738 if (type->isObjCObjectPointerType()) { 5739 return CK_BitCast; 5740 } else if (type->isBlockPointerType()) { 5741 maybeExtendBlockObject(E); 5742 return CK_BlockPointerToObjCPointerCast; 5743 } else { 5744 assert(type->isPointerType()); 5745 return CK_CPointerToObjCPointerCast; 5746 } 5747 } 5748 5749 /// Prepares for a scalar cast, performing all the necessary stages 5750 /// except the final cast and returning the kind required. 5751 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5752 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5753 // Also, callers should have filtered out the invalid cases with 5754 // pointers. Everything else should be possible. 5755 5756 QualType SrcTy = Src.get()->getType(); 5757 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5758 return CK_NoOp; 5759 5760 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5761 case Type::STK_MemberPointer: 5762 llvm_unreachable("member pointer type in C"); 5763 5764 case Type::STK_CPointer: 5765 case Type::STK_BlockPointer: 5766 case Type::STK_ObjCObjectPointer: 5767 switch (DestTy->getScalarTypeKind()) { 5768 case Type::STK_CPointer: { 5769 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5770 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5771 if (SrcAS != DestAS) 5772 return CK_AddressSpaceConversion; 5773 return CK_BitCast; 5774 } 5775 case Type::STK_BlockPointer: 5776 return (SrcKind == Type::STK_BlockPointer 5777 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5778 case Type::STK_ObjCObjectPointer: 5779 if (SrcKind == Type::STK_ObjCObjectPointer) 5780 return CK_BitCast; 5781 if (SrcKind == Type::STK_CPointer) 5782 return CK_CPointerToObjCPointerCast; 5783 maybeExtendBlockObject(Src); 5784 return CK_BlockPointerToObjCPointerCast; 5785 case Type::STK_Bool: 5786 return CK_PointerToBoolean; 5787 case Type::STK_Integral: 5788 return CK_PointerToIntegral; 5789 case Type::STK_Floating: 5790 case Type::STK_FloatingComplex: 5791 case Type::STK_IntegralComplex: 5792 case Type::STK_MemberPointer: 5793 llvm_unreachable("illegal cast from pointer"); 5794 } 5795 llvm_unreachable("Should have returned before this"); 5796 5797 case Type::STK_Bool: // casting from bool is like casting from an integer 5798 case Type::STK_Integral: 5799 switch (DestTy->getScalarTypeKind()) { 5800 case Type::STK_CPointer: 5801 case Type::STK_ObjCObjectPointer: 5802 case Type::STK_BlockPointer: 5803 if (Src.get()->isNullPointerConstant(Context, 5804 Expr::NPC_ValueDependentIsNull)) 5805 return CK_NullToPointer; 5806 return CK_IntegralToPointer; 5807 case Type::STK_Bool: 5808 return CK_IntegralToBoolean; 5809 case Type::STK_Integral: 5810 return CK_IntegralCast; 5811 case Type::STK_Floating: 5812 return CK_IntegralToFloating; 5813 case Type::STK_IntegralComplex: 5814 Src = ImpCastExprToType(Src.get(), 5815 DestTy->castAs<ComplexType>()->getElementType(), 5816 CK_IntegralCast); 5817 return CK_IntegralRealToComplex; 5818 case Type::STK_FloatingComplex: 5819 Src = ImpCastExprToType(Src.get(), 5820 DestTy->castAs<ComplexType>()->getElementType(), 5821 CK_IntegralToFloating); 5822 return CK_FloatingRealToComplex; 5823 case Type::STK_MemberPointer: 5824 llvm_unreachable("member pointer type in C"); 5825 } 5826 llvm_unreachable("Should have returned before this"); 5827 5828 case Type::STK_Floating: 5829 switch (DestTy->getScalarTypeKind()) { 5830 case Type::STK_Floating: 5831 return CK_FloatingCast; 5832 case Type::STK_Bool: 5833 return CK_FloatingToBoolean; 5834 case Type::STK_Integral: 5835 return CK_FloatingToIntegral; 5836 case Type::STK_FloatingComplex: 5837 Src = ImpCastExprToType(Src.get(), 5838 DestTy->castAs<ComplexType>()->getElementType(), 5839 CK_FloatingCast); 5840 return CK_FloatingRealToComplex; 5841 case Type::STK_IntegralComplex: 5842 Src = ImpCastExprToType(Src.get(), 5843 DestTy->castAs<ComplexType>()->getElementType(), 5844 CK_FloatingToIntegral); 5845 return CK_IntegralRealToComplex; 5846 case Type::STK_CPointer: 5847 case Type::STK_ObjCObjectPointer: 5848 case Type::STK_BlockPointer: 5849 llvm_unreachable("valid float->pointer cast?"); 5850 case Type::STK_MemberPointer: 5851 llvm_unreachable("member pointer type in C"); 5852 } 5853 llvm_unreachable("Should have returned before this"); 5854 5855 case Type::STK_FloatingComplex: 5856 switch (DestTy->getScalarTypeKind()) { 5857 case Type::STK_FloatingComplex: 5858 return CK_FloatingComplexCast; 5859 case Type::STK_IntegralComplex: 5860 return CK_FloatingComplexToIntegralComplex; 5861 case Type::STK_Floating: { 5862 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5863 if (Context.hasSameType(ET, DestTy)) 5864 return CK_FloatingComplexToReal; 5865 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5866 return CK_FloatingCast; 5867 } 5868 case Type::STK_Bool: 5869 return CK_FloatingComplexToBoolean; 5870 case Type::STK_Integral: 5871 Src = ImpCastExprToType(Src.get(), 5872 SrcTy->castAs<ComplexType>()->getElementType(), 5873 CK_FloatingComplexToReal); 5874 return CK_FloatingToIntegral; 5875 case Type::STK_CPointer: 5876 case Type::STK_ObjCObjectPointer: 5877 case Type::STK_BlockPointer: 5878 llvm_unreachable("valid complex float->pointer cast?"); 5879 case Type::STK_MemberPointer: 5880 llvm_unreachable("member pointer type in C"); 5881 } 5882 llvm_unreachable("Should have returned before this"); 5883 5884 case Type::STK_IntegralComplex: 5885 switch (DestTy->getScalarTypeKind()) { 5886 case Type::STK_FloatingComplex: 5887 return CK_IntegralComplexToFloatingComplex; 5888 case Type::STK_IntegralComplex: 5889 return CK_IntegralComplexCast; 5890 case Type::STK_Integral: { 5891 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5892 if (Context.hasSameType(ET, DestTy)) 5893 return CK_IntegralComplexToReal; 5894 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5895 return CK_IntegralCast; 5896 } 5897 case Type::STK_Bool: 5898 return CK_IntegralComplexToBoolean; 5899 case Type::STK_Floating: 5900 Src = ImpCastExprToType(Src.get(), 5901 SrcTy->castAs<ComplexType>()->getElementType(), 5902 CK_IntegralComplexToReal); 5903 return CK_IntegralToFloating; 5904 case Type::STK_CPointer: 5905 case Type::STK_ObjCObjectPointer: 5906 case Type::STK_BlockPointer: 5907 llvm_unreachable("valid complex int->pointer cast?"); 5908 case Type::STK_MemberPointer: 5909 llvm_unreachable("member pointer type in C"); 5910 } 5911 llvm_unreachable("Should have returned before this"); 5912 } 5913 5914 llvm_unreachable("Unhandled scalar cast"); 5915 } 5916 5917 static bool breakDownVectorType(QualType type, uint64_t &len, 5918 QualType &eltType) { 5919 // Vectors are simple. 5920 if (const VectorType *vecType = type->getAs<VectorType>()) { 5921 len = vecType->getNumElements(); 5922 eltType = vecType->getElementType(); 5923 assert(eltType->isScalarType()); 5924 return true; 5925 } 5926 5927 // We allow lax conversion to and from non-vector types, but only if 5928 // they're real types (i.e. non-complex, non-pointer scalar types). 5929 if (!type->isRealType()) return false; 5930 5931 len = 1; 5932 eltType = type; 5933 return true; 5934 } 5935 5936 /// Are the two types lax-compatible vector types? That is, given 5937 /// that one of them is a vector, do they have equal storage sizes, 5938 /// where the storage size is the number of elements times the element 5939 /// size? 5940 /// 5941 /// This will also return false if either of the types is neither a 5942 /// vector nor a real type. 5943 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5944 assert(destTy->isVectorType() || srcTy->isVectorType()); 5945 5946 // Disallow lax conversions between scalars and ExtVectors (these 5947 // conversions are allowed for other vector types because common headers 5948 // depend on them). Most scalar OP ExtVector cases are handled by the 5949 // splat path anyway, which does what we want (convert, not bitcast). 5950 // What this rules out for ExtVectors is crazy things like char4*float. 5951 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5952 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5953 5954 uint64_t srcLen, destLen; 5955 QualType srcEltTy, destEltTy; 5956 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5957 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5958 5959 // ASTContext::getTypeSize will return the size rounded up to a 5960 // power of 2, so instead of using that, we need to use the raw 5961 // element size multiplied by the element count. 5962 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5963 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5964 5965 return (srcLen * srcEltSize == destLen * destEltSize); 5966 } 5967 5968 /// Is this a legal conversion between two types, one of which is 5969 /// known to be a vector type? 5970 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5971 assert(destTy->isVectorType() || srcTy->isVectorType()); 5972 5973 if (!Context.getLangOpts().LaxVectorConversions) 5974 return false; 5975 return areLaxCompatibleVectorTypes(srcTy, destTy); 5976 } 5977 5978 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5979 CastKind &Kind) { 5980 assert(VectorTy->isVectorType() && "Not a vector type!"); 5981 5982 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5983 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5984 return Diag(R.getBegin(), 5985 Ty->isVectorType() ? 5986 diag::err_invalid_conversion_between_vectors : 5987 diag::err_invalid_conversion_between_vector_and_integer) 5988 << VectorTy << Ty << R; 5989 } else 5990 return Diag(R.getBegin(), 5991 diag::err_invalid_conversion_between_vector_and_scalar) 5992 << VectorTy << Ty << R; 5993 5994 Kind = CK_BitCast; 5995 return false; 5996 } 5997 5998 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5999 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6000 6001 if (DestElemTy == SplattedExpr->getType()) 6002 return SplattedExpr; 6003 6004 assert(DestElemTy->isFloatingType() || 6005 DestElemTy->isIntegralOrEnumerationType()); 6006 6007 CastKind CK; 6008 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6009 // OpenCL requires that we convert `true` boolean expressions to -1, but 6010 // only when splatting vectors. 6011 if (DestElemTy->isFloatingType()) { 6012 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6013 // in two steps: boolean to signed integral, then to floating. 6014 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6015 CK_BooleanToSignedIntegral); 6016 SplattedExpr = CastExprRes.get(); 6017 CK = CK_IntegralToFloating; 6018 } else { 6019 CK = CK_BooleanToSignedIntegral; 6020 } 6021 } else { 6022 ExprResult CastExprRes = SplattedExpr; 6023 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6024 if (CastExprRes.isInvalid()) 6025 return ExprError(); 6026 SplattedExpr = CastExprRes.get(); 6027 } 6028 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6029 } 6030 6031 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6032 Expr *CastExpr, CastKind &Kind) { 6033 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6034 6035 QualType SrcTy = CastExpr->getType(); 6036 6037 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6038 // an ExtVectorType. 6039 // In OpenCL, casts between vectors of different types are not allowed. 6040 // (See OpenCL 6.2). 6041 if (SrcTy->isVectorType()) { 6042 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6043 (getLangOpts().OpenCL && 6044 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6045 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6046 << DestTy << SrcTy << R; 6047 return ExprError(); 6048 } 6049 Kind = CK_BitCast; 6050 return CastExpr; 6051 } 6052 6053 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6054 // conversion will take place first from scalar to elt type, and then 6055 // splat from elt type to vector. 6056 if (SrcTy->isPointerType()) 6057 return Diag(R.getBegin(), 6058 diag::err_invalid_conversion_between_vector_and_scalar) 6059 << DestTy << SrcTy << R; 6060 6061 Kind = CK_VectorSplat; 6062 return prepareVectorSplat(DestTy, CastExpr); 6063 } 6064 6065 ExprResult 6066 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6067 Declarator &D, ParsedType &Ty, 6068 SourceLocation RParenLoc, Expr *CastExpr) { 6069 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6070 "ActOnCastExpr(): missing type or expr"); 6071 6072 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6073 if (D.isInvalidType()) 6074 return ExprError(); 6075 6076 if (getLangOpts().CPlusPlus) { 6077 // Check that there are no default arguments (C++ only). 6078 CheckExtraCXXDefaultArguments(D); 6079 } else { 6080 // Make sure any TypoExprs have been dealt with. 6081 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6082 if (!Res.isUsable()) 6083 return ExprError(); 6084 CastExpr = Res.get(); 6085 } 6086 6087 checkUnusedDeclAttributes(D); 6088 6089 QualType castType = castTInfo->getType(); 6090 Ty = CreateParsedType(castType, castTInfo); 6091 6092 bool isVectorLiteral = false; 6093 6094 // Check for an altivec or OpenCL literal, 6095 // i.e. all the elements are integer constants. 6096 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6097 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6098 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6099 && castType->isVectorType() && (PE || PLE)) { 6100 if (PLE && PLE->getNumExprs() == 0) { 6101 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6102 return ExprError(); 6103 } 6104 if (PE || PLE->getNumExprs() == 1) { 6105 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6106 if (!E->getType()->isVectorType()) 6107 isVectorLiteral = true; 6108 } 6109 else 6110 isVectorLiteral = true; 6111 } 6112 6113 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6114 // then handle it as such. 6115 if (isVectorLiteral) 6116 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6117 6118 // If the Expr being casted is a ParenListExpr, handle it specially. 6119 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6120 // sequence of BinOp comma operators. 6121 if (isa<ParenListExpr>(CastExpr)) { 6122 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6123 if (Result.isInvalid()) return ExprError(); 6124 CastExpr = Result.get(); 6125 } 6126 6127 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6128 !getSourceManager().isInSystemMacro(LParenLoc)) 6129 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6130 6131 CheckTollFreeBridgeCast(castType, CastExpr); 6132 6133 CheckObjCBridgeRelatedCast(castType, CastExpr); 6134 6135 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6136 6137 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6138 } 6139 6140 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6141 SourceLocation RParenLoc, Expr *E, 6142 TypeSourceInfo *TInfo) { 6143 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6144 "Expected paren or paren list expression"); 6145 6146 Expr **exprs; 6147 unsigned numExprs; 6148 Expr *subExpr; 6149 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6150 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6151 LiteralLParenLoc = PE->getLParenLoc(); 6152 LiteralRParenLoc = PE->getRParenLoc(); 6153 exprs = PE->getExprs(); 6154 numExprs = PE->getNumExprs(); 6155 } else { // isa<ParenExpr> by assertion at function entrance 6156 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6157 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6158 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6159 exprs = &subExpr; 6160 numExprs = 1; 6161 } 6162 6163 QualType Ty = TInfo->getType(); 6164 assert(Ty->isVectorType() && "Expected vector type"); 6165 6166 SmallVector<Expr *, 8> initExprs; 6167 const VectorType *VTy = Ty->getAs<VectorType>(); 6168 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6169 6170 // '(...)' form of vector initialization in AltiVec: the number of 6171 // initializers must be one or must match the size of the vector. 6172 // If a single value is specified in the initializer then it will be 6173 // replicated to all the components of the vector 6174 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6175 // The number of initializers must be one or must match the size of the 6176 // vector. If a single value is specified in the initializer then it will 6177 // be replicated to all the components of the vector 6178 if (numExprs == 1) { 6179 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6180 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6181 if (Literal.isInvalid()) 6182 return ExprError(); 6183 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6184 PrepareScalarCast(Literal, ElemTy)); 6185 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6186 } 6187 else if (numExprs < numElems) { 6188 Diag(E->getExprLoc(), 6189 diag::err_incorrect_number_of_vector_initializers); 6190 return ExprError(); 6191 } 6192 else 6193 initExprs.append(exprs, exprs + numExprs); 6194 } 6195 else { 6196 // For OpenCL, when the number of initializers is a single value, 6197 // it will be replicated to all components of the vector. 6198 if (getLangOpts().OpenCL && 6199 VTy->getVectorKind() == VectorType::GenericVector && 6200 numExprs == 1) { 6201 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6202 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6203 if (Literal.isInvalid()) 6204 return ExprError(); 6205 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6206 PrepareScalarCast(Literal, ElemTy)); 6207 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6208 } 6209 6210 initExprs.append(exprs, exprs + numExprs); 6211 } 6212 // FIXME: This means that pretty-printing the final AST will produce curly 6213 // braces instead of the original commas. 6214 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6215 initExprs, LiteralRParenLoc); 6216 initE->setType(Ty); 6217 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6218 } 6219 6220 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6221 /// the ParenListExpr into a sequence of comma binary operators. 6222 ExprResult 6223 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6224 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6225 if (!E) 6226 return OrigExpr; 6227 6228 ExprResult Result(E->getExpr(0)); 6229 6230 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6231 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6232 E->getExpr(i)); 6233 6234 if (Result.isInvalid()) return ExprError(); 6235 6236 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6237 } 6238 6239 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6240 SourceLocation R, 6241 MultiExprArg Val) { 6242 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6243 return expr; 6244 } 6245 6246 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6247 /// constant and the other is not a pointer. Returns true if a diagnostic is 6248 /// emitted. 6249 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6250 SourceLocation QuestionLoc) { 6251 Expr *NullExpr = LHSExpr; 6252 Expr *NonPointerExpr = RHSExpr; 6253 Expr::NullPointerConstantKind NullKind = 6254 NullExpr->isNullPointerConstant(Context, 6255 Expr::NPC_ValueDependentIsNotNull); 6256 6257 if (NullKind == Expr::NPCK_NotNull) { 6258 NullExpr = RHSExpr; 6259 NonPointerExpr = LHSExpr; 6260 NullKind = 6261 NullExpr->isNullPointerConstant(Context, 6262 Expr::NPC_ValueDependentIsNotNull); 6263 } 6264 6265 if (NullKind == Expr::NPCK_NotNull) 6266 return false; 6267 6268 if (NullKind == Expr::NPCK_ZeroExpression) 6269 return false; 6270 6271 if (NullKind == Expr::NPCK_ZeroLiteral) { 6272 // In this case, check to make sure that we got here from a "NULL" 6273 // string in the source code. 6274 NullExpr = NullExpr->IgnoreParenImpCasts(); 6275 SourceLocation loc = NullExpr->getExprLoc(); 6276 if (!findMacroSpelling(loc, "NULL")) 6277 return false; 6278 } 6279 6280 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6281 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6282 << NonPointerExpr->getType() << DiagType 6283 << NonPointerExpr->getSourceRange(); 6284 return true; 6285 } 6286 6287 /// \brief Return false if the condition expression is valid, true otherwise. 6288 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6289 QualType CondTy = Cond->getType(); 6290 6291 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6292 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6293 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6294 << CondTy << Cond->getSourceRange(); 6295 return true; 6296 } 6297 6298 // C99 6.5.15p2 6299 if (CondTy->isScalarType()) return false; 6300 6301 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6302 << CondTy << Cond->getSourceRange(); 6303 return true; 6304 } 6305 6306 /// \brief Handle when one or both operands are void type. 6307 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6308 ExprResult &RHS) { 6309 Expr *LHSExpr = LHS.get(); 6310 Expr *RHSExpr = RHS.get(); 6311 6312 if (!LHSExpr->getType()->isVoidType()) 6313 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6314 << RHSExpr->getSourceRange(); 6315 if (!RHSExpr->getType()->isVoidType()) 6316 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6317 << LHSExpr->getSourceRange(); 6318 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6319 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6320 return S.Context.VoidTy; 6321 } 6322 6323 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6324 /// true otherwise. 6325 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6326 QualType PointerTy) { 6327 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6328 !NullExpr.get()->isNullPointerConstant(S.Context, 6329 Expr::NPC_ValueDependentIsNull)) 6330 return true; 6331 6332 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6333 return false; 6334 } 6335 6336 /// \brief Checks compatibility between two pointers and return the resulting 6337 /// type. 6338 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6339 ExprResult &RHS, 6340 SourceLocation Loc) { 6341 QualType LHSTy = LHS.get()->getType(); 6342 QualType RHSTy = RHS.get()->getType(); 6343 6344 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6345 // Two identical pointers types are always compatible. 6346 return LHSTy; 6347 } 6348 6349 QualType lhptee, rhptee; 6350 6351 // Get the pointee types. 6352 bool IsBlockPointer = false; 6353 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6354 lhptee = LHSBTy->getPointeeType(); 6355 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6356 IsBlockPointer = true; 6357 } else { 6358 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6359 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6360 } 6361 6362 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6363 // differently qualified versions of compatible types, the result type is 6364 // a pointer to an appropriately qualified version of the composite 6365 // type. 6366 6367 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6368 // clause doesn't make sense for our extensions. E.g. address space 2 should 6369 // be incompatible with address space 3: they may live on different devices or 6370 // anything. 6371 Qualifiers lhQual = lhptee.getQualifiers(); 6372 Qualifiers rhQual = rhptee.getQualifiers(); 6373 6374 LangAS ResultAddrSpace = LangAS::Default; 6375 LangAS LAddrSpace = lhQual.getAddressSpace(); 6376 LangAS RAddrSpace = rhQual.getAddressSpace(); 6377 if (S.getLangOpts().OpenCL) { 6378 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6379 // spaces is disallowed. 6380 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6381 ResultAddrSpace = LAddrSpace; 6382 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6383 ResultAddrSpace = RAddrSpace; 6384 else { 6385 S.Diag(Loc, 6386 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6387 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6388 << RHS.get()->getSourceRange(); 6389 return QualType(); 6390 } 6391 } 6392 6393 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6394 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6395 lhQual.removeCVRQualifiers(); 6396 rhQual.removeCVRQualifiers(); 6397 6398 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6399 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6400 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6401 // qual types are compatible iff 6402 // * corresponded types are compatible 6403 // * CVR qualifiers are equal 6404 // * address spaces are equal 6405 // Thus for conditional operator we merge CVR and address space unqualified 6406 // pointees and if there is a composite type we return a pointer to it with 6407 // merged qualifiers. 6408 if (S.getLangOpts().OpenCL) { 6409 LHSCastKind = LAddrSpace == ResultAddrSpace 6410 ? CK_BitCast 6411 : CK_AddressSpaceConversion; 6412 RHSCastKind = RAddrSpace == ResultAddrSpace 6413 ? CK_BitCast 6414 : CK_AddressSpaceConversion; 6415 lhQual.removeAddressSpace(); 6416 rhQual.removeAddressSpace(); 6417 } 6418 6419 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6420 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6421 6422 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6423 6424 if (CompositeTy.isNull()) { 6425 // In this situation, we assume void* type. No especially good 6426 // reason, but this is what gcc does, and we do have to pick 6427 // to get a consistent AST. 6428 QualType incompatTy; 6429 incompatTy = S.Context.getPointerType( 6430 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6431 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6432 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6433 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6434 // for casts between types with incompatible address space qualifiers. 6435 // For the following code the compiler produces casts between global and 6436 // local address spaces of the corresponded innermost pointees: 6437 // local int *global *a; 6438 // global int *global *b; 6439 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6440 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6441 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6442 << RHS.get()->getSourceRange(); 6443 return incompatTy; 6444 } 6445 6446 // The pointer types are compatible. 6447 // In case of OpenCL ResultTy should have the address space qualifier 6448 // which is a superset of address spaces of both the 2nd and the 3rd 6449 // operands of the conditional operator. 6450 QualType ResultTy = [&, ResultAddrSpace]() { 6451 if (S.getLangOpts().OpenCL) { 6452 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6453 CompositeQuals.setAddressSpace(ResultAddrSpace); 6454 return S.Context 6455 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6456 .withCVRQualifiers(MergedCVRQual); 6457 } 6458 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6459 }(); 6460 if (IsBlockPointer) 6461 ResultTy = S.Context.getBlockPointerType(ResultTy); 6462 else 6463 ResultTy = S.Context.getPointerType(ResultTy); 6464 6465 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6466 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6467 return ResultTy; 6468 } 6469 6470 /// \brief Return the resulting type when the operands are both block pointers. 6471 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6472 ExprResult &LHS, 6473 ExprResult &RHS, 6474 SourceLocation Loc) { 6475 QualType LHSTy = LHS.get()->getType(); 6476 QualType RHSTy = RHS.get()->getType(); 6477 6478 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6479 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6480 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6481 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6482 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6483 return destType; 6484 } 6485 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6486 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6487 << RHS.get()->getSourceRange(); 6488 return QualType(); 6489 } 6490 6491 // We have 2 block pointer types. 6492 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6493 } 6494 6495 /// \brief Return the resulting type when the operands are both pointers. 6496 static QualType 6497 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6498 ExprResult &RHS, 6499 SourceLocation Loc) { 6500 // get the pointer types 6501 QualType LHSTy = LHS.get()->getType(); 6502 QualType RHSTy = RHS.get()->getType(); 6503 6504 // get the "pointed to" types 6505 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6506 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6507 6508 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6509 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6510 // Figure out necessary qualifiers (C99 6.5.15p6) 6511 QualType destPointee 6512 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6513 QualType destType = S.Context.getPointerType(destPointee); 6514 // Add qualifiers if necessary. 6515 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6516 // Promote to void*. 6517 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6518 return destType; 6519 } 6520 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6521 QualType destPointee 6522 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6523 QualType destType = S.Context.getPointerType(destPointee); 6524 // Add qualifiers if necessary. 6525 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6526 // Promote to void*. 6527 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6528 return destType; 6529 } 6530 6531 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6532 } 6533 6534 /// \brief Return false if the first expression is not an integer and the second 6535 /// expression is not a pointer, true otherwise. 6536 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6537 Expr* PointerExpr, SourceLocation Loc, 6538 bool IsIntFirstExpr) { 6539 if (!PointerExpr->getType()->isPointerType() || 6540 !Int.get()->getType()->isIntegerType()) 6541 return false; 6542 6543 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6544 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6545 6546 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6547 << Expr1->getType() << Expr2->getType() 6548 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6549 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6550 CK_IntegralToPointer); 6551 return true; 6552 } 6553 6554 /// \brief Simple conversion between integer and floating point types. 6555 /// 6556 /// Used when handling the OpenCL conditional operator where the 6557 /// condition is a vector while the other operands are scalar. 6558 /// 6559 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6560 /// types are either integer or floating type. Between the two 6561 /// operands, the type with the higher rank is defined as the "result 6562 /// type". The other operand needs to be promoted to the same type. No 6563 /// other type promotion is allowed. We cannot use 6564 /// UsualArithmeticConversions() for this purpose, since it always 6565 /// promotes promotable types. 6566 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6567 ExprResult &RHS, 6568 SourceLocation QuestionLoc) { 6569 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6570 if (LHS.isInvalid()) 6571 return QualType(); 6572 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6573 if (RHS.isInvalid()) 6574 return QualType(); 6575 6576 // For conversion purposes, we ignore any qualifiers. 6577 // For example, "const float" and "float" are equivalent. 6578 QualType LHSType = 6579 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6580 QualType RHSType = 6581 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6582 6583 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6584 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6585 << LHSType << LHS.get()->getSourceRange(); 6586 return QualType(); 6587 } 6588 6589 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6590 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6591 << RHSType << RHS.get()->getSourceRange(); 6592 return QualType(); 6593 } 6594 6595 // If both types are identical, no conversion is needed. 6596 if (LHSType == RHSType) 6597 return LHSType; 6598 6599 // Now handle "real" floating types (i.e. float, double, long double). 6600 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6601 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6602 /*IsCompAssign = */ false); 6603 6604 // Finally, we have two differing integer types. 6605 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6606 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6607 } 6608 6609 /// \brief Convert scalar operands to a vector that matches the 6610 /// condition in length. 6611 /// 6612 /// Used when handling the OpenCL conditional operator where the 6613 /// condition is a vector while the other operands are scalar. 6614 /// 6615 /// We first compute the "result type" for the scalar operands 6616 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6617 /// into a vector of that type where the length matches the condition 6618 /// vector type. s6.11.6 requires that the element types of the result 6619 /// and the condition must have the same number of bits. 6620 static QualType 6621 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6622 QualType CondTy, SourceLocation QuestionLoc) { 6623 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6624 if (ResTy.isNull()) return QualType(); 6625 6626 const VectorType *CV = CondTy->getAs<VectorType>(); 6627 assert(CV); 6628 6629 // Determine the vector result type 6630 unsigned NumElements = CV->getNumElements(); 6631 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6632 6633 // Ensure that all types have the same number of bits 6634 if (S.Context.getTypeSize(CV->getElementType()) 6635 != S.Context.getTypeSize(ResTy)) { 6636 // Since VectorTy is created internally, it does not pretty print 6637 // with an OpenCL name. Instead, we just print a description. 6638 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6639 SmallString<64> Str; 6640 llvm::raw_svector_ostream OS(Str); 6641 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6642 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6643 << CondTy << OS.str(); 6644 return QualType(); 6645 } 6646 6647 // Convert operands to the vector result type 6648 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6649 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6650 6651 return VectorTy; 6652 } 6653 6654 /// \brief Return false if this is a valid OpenCL condition vector 6655 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6656 SourceLocation QuestionLoc) { 6657 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6658 // integral type. 6659 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6660 assert(CondTy); 6661 QualType EleTy = CondTy->getElementType(); 6662 if (EleTy->isIntegerType()) return false; 6663 6664 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6665 << Cond->getType() << Cond->getSourceRange(); 6666 return true; 6667 } 6668 6669 /// \brief Return false if the vector condition type and the vector 6670 /// result type are compatible. 6671 /// 6672 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6673 /// number of elements, and their element types have the same number 6674 /// of bits. 6675 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6676 SourceLocation QuestionLoc) { 6677 const VectorType *CV = CondTy->getAs<VectorType>(); 6678 const VectorType *RV = VecResTy->getAs<VectorType>(); 6679 assert(CV && RV); 6680 6681 if (CV->getNumElements() != RV->getNumElements()) { 6682 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6683 << CondTy << VecResTy; 6684 return true; 6685 } 6686 6687 QualType CVE = CV->getElementType(); 6688 QualType RVE = RV->getElementType(); 6689 6690 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6691 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6692 << CondTy << VecResTy; 6693 return true; 6694 } 6695 6696 return false; 6697 } 6698 6699 /// \brief Return the resulting type for the conditional operator in 6700 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6701 /// s6.3.i) when the condition is a vector type. 6702 static QualType 6703 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6704 ExprResult &LHS, ExprResult &RHS, 6705 SourceLocation QuestionLoc) { 6706 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6707 if (Cond.isInvalid()) 6708 return QualType(); 6709 QualType CondTy = Cond.get()->getType(); 6710 6711 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6712 return QualType(); 6713 6714 // If either operand is a vector then find the vector type of the 6715 // result as specified in OpenCL v1.1 s6.3.i. 6716 if (LHS.get()->getType()->isVectorType() || 6717 RHS.get()->getType()->isVectorType()) { 6718 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6719 /*isCompAssign*/false, 6720 /*AllowBothBool*/true, 6721 /*AllowBoolConversions*/false); 6722 if (VecResTy.isNull()) return QualType(); 6723 // The result type must match the condition type as specified in 6724 // OpenCL v1.1 s6.11.6. 6725 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6726 return QualType(); 6727 return VecResTy; 6728 } 6729 6730 // Both operands are scalar. 6731 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6732 } 6733 6734 /// \brief Return true if the Expr is block type 6735 static bool checkBlockType(Sema &S, const Expr *E) { 6736 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6737 QualType Ty = CE->getCallee()->getType(); 6738 if (Ty->isBlockPointerType()) { 6739 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6740 return true; 6741 } 6742 } 6743 return false; 6744 } 6745 6746 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6747 /// In that case, LHS = cond. 6748 /// C99 6.5.15 6749 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6750 ExprResult &RHS, ExprValueKind &VK, 6751 ExprObjectKind &OK, 6752 SourceLocation QuestionLoc) { 6753 6754 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6755 if (!LHSResult.isUsable()) return QualType(); 6756 LHS = LHSResult; 6757 6758 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6759 if (!RHSResult.isUsable()) return QualType(); 6760 RHS = RHSResult; 6761 6762 // C++ is sufficiently different to merit its own checker. 6763 if (getLangOpts().CPlusPlus) 6764 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6765 6766 VK = VK_RValue; 6767 OK = OK_Ordinary; 6768 6769 // The OpenCL operator with a vector condition is sufficiently 6770 // different to merit its own checker. 6771 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6772 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6773 6774 // First, check the condition. 6775 Cond = UsualUnaryConversions(Cond.get()); 6776 if (Cond.isInvalid()) 6777 return QualType(); 6778 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6779 return QualType(); 6780 6781 // Now check the two expressions. 6782 if (LHS.get()->getType()->isVectorType() || 6783 RHS.get()->getType()->isVectorType()) 6784 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6785 /*AllowBothBool*/true, 6786 /*AllowBoolConversions*/false); 6787 6788 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6789 if (LHS.isInvalid() || RHS.isInvalid()) 6790 return QualType(); 6791 6792 QualType LHSTy = LHS.get()->getType(); 6793 QualType RHSTy = RHS.get()->getType(); 6794 6795 // Diagnose attempts to convert between __float128 and long double where 6796 // such conversions currently can't be handled. 6797 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6798 Diag(QuestionLoc, 6799 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6800 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6801 return QualType(); 6802 } 6803 6804 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6805 // selection operator (?:). 6806 if (getLangOpts().OpenCL && 6807 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6808 return QualType(); 6809 } 6810 6811 // If both operands have arithmetic type, do the usual arithmetic conversions 6812 // to find a common type: C99 6.5.15p3,5. 6813 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6814 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6815 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6816 6817 return ResTy; 6818 } 6819 6820 // If both operands are the same structure or union type, the result is that 6821 // type. 6822 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6823 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6824 if (LHSRT->getDecl() == RHSRT->getDecl()) 6825 // "If both the operands have structure or union type, the result has 6826 // that type." This implies that CV qualifiers are dropped. 6827 return LHSTy.getUnqualifiedType(); 6828 // FIXME: Type of conditional expression must be complete in C mode. 6829 } 6830 6831 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6832 // The following || allows only one side to be void (a GCC-ism). 6833 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6834 return checkConditionalVoidType(*this, LHS, RHS); 6835 } 6836 6837 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6838 // the type of the other operand." 6839 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6840 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6841 6842 // All objective-c pointer type analysis is done here. 6843 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6844 QuestionLoc); 6845 if (LHS.isInvalid() || RHS.isInvalid()) 6846 return QualType(); 6847 if (!compositeType.isNull()) 6848 return compositeType; 6849 6850 6851 // Handle block pointer types. 6852 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6853 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6854 QuestionLoc); 6855 6856 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6857 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6858 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6859 QuestionLoc); 6860 6861 // GCC compatibility: soften pointer/integer mismatch. Note that 6862 // null pointers have been filtered out by this point. 6863 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6864 /*isIntFirstExpr=*/true)) 6865 return RHSTy; 6866 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6867 /*isIntFirstExpr=*/false)) 6868 return LHSTy; 6869 6870 // Emit a better diagnostic if one of the expressions is a null pointer 6871 // constant and the other is not a pointer type. In this case, the user most 6872 // likely forgot to take the address of the other expression. 6873 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6874 return QualType(); 6875 6876 // Otherwise, the operands are not compatible. 6877 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6878 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6879 << RHS.get()->getSourceRange(); 6880 return QualType(); 6881 } 6882 6883 /// FindCompositeObjCPointerType - Helper method to find composite type of 6884 /// two objective-c pointer types of the two input expressions. 6885 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6886 SourceLocation QuestionLoc) { 6887 QualType LHSTy = LHS.get()->getType(); 6888 QualType RHSTy = RHS.get()->getType(); 6889 6890 // Handle things like Class and struct objc_class*. Here we case the result 6891 // to the pseudo-builtin, because that will be implicitly cast back to the 6892 // redefinition type if an attempt is made to access its fields. 6893 if (LHSTy->isObjCClassType() && 6894 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6895 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6896 return LHSTy; 6897 } 6898 if (RHSTy->isObjCClassType() && 6899 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6900 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6901 return RHSTy; 6902 } 6903 // And the same for struct objc_object* / id 6904 if (LHSTy->isObjCIdType() && 6905 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6906 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6907 return LHSTy; 6908 } 6909 if (RHSTy->isObjCIdType() && 6910 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6911 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6912 return RHSTy; 6913 } 6914 // And the same for struct objc_selector* / SEL 6915 if (Context.isObjCSelType(LHSTy) && 6916 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6917 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6918 return LHSTy; 6919 } 6920 if (Context.isObjCSelType(RHSTy) && 6921 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6922 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6923 return RHSTy; 6924 } 6925 // Check constraints for Objective-C object pointers types. 6926 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6927 6928 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6929 // Two identical object pointer types are always compatible. 6930 return LHSTy; 6931 } 6932 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6933 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6934 QualType compositeType = LHSTy; 6935 6936 // If both operands are interfaces and either operand can be 6937 // assigned to the other, use that type as the composite 6938 // type. This allows 6939 // xxx ? (A*) a : (B*) b 6940 // where B is a subclass of A. 6941 // 6942 // Additionally, as for assignment, if either type is 'id' 6943 // allow silent coercion. Finally, if the types are 6944 // incompatible then make sure to use 'id' as the composite 6945 // type so the result is acceptable for sending messages to. 6946 6947 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6948 // It could return the composite type. 6949 if (!(compositeType = 6950 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6951 // Nothing more to do. 6952 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6953 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6954 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6955 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6956 } else if ((LHSTy->isObjCQualifiedIdType() || 6957 RHSTy->isObjCQualifiedIdType()) && 6958 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6959 // Need to handle "id<xx>" explicitly. 6960 // GCC allows qualified id and any Objective-C type to devolve to 6961 // id. Currently localizing to here until clear this should be 6962 // part of ObjCQualifiedIdTypesAreCompatible. 6963 compositeType = Context.getObjCIdType(); 6964 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6965 compositeType = Context.getObjCIdType(); 6966 } else { 6967 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6968 << LHSTy << RHSTy 6969 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6970 QualType incompatTy = Context.getObjCIdType(); 6971 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6972 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6973 return incompatTy; 6974 } 6975 // The object pointer types are compatible. 6976 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6977 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6978 return compositeType; 6979 } 6980 // Check Objective-C object pointer types and 'void *' 6981 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6982 if (getLangOpts().ObjCAutoRefCount) { 6983 // ARC forbids the implicit conversion of object pointers to 'void *', 6984 // so these types are not compatible. 6985 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6986 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6987 LHS = RHS = true; 6988 return QualType(); 6989 } 6990 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6991 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6992 QualType destPointee 6993 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6994 QualType destType = Context.getPointerType(destPointee); 6995 // Add qualifiers if necessary. 6996 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6997 // Promote to void*. 6998 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6999 return destType; 7000 } 7001 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7002 if (getLangOpts().ObjCAutoRefCount) { 7003 // ARC forbids the implicit conversion of object pointers to 'void *', 7004 // so these types are not compatible. 7005 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7006 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7007 LHS = RHS = true; 7008 return QualType(); 7009 } 7010 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7011 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7012 QualType destPointee 7013 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7014 QualType destType = Context.getPointerType(destPointee); 7015 // Add qualifiers if necessary. 7016 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7017 // Promote to void*. 7018 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7019 return destType; 7020 } 7021 return QualType(); 7022 } 7023 7024 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7025 /// ParenRange in parentheses. 7026 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7027 const PartialDiagnostic &Note, 7028 SourceRange ParenRange) { 7029 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7030 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7031 EndLoc.isValid()) { 7032 Self.Diag(Loc, Note) 7033 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7034 << FixItHint::CreateInsertion(EndLoc, ")"); 7035 } else { 7036 // We can't display the parentheses, so just show the bare note. 7037 Self.Diag(Loc, Note) << ParenRange; 7038 } 7039 } 7040 7041 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7042 return BinaryOperator::isAdditiveOp(Opc) || 7043 BinaryOperator::isMultiplicativeOp(Opc) || 7044 BinaryOperator::isShiftOp(Opc); 7045 } 7046 7047 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7048 /// expression, either using a built-in or overloaded operator, 7049 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7050 /// expression. 7051 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7052 Expr **RHSExprs) { 7053 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7054 E = E->IgnoreImpCasts(); 7055 E = E->IgnoreConversionOperator(); 7056 E = E->IgnoreImpCasts(); 7057 7058 // Built-in binary operator. 7059 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7060 if (IsArithmeticOp(OP->getOpcode())) { 7061 *Opcode = OP->getOpcode(); 7062 *RHSExprs = OP->getRHS(); 7063 return true; 7064 } 7065 } 7066 7067 // Overloaded operator. 7068 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7069 if (Call->getNumArgs() != 2) 7070 return false; 7071 7072 // Make sure this is really a binary operator that is safe to pass into 7073 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7074 OverloadedOperatorKind OO = Call->getOperator(); 7075 if (OO < OO_Plus || OO > OO_Arrow || 7076 OO == OO_PlusPlus || OO == OO_MinusMinus) 7077 return false; 7078 7079 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7080 if (IsArithmeticOp(OpKind)) { 7081 *Opcode = OpKind; 7082 *RHSExprs = Call->getArg(1); 7083 return true; 7084 } 7085 } 7086 7087 return false; 7088 } 7089 7090 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7091 /// or is a logical expression such as (x==y) which has int type, but is 7092 /// commonly interpreted as boolean. 7093 static bool ExprLooksBoolean(Expr *E) { 7094 E = E->IgnoreParenImpCasts(); 7095 7096 if (E->getType()->isBooleanType()) 7097 return true; 7098 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7099 return OP->isComparisonOp() || OP->isLogicalOp(); 7100 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7101 return OP->getOpcode() == UO_LNot; 7102 if (E->getType()->isPointerType()) 7103 return true; 7104 7105 return false; 7106 } 7107 7108 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7109 /// and binary operator are mixed in a way that suggests the programmer assumed 7110 /// the conditional operator has higher precedence, for example: 7111 /// "int x = a + someBinaryCondition ? 1 : 2". 7112 static void DiagnoseConditionalPrecedence(Sema &Self, 7113 SourceLocation OpLoc, 7114 Expr *Condition, 7115 Expr *LHSExpr, 7116 Expr *RHSExpr) { 7117 BinaryOperatorKind CondOpcode; 7118 Expr *CondRHS; 7119 7120 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7121 return; 7122 if (!ExprLooksBoolean(CondRHS)) 7123 return; 7124 7125 // The condition is an arithmetic binary expression, with a right- 7126 // hand side that looks boolean, so warn. 7127 7128 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7129 << Condition->getSourceRange() 7130 << BinaryOperator::getOpcodeStr(CondOpcode); 7131 7132 SuggestParentheses(Self, OpLoc, 7133 Self.PDiag(diag::note_precedence_silence) 7134 << BinaryOperator::getOpcodeStr(CondOpcode), 7135 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7136 7137 SuggestParentheses(Self, OpLoc, 7138 Self.PDiag(diag::note_precedence_conditional_first), 7139 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7140 } 7141 7142 /// Compute the nullability of a conditional expression. 7143 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7144 QualType LHSTy, QualType RHSTy, 7145 ASTContext &Ctx) { 7146 if (!ResTy->isAnyPointerType()) 7147 return ResTy; 7148 7149 auto GetNullability = [&Ctx](QualType Ty) { 7150 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7151 if (Kind) 7152 return *Kind; 7153 return NullabilityKind::Unspecified; 7154 }; 7155 7156 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7157 NullabilityKind MergedKind; 7158 7159 // Compute nullability of a binary conditional expression. 7160 if (IsBin) { 7161 if (LHSKind == NullabilityKind::NonNull) 7162 MergedKind = NullabilityKind::NonNull; 7163 else 7164 MergedKind = RHSKind; 7165 // Compute nullability of a normal conditional expression. 7166 } else { 7167 if (LHSKind == NullabilityKind::Nullable || 7168 RHSKind == NullabilityKind::Nullable) 7169 MergedKind = NullabilityKind::Nullable; 7170 else if (LHSKind == NullabilityKind::NonNull) 7171 MergedKind = RHSKind; 7172 else if (RHSKind == NullabilityKind::NonNull) 7173 MergedKind = LHSKind; 7174 else 7175 MergedKind = NullabilityKind::Unspecified; 7176 } 7177 7178 // Return if ResTy already has the correct nullability. 7179 if (GetNullability(ResTy) == MergedKind) 7180 return ResTy; 7181 7182 // Strip all nullability from ResTy. 7183 while (ResTy->getNullability(Ctx)) 7184 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7185 7186 // Create a new AttributedType with the new nullability kind. 7187 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7188 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7189 } 7190 7191 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7192 /// in the case of a the GNU conditional expr extension. 7193 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7194 SourceLocation ColonLoc, 7195 Expr *CondExpr, Expr *LHSExpr, 7196 Expr *RHSExpr) { 7197 if (!getLangOpts().CPlusPlus) { 7198 // C cannot handle TypoExpr nodes in the condition because it 7199 // doesn't handle dependent types properly, so make sure any TypoExprs have 7200 // been dealt with before checking the operands. 7201 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7202 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7203 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7204 7205 if (!CondResult.isUsable()) 7206 return ExprError(); 7207 7208 if (LHSExpr) { 7209 if (!LHSResult.isUsable()) 7210 return ExprError(); 7211 } 7212 7213 if (!RHSResult.isUsable()) 7214 return ExprError(); 7215 7216 CondExpr = CondResult.get(); 7217 LHSExpr = LHSResult.get(); 7218 RHSExpr = RHSResult.get(); 7219 } 7220 7221 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7222 // was the condition. 7223 OpaqueValueExpr *opaqueValue = nullptr; 7224 Expr *commonExpr = nullptr; 7225 if (!LHSExpr) { 7226 commonExpr = CondExpr; 7227 // Lower out placeholder types first. This is important so that we don't 7228 // try to capture a placeholder. This happens in few cases in C++; such 7229 // as Objective-C++'s dictionary subscripting syntax. 7230 if (commonExpr->hasPlaceholderType()) { 7231 ExprResult result = CheckPlaceholderExpr(commonExpr); 7232 if (!result.isUsable()) return ExprError(); 7233 commonExpr = result.get(); 7234 } 7235 // We usually want to apply unary conversions *before* saving, except 7236 // in the special case of a C++ l-value conditional. 7237 if (!(getLangOpts().CPlusPlus 7238 && !commonExpr->isTypeDependent() 7239 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7240 && commonExpr->isGLValue() 7241 && commonExpr->isOrdinaryOrBitFieldObject() 7242 && RHSExpr->isOrdinaryOrBitFieldObject() 7243 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7244 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7245 if (commonRes.isInvalid()) 7246 return ExprError(); 7247 commonExpr = commonRes.get(); 7248 } 7249 7250 // If the common expression is a class or array prvalue, materialize it 7251 // so that we can safely refer to it multiple times. 7252 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7253 commonExpr->getType()->isArrayType())) { 7254 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7255 if (MatExpr.isInvalid()) 7256 return ExprError(); 7257 commonExpr = MatExpr.get(); 7258 } 7259 7260 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7261 commonExpr->getType(), 7262 commonExpr->getValueKind(), 7263 commonExpr->getObjectKind(), 7264 commonExpr); 7265 LHSExpr = CondExpr = opaqueValue; 7266 } 7267 7268 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7269 ExprValueKind VK = VK_RValue; 7270 ExprObjectKind OK = OK_Ordinary; 7271 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7272 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7273 VK, OK, QuestionLoc); 7274 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7275 RHS.isInvalid()) 7276 return ExprError(); 7277 7278 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7279 RHS.get()); 7280 7281 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7282 7283 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7284 Context); 7285 7286 if (!commonExpr) 7287 return new (Context) 7288 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7289 RHS.get(), result, VK, OK); 7290 7291 return new (Context) BinaryConditionalOperator( 7292 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7293 ColonLoc, result, VK, OK); 7294 } 7295 7296 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7297 // being closely modeled after the C99 spec:-). The odd characteristic of this 7298 // routine is it effectively iqnores the qualifiers on the top level pointee. 7299 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7300 // FIXME: add a couple examples in this comment. 7301 static Sema::AssignConvertType 7302 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7303 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7304 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7305 7306 // get the "pointed to" type (ignoring qualifiers at the top level) 7307 const Type *lhptee, *rhptee; 7308 Qualifiers lhq, rhq; 7309 std::tie(lhptee, lhq) = 7310 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7311 std::tie(rhptee, rhq) = 7312 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7313 7314 Sema::AssignConvertType ConvTy = Sema::Compatible; 7315 7316 // C99 6.5.16.1p1: This following citation is common to constraints 7317 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7318 // qualifiers of the type *pointed to* by the right; 7319 7320 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7321 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7322 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7323 // Ignore lifetime for further calculation. 7324 lhq.removeObjCLifetime(); 7325 rhq.removeObjCLifetime(); 7326 } 7327 7328 if (!lhq.compatiblyIncludes(rhq)) { 7329 // Treat address-space mismatches as fatal. TODO: address subspaces 7330 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7331 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7332 7333 // It's okay to add or remove GC or lifetime qualifiers when converting to 7334 // and from void*. 7335 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7336 .compatiblyIncludes( 7337 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7338 && (lhptee->isVoidType() || rhptee->isVoidType())) 7339 ; // keep old 7340 7341 // Treat lifetime mismatches as fatal. 7342 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7343 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7344 7345 // For GCC/MS compatibility, other qualifier mismatches are treated 7346 // as still compatible in C. 7347 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7348 } 7349 7350 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7351 // incomplete type and the other is a pointer to a qualified or unqualified 7352 // version of void... 7353 if (lhptee->isVoidType()) { 7354 if (rhptee->isIncompleteOrObjectType()) 7355 return ConvTy; 7356 7357 // As an extension, we allow cast to/from void* to function pointer. 7358 assert(rhptee->isFunctionType()); 7359 return Sema::FunctionVoidPointer; 7360 } 7361 7362 if (rhptee->isVoidType()) { 7363 if (lhptee->isIncompleteOrObjectType()) 7364 return ConvTy; 7365 7366 // As an extension, we allow cast to/from void* to function pointer. 7367 assert(lhptee->isFunctionType()); 7368 return Sema::FunctionVoidPointer; 7369 } 7370 7371 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7372 // unqualified versions of compatible types, ... 7373 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7374 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7375 // Check if the pointee types are compatible ignoring the sign. 7376 // We explicitly check for char so that we catch "char" vs 7377 // "unsigned char" on systems where "char" is unsigned. 7378 if (lhptee->isCharType()) 7379 ltrans = S.Context.UnsignedCharTy; 7380 else if (lhptee->hasSignedIntegerRepresentation()) 7381 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7382 7383 if (rhptee->isCharType()) 7384 rtrans = S.Context.UnsignedCharTy; 7385 else if (rhptee->hasSignedIntegerRepresentation()) 7386 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7387 7388 if (ltrans == rtrans) { 7389 // Types are compatible ignoring the sign. Qualifier incompatibility 7390 // takes priority over sign incompatibility because the sign 7391 // warning can be disabled. 7392 if (ConvTy != Sema::Compatible) 7393 return ConvTy; 7394 7395 return Sema::IncompatiblePointerSign; 7396 } 7397 7398 // If we are a multi-level pointer, it's possible that our issue is simply 7399 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7400 // the eventual target type is the same and the pointers have the same 7401 // level of indirection, this must be the issue. 7402 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7403 do { 7404 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7405 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7406 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7407 7408 if (lhptee == rhptee) 7409 return Sema::IncompatibleNestedPointerQualifiers; 7410 } 7411 7412 // General pointer incompatibility takes priority over qualifiers. 7413 return Sema::IncompatiblePointer; 7414 } 7415 if (!S.getLangOpts().CPlusPlus && 7416 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7417 return Sema::IncompatiblePointer; 7418 return ConvTy; 7419 } 7420 7421 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7422 /// block pointer types are compatible or whether a block and normal pointer 7423 /// are compatible. It is more restrict than comparing two function pointer 7424 // types. 7425 static Sema::AssignConvertType 7426 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7427 QualType RHSType) { 7428 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7429 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7430 7431 QualType lhptee, rhptee; 7432 7433 // get the "pointed to" type (ignoring qualifiers at the top level) 7434 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7435 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7436 7437 // In C++, the types have to match exactly. 7438 if (S.getLangOpts().CPlusPlus) 7439 return Sema::IncompatibleBlockPointer; 7440 7441 Sema::AssignConvertType ConvTy = Sema::Compatible; 7442 7443 // For blocks we enforce that qualifiers are identical. 7444 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7445 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7446 if (S.getLangOpts().OpenCL) { 7447 LQuals.removeAddressSpace(); 7448 RQuals.removeAddressSpace(); 7449 } 7450 if (LQuals != RQuals) 7451 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7452 7453 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7454 // assignment. 7455 // The current behavior is similar to C++ lambdas. A block might be 7456 // assigned to a variable iff its return type and parameters are compatible 7457 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7458 // an assignment. Presumably it should behave in way that a function pointer 7459 // assignment does in C, so for each parameter and return type: 7460 // * CVR and address space of LHS should be a superset of CVR and address 7461 // space of RHS. 7462 // * unqualified types should be compatible. 7463 if (S.getLangOpts().OpenCL) { 7464 if (!S.Context.typesAreBlockPointerCompatible( 7465 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7466 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7467 return Sema::IncompatibleBlockPointer; 7468 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7469 return Sema::IncompatibleBlockPointer; 7470 7471 return ConvTy; 7472 } 7473 7474 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7475 /// for assignment compatibility. 7476 static Sema::AssignConvertType 7477 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7478 QualType RHSType) { 7479 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7480 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7481 7482 if (LHSType->isObjCBuiltinType()) { 7483 // Class is not compatible with ObjC object pointers. 7484 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7485 !RHSType->isObjCQualifiedClassType()) 7486 return Sema::IncompatiblePointer; 7487 return Sema::Compatible; 7488 } 7489 if (RHSType->isObjCBuiltinType()) { 7490 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7491 !LHSType->isObjCQualifiedClassType()) 7492 return Sema::IncompatiblePointer; 7493 return Sema::Compatible; 7494 } 7495 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7496 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7497 7498 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7499 // make an exception for id<P> 7500 !LHSType->isObjCQualifiedIdType()) 7501 return Sema::CompatiblePointerDiscardsQualifiers; 7502 7503 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7504 return Sema::Compatible; 7505 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7506 return Sema::IncompatibleObjCQualifiedId; 7507 return Sema::IncompatiblePointer; 7508 } 7509 7510 Sema::AssignConvertType 7511 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7512 QualType LHSType, QualType RHSType) { 7513 // Fake up an opaque expression. We don't actually care about what 7514 // cast operations are required, so if CheckAssignmentConstraints 7515 // adds casts to this they'll be wasted, but fortunately that doesn't 7516 // usually happen on valid code. 7517 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7518 ExprResult RHSPtr = &RHSExpr; 7519 CastKind K; 7520 7521 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7522 } 7523 7524 /// This helper function returns true if QT is a vector type that has element 7525 /// type ElementType. 7526 static bool isVector(QualType QT, QualType ElementType) { 7527 if (const VectorType *VT = QT->getAs<VectorType>()) 7528 return VT->getElementType() == ElementType; 7529 return false; 7530 } 7531 7532 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7533 /// has code to accommodate several GCC extensions when type checking 7534 /// pointers. Here are some objectionable examples that GCC considers warnings: 7535 /// 7536 /// int a, *pint; 7537 /// short *pshort; 7538 /// struct foo *pfoo; 7539 /// 7540 /// pint = pshort; // warning: assignment from incompatible pointer type 7541 /// a = pint; // warning: assignment makes integer from pointer without a cast 7542 /// pint = a; // warning: assignment makes pointer from integer without a cast 7543 /// pint = pfoo; // warning: assignment from incompatible pointer type 7544 /// 7545 /// As a result, the code for dealing with pointers is more complex than the 7546 /// C99 spec dictates. 7547 /// 7548 /// Sets 'Kind' for any result kind except Incompatible. 7549 Sema::AssignConvertType 7550 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7551 CastKind &Kind, bool ConvertRHS) { 7552 QualType RHSType = RHS.get()->getType(); 7553 QualType OrigLHSType = LHSType; 7554 7555 // Get canonical types. We're not formatting these types, just comparing 7556 // them. 7557 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7558 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7559 7560 // Common case: no conversion required. 7561 if (LHSType == RHSType) { 7562 Kind = CK_NoOp; 7563 return Compatible; 7564 } 7565 7566 // If we have an atomic type, try a non-atomic assignment, then just add an 7567 // atomic qualification step. 7568 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7569 Sema::AssignConvertType result = 7570 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7571 if (result != Compatible) 7572 return result; 7573 if (Kind != CK_NoOp && ConvertRHS) 7574 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7575 Kind = CK_NonAtomicToAtomic; 7576 return Compatible; 7577 } 7578 7579 // If the left-hand side is a reference type, then we are in a 7580 // (rare!) case where we've allowed the use of references in C, 7581 // e.g., as a parameter type in a built-in function. In this case, 7582 // just make sure that the type referenced is compatible with the 7583 // right-hand side type. The caller is responsible for adjusting 7584 // LHSType so that the resulting expression does not have reference 7585 // type. 7586 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7587 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7588 Kind = CK_LValueBitCast; 7589 return Compatible; 7590 } 7591 return Incompatible; 7592 } 7593 7594 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7595 // to the same ExtVector type. 7596 if (LHSType->isExtVectorType()) { 7597 if (RHSType->isExtVectorType()) 7598 return Incompatible; 7599 if (RHSType->isArithmeticType()) { 7600 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7601 if (ConvertRHS) 7602 RHS = prepareVectorSplat(LHSType, RHS.get()); 7603 Kind = CK_VectorSplat; 7604 return Compatible; 7605 } 7606 } 7607 7608 // Conversions to or from vector type. 7609 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7610 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7611 // Allow assignments of an AltiVec vector type to an equivalent GCC 7612 // vector type and vice versa 7613 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7614 Kind = CK_BitCast; 7615 return Compatible; 7616 } 7617 7618 // If we are allowing lax vector conversions, and LHS and RHS are both 7619 // vectors, the total size only needs to be the same. This is a bitcast; 7620 // no bits are changed but the result type is different. 7621 if (isLaxVectorConversion(RHSType, LHSType)) { 7622 Kind = CK_BitCast; 7623 return IncompatibleVectors; 7624 } 7625 } 7626 7627 // When the RHS comes from another lax conversion (e.g. binops between 7628 // scalars and vectors) the result is canonicalized as a vector. When the 7629 // LHS is also a vector, the lax is allowed by the condition above. Handle 7630 // the case where LHS is a scalar. 7631 if (LHSType->isScalarType()) { 7632 const VectorType *VecType = RHSType->getAs<VectorType>(); 7633 if (VecType && VecType->getNumElements() == 1 && 7634 isLaxVectorConversion(RHSType, LHSType)) { 7635 ExprResult *VecExpr = &RHS; 7636 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7637 Kind = CK_BitCast; 7638 return Compatible; 7639 } 7640 } 7641 7642 return Incompatible; 7643 } 7644 7645 // Diagnose attempts to convert between __float128 and long double where 7646 // such conversions currently can't be handled. 7647 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7648 return Incompatible; 7649 7650 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7651 // discards the imaginary part. 7652 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7653 !LHSType->getAs<ComplexType>()) 7654 return Incompatible; 7655 7656 // Arithmetic conversions. 7657 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7658 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7659 if (ConvertRHS) 7660 Kind = PrepareScalarCast(RHS, LHSType); 7661 return Compatible; 7662 } 7663 7664 // Conversions to normal pointers. 7665 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7666 // U* -> T* 7667 if (isa<PointerType>(RHSType)) { 7668 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7669 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7670 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7671 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7672 } 7673 7674 // int -> T* 7675 if (RHSType->isIntegerType()) { 7676 Kind = CK_IntegralToPointer; // FIXME: null? 7677 return IntToPointer; 7678 } 7679 7680 // C pointers are not compatible with ObjC object pointers, 7681 // with two exceptions: 7682 if (isa<ObjCObjectPointerType>(RHSType)) { 7683 // - conversions to void* 7684 if (LHSPointer->getPointeeType()->isVoidType()) { 7685 Kind = CK_BitCast; 7686 return Compatible; 7687 } 7688 7689 // - conversions from 'Class' to the redefinition type 7690 if (RHSType->isObjCClassType() && 7691 Context.hasSameType(LHSType, 7692 Context.getObjCClassRedefinitionType())) { 7693 Kind = CK_BitCast; 7694 return Compatible; 7695 } 7696 7697 Kind = CK_BitCast; 7698 return IncompatiblePointer; 7699 } 7700 7701 // U^ -> void* 7702 if (RHSType->getAs<BlockPointerType>()) { 7703 if (LHSPointer->getPointeeType()->isVoidType()) { 7704 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7705 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7706 ->getPointeeType() 7707 .getAddressSpace(); 7708 Kind = 7709 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7710 return Compatible; 7711 } 7712 } 7713 7714 return Incompatible; 7715 } 7716 7717 // Conversions to block pointers. 7718 if (isa<BlockPointerType>(LHSType)) { 7719 // U^ -> T^ 7720 if (RHSType->isBlockPointerType()) { 7721 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7722 ->getPointeeType() 7723 .getAddressSpace(); 7724 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7725 ->getPointeeType() 7726 .getAddressSpace(); 7727 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7728 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7729 } 7730 7731 // int or null -> T^ 7732 if (RHSType->isIntegerType()) { 7733 Kind = CK_IntegralToPointer; // FIXME: null 7734 return IntToBlockPointer; 7735 } 7736 7737 // id -> T^ 7738 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7739 Kind = CK_AnyPointerToBlockPointerCast; 7740 return Compatible; 7741 } 7742 7743 // void* -> T^ 7744 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7745 if (RHSPT->getPointeeType()->isVoidType()) { 7746 Kind = CK_AnyPointerToBlockPointerCast; 7747 return Compatible; 7748 } 7749 7750 return Incompatible; 7751 } 7752 7753 // Conversions to Objective-C pointers. 7754 if (isa<ObjCObjectPointerType>(LHSType)) { 7755 // A* -> B* 7756 if (RHSType->isObjCObjectPointerType()) { 7757 Kind = CK_BitCast; 7758 Sema::AssignConvertType result = 7759 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7760 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7761 result == Compatible && 7762 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7763 result = IncompatibleObjCWeakRef; 7764 return result; 7765 } 7766 7767 // int or null -> A* 7768 if (RHSType->isIntegerType()) { 7769 Kind = CK_IntegralToPointer; // FIXME: null 7770 return IntToPointer; 7771 } 7772 7773 // In general, C pointers are not compatible with ObjC object pointers, 7774 // with two exceptions: 7775 if (isa<PointerType>(RHSType)) { 7776 Kind = CK_CPointerToObjCPointerCast; 7777 7778 // - conversions from 'void*' 7779 if (RHSType->isVoidPointerType()) { 7780 return Compatible; 7781 } 7782 7783 // - conversions to 'Class' from its redefinition type 7784 if (LHSType->isObjCClassType() && 7785 Context.hasSameType(RHSType, 7786 Context.getObjCClassRedefinitionType())) { 7787 return Compatible; 7788 } 7789 7790 return IncompatiblePointer; 7791 } 7792 7793 // Only under strict condition T^ is compatible with an Objective-C pointer. 7794 if (RHSType->isBlockPointerType() && 7795 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7796 if (ConvertRHS) 7797 maybeExtendBlockObject(RHS); 7798 Kind = CK_BlockPointerToObjCPointerCast; 7799 return Compatible; 7800 } 7801 7802 return Incompatible; 7803 } 7804 7805 // Conversions from pointers that are not covered by the above. 7806 if (isa<PointerType>(RHSType)) { 7807 // T* -> _Bool 7808 if (LHSType == Context.BoolTy) { 7809 Kind = CK_PointerToBoolean; 7810 return Compatible; 7811 } 7812 7813 // T* -> int 7814 if (LHSType->isIntegerType()) { 7815 Kind = CK_PointerToIntegral; 7816 return PointerToInt; 7817 } 7818 7819 return Incompatible; 7820 } 7821 7822 // Conversions from Objective-C pointers that are not covered by the above. 7823 if (isa<ObjCObjectPointerType>(RHSType)) { 7824 // T* -> _Bool 7825 if (LHSType == Context.BoolTy) { 7826 Kind = CK_PointerToBoolean; 7827 return Compatible; 7828 } 7829 7830 // T* -> int 7831 if (LHSType->isIntegerType()) { 7832 Kind = CK_PointerToIntegral; 7833 return PointerToInt; 7834 } 7835 7836 return Incompatible; 7837 } 7838 7839 // struct A -> struct B 7840 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7841 if (Context.typesAreCompatible(LHSType, RHSType)) { 7842 Kind = CK_NoOp; 7843 return Compatible; 7844 } 7845 } 7846 7847 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7848 Kind = CK_IntToOCLSampler; 7849 return Compatible; 7850 } 7851 7852 return Incompatible; 7853 } 7854 7855 /// \brief Constructs a transparent union from an expression that is 7856 /// used to initialize the transparent union. 7857 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7858 ExprResult &EResult, QualType UnionType, 7859 FieldDecl *Field) { 7860 // Build an initializer list that designates the appropriate member 7861 // of the transparent union. 7862 Expr *E = EResult.get(); 7863 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7864 E, SourceLocation()); 7865 Initializer->setType(UnionType); 7866 Initializer->setInitializedFieldInUnion(Field); 7867 7868 // Build a compound literal constructing a value of the transparent 7869 // union type from this initializer list. 7870 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7871 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7872 VK_RValue, Initializer, false); 7873 } 7874 7875 Sema::AssignConvertType 7876 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7877 ExprResult &RHS) { 7878 QualType RHSType = RHS.get()->getType(); 7879 7880 // If the ArgType is a Union type, we want to handle a potential 7881 // transparent_union GCC extension. 7882 const RecordType *UT = ArgType->getAsUnionType(); 7883 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7884 return Incompatible; 7885 7886 // The field to initialize within the transparent union. 7887 RecordDecl *UD = UT->getDecl(); 7888 FieldDecl *InitField = nullptr; 7889 // It's compatible if the expression matches any of the fields. 7890 for (auto *it : UD->fields()) { 7891 if (it->getType()->isPointerType()) { 7892 // If the transparent union contains a pointer type, we allow: 7893 // 1) void pointer 7894 // 2) null pointer constant 7895 if (RHSType->isPointerType()) 7896 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7897 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7898 InitField = it; 7899 break; 7900 } 7901 7902 if (RHS.get()->isNullPointerConstant(Context, 7903 Expr::NPC_ValueDependentIsNull)) { 7904 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7905 CK_NullToPointer); 7906 InitField = it; 7907 break; 7908 } 7909 } 7910 7911 CastKind Kind; 7912 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7913 == Compatible) { 7914 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7915 InitField = it; 7916 break; 7917 } 7918 } 7919 7920 if (!InitField) 7921 return Incompatible; 7922 7923 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7924 return Compatible; 7925 } 7926 7927 Sema::AssignConvertType 7928 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7929 bool Diagnose, 7930 bool DiagnoseCFAudited, 7931 bool ConvertRHS) { 7932 // We need to be able to tell the caller whether we diagnosed a problem, if 7933 // they ask us to issue diagnostics. 7934 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7935 7936 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7937 // we can't avoid *all* modifications at the moment, so we need some somewhere 7938 // to put the updated value. 7939 ExprResult LocalRHS = CallerRHS; 7940 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7941 7942 if (getLangOpts().CPlusPlus) { 7943 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7944 // C++ 5.17p3: If the left operand is not of class type, the 7945 // expression is implicitly converted (C++ 4) to the 7946 // cv-unqualified type of the left operand. 7947 QualType RHSType = RHS.get()->getType(); 7948 if (Diagnose) { 7949 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7950 AA_Assigning); 7951 } else { 7952 ImplicitConversionSequence ICS = 7953 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7954 /*SuppressUserConversions=*/false, 7955 /*AllowExplicit=*/false, 7956 /*InOverloadResolution=*/false, 7957 /*CStyle=*/false, 7958 /*AllowObjCWritebackConversion=*/false); 7959 if (ICS.isFailure()) 7960 return Incompatible; 7961 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7962 ICS, AA_Assigning); 7963 } 7964 if (RHS.isInvalid()) 7965 return Incompatible; 7966 Sema::AssignConvertType result = Compatible; 7967 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7968 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7969 result = IncompatibleObjCWeakRef; 7970 return result; 7971 } 7972 7973 // FIXME: Currently, we fall through and treat C++ classes like C 7974 // structures. 7975 // FIXME: We also fall through for atomics; not sure what should 7976 // happen there, though. 7977 } else if (RHS.get()->getType() == Context.OverloadTy) { 7978 // As a set of extensions to C, we support overloading on functions. These 7979 // functions need to be resolved here. 7980 DeclAccessPair DAP; 7981 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7982 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7983 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7984 else 7985 return Incompatible; 7986 } 7987 7988 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7989 // a null pointer constant. 7990 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7991 LHSType->isBlockPointerType()) && 7992 RHS.get()->isNullPointerConstant(Context, 7993 Expr::NPC_ValueDependentIsNull)) { 7994 if (Diagnose || ConvertRHS) { 7995 CastKind Kind; 7996 CXXCastPath Path; 7997 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7998 /*IgnoreBaseAccess=*/false, Diagnose); 7999 if (ConvertRHS) 8000 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8001 } 8002 return Compatible; 8003 } 8004 8005 // This check seems unnatural, however it is necessary to ensure the proper 8006 // conversion of functions/arrays. If the conversion were done for all 8007 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8008 // expressions that suppress this implicit conversion (&, sizeof). 8009 // 8010 // Suppress this for references: C++ 8.5.3p5. 8011 if (!LHSType->isReferenceType()) { 8012 // FIXME: We potentially allocate here even if ConvertRHS is false. 8013 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8014 if (RHS.isInvalid()) 8015 return Incompatible; 8016 } 8017 8018 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8019 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8020 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8021 if (PDecl && !PDecl->hasDefinition()) { 8022 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 8023 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8024 } 8025 } 8026 8027 CastKind Kind; 8028 Sema::AssignConvertType result = 8029 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8030 8031 // C99 6.5.16.1p2: The value of the right operand is converted to the 8032 // type of the assignment expression. 8033 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8034 // so that we can use references in built-in functions even in C. 8035 // The getNonReferenceType() call makes sure that the resulting expression 8036 // does not have reference type. 8037 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8038 QualType Ty = LHSType.getNonLValueExprType(Context); 8039 Expr *E = RHS.get(); 8040 8041 // Check for various Objective-C errors. If we are not reporting 8042 // diagnostics and just checking for errors, e.g., during overload 8043 // resolution, return Incompatible to indicate the failure. 8044 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8045 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8046 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8047 if (!Diagnose) 8048 return Incompatible; 8049 } 8050 if (getLangOpts().ObjC1 && 8051 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8052 E->getType(), E, Diagnose) || 8053 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8054 if (!Diagnose) 8055 return Incompatible; 8056 // Replace the expression with a corrected version and continue so we 8057 // can find further errors. 8058 RHS = E; 8059 return Compatible; 8060 } 8061 8062 if (ConvertRHS) 8063 RHS = ImpCastExprToType(E, Ty, Kind); 8064 } 8065 return result; 8066 } 8067 8068 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8069 ExprResult &RHS) { 8070 Diag(Loc, diag::err_typecheck_invalid_operands) 8071 << LHS.get()->getType() << RHS.get()->getType() 8072 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8073 return QualType(); 8074 } 8075 8076 // Diagnose cases where a scalar was implicitly converted to a vector and 8077 // diagnose the underlying types. Otherwise, diagnose the error 8078 // as invalid vector logical operands for non-C++ cases. 8079 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8080 ExprResult &RHS) { 8081 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8082 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8083 8084 bool LHSNatVec = LHSType->isVectorType(); 8085 bool RHSNatVec = RHSType->isVectorType(); 8086 8087 if (!(LHSNatVec && RHSNatVec)) { 8088 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8089 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8090 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8091 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8092 << Vector->getSourceRange(); 8093 return QualType(); 8094 } 8095 8096 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8097 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8098 << RHS.get()->getSourceRange(); 8099 8100 return QualType(); 8101 } 8102 8103 /// Try to convert a value of non-vector type to a vector type by converting 8104 /// the type to the element type of the vector and then performing a splat. 8105 /// If the language is OpenCL, we only use conversions that promote scalar 8106 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8107 /// for float->int. 8108 /// 8109 /// OpenCL V2.0 6.2.6.p2: 8110 /// An error shall occur if any scalar operand type has greater rank 8111 /// than the type of the vector element. 8112 /// 8113 /// \param scalar - if non-null, actually perform the conversions 8114 /// \return true if the operation fails (but without diagnosing the failure) 8115 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8116 QualType scalarTy, 8117 QualType vectorEltTy, 8118 QualType vectorTy, 8119 unsigned &DiagID) { 8120 // The conversion to apply to the scalar before splatting it, 8121 // if necessary. 8122 CastKind scalarCast = CK_NoOp; 8123 8124 if (vectorEltTy->isIntegralType(S.Context)) { 8125 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8126 (scalarTy->isIntegerType() && 8127 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8128 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8129 return true; 8130 } 8131 if (!scalarTy->isIntegralType(S.Context)) 8132 return true; 8133 scalarCast = CK_IntegralCast; 8134 } else if (vectorEltTy->isRealFloatingType()) { 8135 if (scalarTy->isRealFloatingType()) { 8136 if (S.getLangOpts().OpenCL && 8137 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8138 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8139 return true; 8140 } 8141 scalarCast = CK_FloatingCast; 8142 } 8143 else if (scalarTy->isIntegralType(S.Context)) 8144 scalarCast = CK_IntegralToFloating; 8145 else 8146 return true; 8147 } else { 8148 return true; 8149 } 8150 8151 // Adjust scalar if desired. 8152 if (scalar) { 8153 if (scalarCast != CK_NoOp) 8154 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8155 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8156 } 8157 return false; 8158 } 8159 8160 /// Convert vector E to a vector with the same number of elements but different 8161 /// element type. 8162 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8163 const auto *VecTy = E->getType()->getAs<VectorType>(); 8164 assert(VecTy && "Expression E must be a vector"); 8165 QualType NewVecTy = S.Context.getVectorType(ElementType, 8166 VecTy->getNumElements(), 8167 VecTy->getVectorKind()); 8168 8169 // Look through the implicit cast. Return the subexpression if its type is 8170 // NewVecTy. 8171 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8172 if (ICE->getSubExpr()->getType() == NewVecTy) 8173 return ICE->getSubExpr(); 8174 8175 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8176 return S.ImpCastExprToType(E, NewVecTy, Cast); 8177 } 8178 8179 /// Test if a (constant) integer Int can be casted to another integer type 8180 /// IntTy without losing precision. 8181 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8182 QualType OtherIntTy) { 8183 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8184 8185 // Reject cases where the value of the Int is unknown as that would 8186 // possibly cause truncation, but accept cases where the scalar can be 8187 // demoted without loss of precision. 8188 llvm::APSInt Result; 8189 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8190 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8191 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8192 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8193 8194 if (CstInt) { 8195 // If the scalar is constant and is of a higher order and has more active 8196 // bits that the vector element type, reject it. 8197 unsigned NumBits = IntSigned 8198 ? (Result.isNegative() ? Result.getMinSignedBits() 8199 : Result.getActiveBits()) 8200 : Result.getActiveBits(); 8201 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8202 return true; 8203 8204 // If the signedness of the scalar type and the vector element type 8205 // differs and the number of bits is greater than that of the vector 8206 // element reject it. 8207 return (IntSigned != OtherIntSigned && 8208 NumBits > S.Context.getIntWidth(OtherIntTy)); 8209 } 8210 8211 // Reject cases where the value of the scalar is not constant and it's 8212 // order is greater than that of the vector element type. 8213 return (Order < 0); 8214 } 8215 8216 /// Test if a (constant) integer Int can be casted to floating point type 8217 /// FloatTy without losing precision. 8218 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8219 QualType FloatTy) { 8220 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8221 8222 // Determine if the integer constant can be expressed as a floating point 8223 // number of the appropiate type. 8224 llvm::APSInt Result; 8225 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8226 uint64_t Bits = 0; 8227 if (CstInt) { 8228 // Reject constants that would be truncated if they were converted to 8229 // the floating point type. Test by simple to/from conversion. 8230 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8231 // could be avoided if there was a convertFromAPInt method 8232 // which could signal back if implicit truncation occurred. 8233 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8234 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8235 llvm::APFloat::rmTowardZero); 8236 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8237 !IntTy->hasSignedIntegerRepresentation()); 8238 bool Ignored = false; 8239 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8240 &Ignored); 8241 if (Result != ConvertBack) 8242 return true; 8243 } else { 8244 // Reject types that cannot be fully encoded into the mantissa of 8245 // the float. 8246 Bits = S.Context.getTypeSize(IntTy); 8247 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8248 S.Context.getFloatTypeSemantics(FloatTy)); 8249 if (Bits > FloatPrec) 8250 return true; 8251 } 8252 8253 return false; 8254 } 8255 8256 /// Attempt to convert and splat Scalar into a vector whose types matches 8257 /// Vector following GCC conversion rules. The rule is that implicit 8258 /// conversion can occur when Scalar can be casted to match Vector's element 8259 /// type without causing truncation of Scalar. 8260 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8261 ExprResult *Vector) { 8262 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8263 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8264 const VectorType *VT = VectorTy->getAs<VectorType>(); 8265 8266 assert(!isa<ExtVectorType>(VT) && 8267 "ExtVectorTypes should not be handled here!"); 8268 8269 QualType VectorEltTy = VT->getElementType(); 8270 8271 // Reject cases where the vector element type or the scalar element type are 8272 // not integral or floating point types. 8273 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8274 return true; 8275 8276 // The conversion to apply to the scalar before splatting it, 8277 // if necessary. 8278 CastKind ScalarCast = CK_NoOp; 8279 8280 // Accept cases where the vector elements are integers and the scalar is 8281 // an integer. 8282 // FIXME: Notionally if the scalar was a floating point value with a precise 8283 // integral representation, we could cast it to an appropriate integer 8284 // type and then perform the rest of the checks here. GCC will perform 8285 // this conversion in some cases as determined by the input language. 8286 // We should accept it on a language independent basis. 8287 if (VectorEltTy->isIntegralType(S.Context) && 8288 ScalarTy->isIntegralType(S.Context) && 8289 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8290 8291 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8292 return true; 8293 8294 ScalarCast = CK_IntegralCast; 8295 } else if (VectorEltTy->isRealFloatingType()) { 8296 if (ScalarTy->isRealFloatingType()) { 8297 8298 // Reject cases where the scalar type is not a constant and has a higher 8299 // Order than the vector element type. 8300 llvm::APFloat Result(0.0); 8301 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8302 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8303 if (!CstScalar && Order < 0) 8304 return true; 8305 8306 // If the scalar cannot be safely casted to the vector element type, 8307 // reject it. 8308 if (CstScalar) { 8309 bool Truncated = false; 8310 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8311 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8312 if (Truncated) 8313 return true; 8314 } 8315 8316 ScalarCast = CK_FloatingCast; 8317 } else if (ScalarTy->isIntegralType(S.Context)) { 8318 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8319 return true; 8320 8321 ScalarCast = CK_IntegralToFloating; 8322 } else 8323 return true; 8324 } 8325 8326 // Adjust scalar if desired. 8327 if (Scalar) { 8328 if (ScalarCast != CK_NoOp) 8329 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8330 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8331 } 8332 return false; 8333 } 8334 8335 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8336 SourceLocation Loc, bool IsCompAssign, 8337 bool AllowBothBool, 8338 bool AllowBoolConversions) { 8339 if (!IsCompAssign) { 8340 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8341 if (LHS.isInvalid()) 8342 return QualType(); 8343 } 8344 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8345 if (RHS.isInvalid()) 8346 return QualType(); 8347 8348 // For conversion purposes, we ignore any qualifiers. 8349 // For example, "const float" and "float" are equivalent. 8350 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8351 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8352 8353 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8354 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8355 assert(LHSVecType || RHSVecType); 8356 8357 // AltiVec-style "vector bool op vector bool" combinations are allowed 8358 // for some operators but not others. 8359 if (!AllowBothBool && 8360 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8361 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8362 return InvalidOperands(Loc, LHS, RHS); 8363 8364 // If the vector types are identical, return. 8365 if (Context.hasSameType(LHSType, RHSType)) 8366 return LHSType; 8367 8368 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8369 if (LHSVecType && RHSVecType && 8370 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8371 if (isa<ExtVectorType>(LHSVecType)) { 8372 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8373 return LHSType; 8374 } 8375 8376 if (!IsCompAssign) 8377 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8378 return RHSType; 8379 } 8380 8381 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8382 // can be mixed, with the result being the non-bool type. The non-bool 8383 // operand must have integer element type. 8384 if (AllowBoolConversions && LHSVecType && RHSVecType && 8385 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8386 (Context.getTypeSize(LHSVecType->getElementType()) == 8387 Context.getTypeSize(RHSVecType->getElementType()))) { 8388 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8389 LHSVecType->getElementType()->isIntegerType() && 8390 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8391 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8392 return LHSType; 8393 } 8394 if (!IsCompAssign && 8395 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8396 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8397 RHSVecType->getElementType()->isIntegerType()) { 8398 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8399 return RHSType; 8400 } 8401 } 8402 8403 // If there's a vector type and a scalar, try to convert the scalar to 8404 // the vector element type and splat. 8405 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8406 if (!RHSVecType) { 8407 if (isa<ExtVectorType>(LHSVecType)) { 8408 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8409 LHSVecType->getElementType(), LHSType, 8410 DiagID)) 8411 return LHSType; 8412 } else { 8413 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8414 return LHSType; 8415 } 8416 } 8417 if (!LHSVecType) { 8418 if (isa<ExtVectorType>(RHSVecType)) { 8419 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8420 LHSType, RHSVecType->getElementType(), 8421 RHSType, DiagID)) 8422 return RHSType; 8423 } else { 8424 if (LHS.get()->getValueKind() == VK_LValue || 8425 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8426 return RHSType; 8427 } 8428 } 8429 8430 // FIXME: The code below also handles conversion between vectors and 8431 // non-scalars, we should break this down into fine grained specific checks 8432 // and emit proper diagnostics. 8433 QualType VecType = LHSVecType ? LHSType : RHSType; 8434 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8435 QualType OtherType = LHSVecType ? RHSType : LHSType; 8436 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8437 if (isLaxVectorConversion(OtherType, VecType)) { 8438 // If we're allowing lax vector conversions, only the total (data) size 8439 // needs to be the same. For non compound assignment, if one of the types is 8440 // scalar, the result is always the vector type. 8441 if (!IsCompAssign) { 8442 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8443 return VecType; 8444 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8445 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8446 // type. Note that this is already done by non-compound assignments in 8447 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8448 // <1 x T> -> T. The result is also a vector type. 8449 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8450 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8451 ExprResult *RHSExpr = &RHS; 8452 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8453 return VecType; 8454 } 8455 } 8456 8457 // Okay, the expression is invalid. 8458 8459 // If there's a non-vector, non-real operand, diagnose that. 8460 if ((!RHSVecType && !RHSType->isRealType()) || 8461 (!LHSVecType && !LHSType->isRealType())) { 8462 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8463 << LHSType << RHSType 8464 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8465 return QualType(); 8466 } 8467 8468 // OpenCL V1.1 6.2.6.p1: 8469 // If the operands are of more than one vector type, then an error shall 8470 // occur. Implicit conversions between vector types are not permitted, per 8471 // section 6.2.1. 8472 if (getLangOpts().OpenCL && 8473 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8474 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8475 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8476 << RHSType; 8477 return QualType(); 8478 } 8479 8480 8481 // If there is a vector type that is not a ExtVector and a scalar, we reach 8482 // this point if scalar could not be converted to the vector's element type 8483 // without truncation. 8484 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8485 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8486 QualType Scalar = LHSVecType ? RHSType : LHSType; 8487 QualType Vector = LHSVecType ? LHSType : RHSType; 8488 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8489 Diag(Loc, 8490 diag::err_typecheck_vector_not_convertable_implict_truncation) 8491 << ScalarOrVector << Scalar << Vector; 8492 8493 return QualType(); 8494 } 8495 8496 // Otherwise, use the generic diagnostic. 8497 Diag(Loc, DiagID) 8498 << LHSType << RHSType 8499 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8500 return QualType(); 8501 } 8502 8503 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8504 // expression. These are mainly cases where the null pointer is used as an 8505 // integer instead of a pointer. 8506 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8507 SourceLocation Loc, bool IsCompare) { 8508 // The canonical way to check for a GNU null is with isNullPointerConstant, 8509 // but we use a bit of a hack here for speed; this is a relatively 8510 // hot path, and isNullPointerConstant is slow. 8511 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8512 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8513 8514 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8515 8516 // Avoid analyzing cases where the result will either be invalid (and 8517 // diagnosed as such) or entirely valid and not something to warn about. 8518 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8519 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8520 return; 8521 8522 // Comparison operations would not make sense with a null pointer no matter 8523 // what the other expression is. 8524 if (!IsCompare) { 8525 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8526 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8527 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8528 return; 8529 } 8530 8531 // The rest of the operations only make sense with a null pointer 8532 // if the other expression is a pointer. 8533 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8534 NonNullType->canDecayToPointerType()) 8535 return; 8536 8537 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8538 << LHSNull /* LHS is NULL */ << NonNullType 8539 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8540 } 8541 8542 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8543 ExprResult &RHS, 8544 SourceLocation Loc, bool IsDiv) { 8545 // Check for division/remainder by zero. 8546 llvm::APSInt RHSValue; 8547 if (!RHS.get()->isValueDependent() && 8548 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8549 S.DiagRuntimeBehavior(Loc, RHS.get(), 8550 S.PDiag(diag::warn_remainder_division_by_zero) 8551 << IsDiv << RHS.get()->getSourceRange()); 8552 } 8553 8554 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8555 SourceLocation Loc, 8556 bool IsCompAssign, bool IsDiv) { 8557 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8558 8559 if (LHS.get()->getType()->isVectorType() || 8560 RHS.get()->getType()->isVectorType()) 8561 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8562 /*AllowBothBool*/getLangOpts().AltiVec, 8563 /*AllowBoolConversions*/false); 8564 8565 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8566 if (LHS.isInvalid() || RHS.isInvalid()) 8567 return QualType(); 8568 8569 8570 if (compType.isNull() || !compType->isArithmeticType()) 8571 return InvalidOperands(Loc, LHS, RHS); 8572 if (IsDiv) 8573 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8574 return compType; 8575 } 8576 8577 QualType Sema::CheckRemainderOperands( 8578 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8579 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8580 8581 if (LHS.get()->getType()->isVectorType() || 8582 RHS.get()->getType()->isVectorType()) { 8583 if (LHS.get()->getType()->hasIntegerRepresentation() && 8584 RHS.get()->getType()->hasIntegerRepresentation()) 8585 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8586 /*AllowBothBool*/getLangOpts().AltiVec, 8587 /*AllowBoolConversions*/false); 8588 return InvalidOperands(Loc, LHS, RHS); 8589 } 8590 8591 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8592 if (LHS.isInvalid() || RHS.isInvalid()) 8593 return QualType(); 8594 8595 if (compType.isNull() || !compType->isIntegerType()) 8596 return InvalidOperands(Loc, LHS, RHS); 8597 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8598 return compType; 8599 } 8600 8601 /// \brief Diagnose invalid arithmetic on two void pointers. 8602 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8603 Expr *LHSExpr, Expr *RHSExpr) { 8604 S.Diag(Loc, S.getLangOpts().CPlusPlus 8605 ? diag::err_typecheck_pointer_arith_void_type 8606 : diag::ext_gnu_void_ptr) 8607 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8608 << RHSExpr->getSourceRange(); 8609 } 8610 8611 /// \brief Diagnose invalid arithmetic on a void pointer. 8612 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8613 Expr *Pointer) { 8614 S.Diag(Loc, S.getLangOpts().CPlusPlus 8615 ? diag::err_typecheck_pointer_arith_void_type 8616 : diag::ext_gnu_void_ptr) 8617 << 0 /* one pointer */ << Pointer->getSourceRange(); 8618 } 8619 8620 /// \brief Diagnose invalid arithmetic on a null pointer. 8621 /// 8622 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8623 /// idiom, which we recognize as a GNU extension. 8624 /// 8625 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8626 Expr *Pointer, bool IsGNUIdiom) { 8627 if (IsGNUIdiom) 8628 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8629 << Pointer->getSourceRange(); 8630 else 8631 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8632 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8633 } 8634 8635 /// \brief Diagnose invalid arithmetic on two function pointers. 8636 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8637 Expr *LHS, Expr *RHS) { 8638 assert(LHS->getType()->isAnyPointerType()); 8639 assert(RHS->getType()->isAnyPointerType()); 8640 S.Diag(Loc, S.getLangOpts().CPlusPlus 8641 ? diag::err_typecheck_pointer_arith_function_type 8642 : diag::ext_gnu_ptr_func_arith) 8643 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8644 // We only show the second type if it differs from the first. 8645 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8646 RHS->getType()) 8647 << RHS->getType()->getPointeeType() 8648 << LHS->getSourceRange() << RHS->getSourceRange(); 8649 } 8650 8651 /// \brief Diagnose invalid arithmetic on a function pointer. 8652 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8653 Expr *Pointer) { 8654 assert(Pointer->getType()->isAnyPointerType()); 8655 S.Diag(Loc, S.getLangOpts().CPlusPlus 8656 ? diag::err_typecheck_pointer_arith_function_type 8657 : diag::ext_gnu_ptr_func_arith) 8658 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8659 << 0 /* one pointer, so only one type */ 8660 << Pointer->getSourceRange(); 8661 } 8662 8663 /// \brief Emit error if Operand is incomplete pointer type 8664 /// 8665 /// \returns True if pointer has incomplete type 8666 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8667 Expr *Operand) { 8668 QualType ResType = Operand->getType(); 8669 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8670 ResType = ResAtomicType->getValueType(); 8671 8672 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8673 QualType PointeeTy = ResType->getPointeeType(); 8674 return S.RequireCompleteType(Loc, PointeeTy, 8675 diag::err_typecheck_arithmetic_incomplete_type, 8676 PointeeTy, Operand->getSourceRange()); 8677 } 8678 8679 /// \brief Check the validity of an arithmetic pointer operand. 8680 /// 8681 /// If the operand has pointer type, this code will check for pointer types 8682 /// which are invalid in arithmetic operations. These will be diagnosed 8683 /// appropriately, including whether or not the use is supported as an 8684 /// extension. 8685 /// 8686 /// \returns True when the operand is valid to use (even if as an extension). 8687 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8688 Expr *Operand) { 8689 QualType ResType = Operand->getType(); 8690 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8691 ResType = ResAtomicType->getValueType(); 8692 8693 if (!ResType->isAnyPointerType()) return true; 8694 8695 QualType PointeeTy = ResType->getPointeeType(); 8696 if (PointeeTy->isVoidType()) { 8697 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8698 return !S.getLangOpts().CPlusPlus; 8699 } 8700 if (PointeeTy->isFunctionType()) { 8701 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8702 return !S.getLangOpts().CPlusPlus; 8703 } 8704 8705 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8706 8707 return true; 8708 } 8709 8710 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8711 /// operands. 8712 /// 8713 /// This routine will diagnose any invalid arithmetic on pointer operands much 8714 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8715 /// for emitting a single diagnostic even for operations where both LHS and RHS 8716 /// are (potentially problematic) pointers. 8717 /// 8718 /// \returns True when the operand is valid to use (even if as an extension). 8719 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8720 Expr *LHSExpr, Expr *RHSExpr) { 8721 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8722 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8723 if (!isLHSPointer && !isRHSPointer) return true; 8724 8725 QualType LHSPointeeTy, RHSPointeeTy; 8726 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8727 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8728 8729 // if both are pointers check if operation is valid wrt address spaces 8730 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8731 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8732 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8733 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8734 S.Diag(Loc, 8735 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8736 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8737 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8738 return false; 8739 } 8740 } 8741 8742 // Check for arithmetic on pointers to incomplete types. 8743 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8744 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8745 if (isLHSVoidPtr || isRHSVoidPtr) { 8746 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8747 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8748 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8749 8750 return !S.getLangOpts().CPlusPlus; 8751 } 8752 8753 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8754 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8755 if (isLHSFuncPtr || isRHSFuncPtr) { 8756 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8757 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8758 RHSExpr); 8759 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8760 8761 return !S.getLangOpts().CPlusPlus; 8762 } 8763 8764 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8765 return false; 8766 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8767 return false; 8768 8769 return true; 8770 } 8771 8772 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8773 /// literal. 8774 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8775 Expr *LHSExpr, Expr *RHSExpr) { 8776 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8777 Expr* IndexExpr = RHSExpr; 8778 if (!StrExpr) { 8779 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8780 IndexExpr = LHSExpr; 8781 } 8782 8783 bool IsStringPlusInt = StrExpr && 8784 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8785 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8786 return; 8787 8788 llvm::APSInt index; 8789 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8790 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8791 if (index.isNonNegative() && 8792 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8793 index.isUnsigned())) 8794 return; 8795 } 8796 8797 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8798 Self.Diag(OpLoc, diag::warn_string_plus_int) 8799 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8800 8801 // Only print a fixit for "str" + int, not for int + "str". 8802 if (IndexExpr == RHSExpr) { 8803 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8804 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8805 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8806 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8807 << FixItHint::CreateInsertion(EndLoc, "]"); 8808 } else 8809 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8810 } 8811 8812 /// \brief Emit a warning when adding a char literal to a string. 8813 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8814 Expr *LHSExpr, Expr *RHSExpr) { 8815 const Expr *StringRefExpr = LHSExpr; 8816 const CharacterLiteral *CharExpr = 8817 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8818 8819 if (!CharExpr) { 8820 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8821 StringRefExpr = RHSExpr; 8822 } 8823 8824 if (!CharExpr || !StringRefExpr) 8825 return; 8826 8827 const QualType StringType = StringRefExpr->getType(); 8828 8829 // Return if not a PointerType. 8830 if (!StringType->isAnyPointerType()) 8831 return; 8832 8833 // Return if not a CharacterType. 8834 if (!StringType->getPointeeType()->isAnyCharacterType()) 8835 return; 8836 8837 ASTContext &Ctx = Self.getASTContext(); 8838 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8839 8840 const QualType CharType = CharExpr->getType(); 8841 if (!CharType->isAnyCharacterType() && 8842 CharType->isIntegerType() && 8843 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8844 Self.Diag(OpLoc, diag::warn_string_plus_char) 8845 << DiagRange << Ctx.CharTy; 8846 } else { 8847 Self.Diag(OpLoc, diag::warn_string_plus_char) 8848 << DiagRange << CharExpr->getType(); 8849 } 8850 8851 // Only print a fixit for str + char, not for char + str. 8852 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8853 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8854 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8855 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8856 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8857 << FixItHint::CreateInsertion(EndLoc, "]"); 8858 } else { 8859 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8860 } 8861 } 8862 8863 /// \brief Emit error when two pointers are incompatible. 8864 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8865 Expr *LHSExpr, Expr *RHSExpr) { 8866 assert(LHSExpr->getType()->isAnyPointerType()); 8867 assert(RHSExpr->getType()->isAnyPointerType()); 8868 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8869 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8870 << RHSExpr->getSourceRange(); 8871 } 8872 8873 // C99 6.5.6 8874 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8875 SourceLocation Loc, BinaryOperatorKind Opc, 8876 QualType* CompLHSTy) { 8877 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8878 8879 if (LHS.get()->getType()->isVectorType() || 8880 RHS.get()->getType()->isVectorType()) { 8881 QualType compType = CheckVectorOperands( 8882 LHS, RHS, Loc, CompLHSTy, 8883 /*AllowBothBool*/getLangOpts().AltiVec, 8884 /*AllowBoolConversions*/getLangOpts().ZVector); 8885 if (CompLHSTy) *CompLHSTy = compType; 8886 return compType; 8887 } 8888 8889 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8890 if (LHS.isInvalid() || RHS.isInvalid()) 8891 return QualType(); 8892 8893 // Diagnose "string literal" '+' int and string '+' "char literal". 8894 if (Opc == BO_Add) { 8895 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8896 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8897 } 8898 8899 // handle the common case first (both operands are arithmetic). 8900 if (!compType.isNull() && compType->isArithmeticType()) { 8901 if (CompLHSTy) *CompLHSTy = compType; 8902 return compType; 8903 } 8904 8905 // Type-checking. Ultimately the pointer's going to be in PExp; 8906 // note that we bias towards the LHS being the pointer. 8907 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8908 8909 bool isObjCPointer; 8910 if (PExp->getType()->isPointerType()) { 8911 isObjCPointer = false; 8912 } else if (PExp->getType()->isObjCObjectPointerType()) { 8913 isObjCPointer = true; 8914 } else { 8915 std::swap(PExp, IExp); 8916 if (PExp->getType()->isPointerType()) { 8917 isObjCPointer = false; 8918 } else if (PExp->getType()->isObjCObjectPointerType()) { 8919 isObjCPointer = true; 8920 } else { 8921 return InvalidOperands(Loc, LHS, RHS); 8922 } 8923 } 8924 assert(PExp->getType()->isAnyPointerType()); 8925 8926 if (!IExp->getType()->isIntegerType()) 8927 return InvalidOperands(Loc, LHS, RHS); 8928 8929 // Adding to a null pointer results in undefined behavior. 8930 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8931 Context, Expr::NPC_ValueDependentIsNotNull)) { 8932 // In C++ adding zero to a null pointer is defined. 8933 llvm::APSInt KnownVal; 8934 if (!getLangOpts().CPlusPlus || 8935 (!IExp->isValueDependent() && 8936 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8937 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8938 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8939 Context, BO_Add, PExp, IExp); 8940 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8941 } 8942 } 8943 8944 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8945 return QualType(); 8946 8947 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8948 return QualType(); 8949 8950 // Check array bounds for pointer arithemtic 8951 CheckArrayAccess(PExp, IExp); 8952 8953 if (CompLHSTy) { 8954 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8955 if (LHSTy.isNull()) { 8956 LHSTy = LHS.get()->getType(); 8957 if (LHSTy->isPromotableIntegerType()) 8958 LHSTy = Context.getPromotedIntegerType(LHSTy); 8959 } 8960 *CompLHSTy = LHSTy; 8961 } 8962 8963 return PExp->getType(); 8964 } 8965 8966 // C99 6.5.6 8967 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8968 SourceLocation Loc, 8969 QualType* CompLHSTy) { 8970 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8971 8972 if (LHS.get()->getType()->isVectorType() || 8973 RHS.get()->getType()->isVectorType()) { 8974 QualType compType = CheckVectorOperands( 8975 LHS, RHS, Loc, CompLHSTy, 8976 /*AllowBothBool*/getLangOpts().AltiVec, 8977 /*AllowBoolConversions*/getLangOpts().ZVector); 8978 if (CompLHSTy) *CompLHSTy = compType; 8979 return compType; 8980 } 8981 8982 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8983 if (LHS.isInvalid() || RHS.isInvalid()) 8984 return QualType(); 8985 8986 // Enforce type constraints: C99 6.5.6p3. 8987 8988 // Handle the common case first (both operands are arithmetic). 8989 if (!compType.isNull() && compType->isArithmeticType()) { 8990 if (CompLHSTy) *CompLHSTy = compType; 8991 return compType; 8992 } 8993 8994 // Either ptr - int or ptr - ptr. 8995 if (LHS.get()->getType()->isAnyPointerType()) { 8996 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8997 8998 // Diagnose bad cases where we step over interface counts. 8999 if (LHS.get()->getType()->isObjCObjectPointerType() && 9000 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9001 return QualType(); 9002 9003 // The result type of a pointer-int computation is the pointer type. 9004 if (RHS.get()->getType()->isIntegerType()) { 9005 // Subtracting from a null pointer should produce a warning. 9006 // The last argument to the diagnose call says this doesn't match the 9007 // GNU int-to-pointer idiom. 9008 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9009 Expr::NPC_ValueDependentIsNotNull)) { 9010 // In C++ adding zero to a null pointer is defined. 9011 llvm::APSInt KnownVal; 9012 if (!getLangOpts().CPlusPlus || 9013 (!RHS.get()->isValueDependent() && 9014 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9015 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9016 } 9017 } 9018 9019 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9020 return QualType(); 9021 9022 // Check array bounds for pointer arithemtic 9023 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9024 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9025 9026 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9027 return LHS.get()->getType(); 9028 } 9029 9030 // Handle pointer-pointer subtractions. 9031 if (const PointerType *RHSPTy 9032 = RHS.get()->getType()->getAs<PointerType>()) { 9033 QualType rpointee = RHSPTy->getPointeeType(); 9034 9035 if (getLangOpts().CPlusPlus) { 9036 // Pointee types must be the same: C++ [expr.add] 9037 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9038 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9039 } 9040 } else { 9041 // Pointee types must be compatible C99 6.5.6p3 9042 if (!Context.typesAreCompatible( 9043 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9044 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9045 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9046 return QualType(); 9047 } 9048 } 9049 9050 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9051 LHS.get(), RHS.get())) 9052 return QualType(); 9053 9054 // FIXME: Add warnings for nullptr - ptr. 9055 9056 // The pointee type may have zero size. As an extension, a structure or 9057 // union may have zero size or an array may have zero length. In this 9058 // case subtraction does not make sense. 9059 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9060 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9061 if (ElementSize.isZero()) { 9062 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9063 << rpointee.getUnqualifiedType() 9064 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9065 } 9066 } 9067 9068 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9069 return Context.getPointerDiffType(); 9070 } 9071 } 9072 9073 return InvalidOperands(Loc, LHS, RHS); 9074 } 9075 9076 static bool isScopedEnumerationType(QualType T) { 9077 if (const EnumType *ET = T->getAs<EnumType>()) 9078 return ET->getDecl()->isScoped(); 9079 return false; 9080 } 9081 9082 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9083 SourceLocation Loc, BinaryOperatorKind Opc, 9084 QualType LHSType) { 9085 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9086 // so skip remaining warnings as we don't want to modify values within Sema. 9087 if (S.getLangOpts().OpenCL) 9088 return; 9089 9090 llvm::APSInt Right; 9091 // Check right/shifter operand 9092 if (RHS.get()->isValueDependent() || 9093 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9094 return; 9095 9096 if (Right.isNegative()) { 9097 S.DiagRuntimeBehavior(Loc, RHS.get(), 9098 S.PDiag(diag::warn_shift_negative) 9099 << RHS.get()->getSourceRange()); 9100 return; 9101 } 9102 llvm::APInt LeftBits(Right.getBitWidth(), 9103 S.Context.getTypeSize(LHS.get()->getType())); 9104 if (Right.uge(LeftBits)) { 9105 S.DiagRuntimeBehavior(Loc, RHS.get(), 9106 S.PDiag(diag::warn_shift_gt_typewidth) 9107 << RHS.get()->getSourceRange()); 9108 return; 9109 } 9110 if (Opc != BO_Shl) 9111 return; 9112 9113 // When left shifting an ICE which is signed, we can check for overflow which 9114 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9115 // integers have defined behavior modulo one more than the maximum value 9116 // representable in the result type, so never warn for those. 9117 llvm::APSInt Left; 9118 if (LHS.get()->isValueDependent() || 9119 LHSType->hasUnsignedIntegerRepresentation() || 9120 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9121 return; 9122 9123 // If LHS does not have a signed type and non-negative value 9124 // then, the behavior is undefined. Warn about it. 9125 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9126 S.DiagRuntimeBehavior(Loc, LHS.get(), 9127 S.PDiag(diag::warn_shift_lhs_negative) 9128 << LHS.get()->getSourceRange()); 9129 return; 9130 } 9131 9132 llvm::APInt ResultBits = 9133 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9134 if (LeftBits.uge(ResultBits)) 9135 return; 9136 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9137 Result = Result.shl(Right); 9138 9139 // Print the bit representation of the signed integer as an unsigned 9140 // hexadecimal number. 9141 SmallString<40> HexResult; 9142 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9143 9144 // If we are only missing a sign bit, this is less likely to result in actual 9145 // bugs -- if the result is cast back to an unsigned type, it will have the 9146 // expected value. Thus we place this behind a different warning that can be 9147 // turned off separately if needed. 9148 if (LeftBits == ResultBits - 1) { 9149 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9150 << HexResult << LHSType 9151 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9152 return; 9153 } 9154 9155 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9156 << HexResult.str() << Result.getMinSignedBits() << LHSType 9157 << Left.getBitWidth() << LHS.get()->getSourceRange() 9158 << RHS.get()->getSourceRange(); 9159 } 9160 9161 /// \brief Return the resulting type when a vector is shifted 9162 /// by a scalar or vector shift amount. 9163 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9164 SourceLocation Loc, bool IsCompAssign) { 9165 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9166 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9167 !LHS.get()->getType()->isVectorType()) { 9168 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9169 << RHS.get()->getType() << LHS.get()->getType() 9170 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9171 return QualType(); 9172 } 9173 9174 if (!IsCompAssign) { 9175 LHS = S.UsualUnaryConversions(LHS.get()); 9176 if (LHS.isInvalid()) return QualType(); 9177 } 9178 9179 RHS = S.UsualUnaryConversions(RHS.get()); 9180 if (RHS.isInvalid()) return QualType(); 9181 9182 QualType LHSType = LHS.get()->getType(); 9183 // Note that LHS might be a scalar because the routine calls not only in 9184 // OpenCL case. 9185 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9186 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9187 9188 // Note that RHS might not be a vector. 9189 QualType RHSType = RHS.get()->getType(); 9190 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9191 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9192 9193 // The operands need to be integers. 9194 if (!LHSEleType->isIntegerType()) { 9195 S.Diag(Loc, diag::err_typecheck_expect_int) 9196 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9197 return QualType(); 9198 } 9199 9200 if (!RHSEleType->isIntegerType()) { 9201 S.Diag(Loc, diag::err_typecheck_expect_int) 9202 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9203 return QualType(); 9204 } 9205 9206 if (!LHSVecTy) { 9207 assert(RHSVecTy); 9208 if (IsCompAssign) 9209 return RHSType; 9210 if (LHSEleType != RHSEleType) { 9211 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9212 LHSEleType = RHSEleType; 9213 } 9214 QualType VecTy = 9215 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9216 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9217 LHSType = VecTy; 9218 } else if (RHSVecTy) { 9219 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9220 // are applied component-wise. So if RHS is a vector, then ensure 9221 // that the number of elements is the same as LHS... 9222 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9223 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9224 << LHS.get()->getType() << RHS.get()->getType() 9225 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9226 return QualType(); 9227 } 9228 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9229 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9230 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9231 if (LHSBT != RHSBT && 9232 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9233 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9234 << LHS.get()->getType() << RHS.get()->getType() 9235 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9236 } 9237 } 9238 } else { 9239 // ...else expand RHS to match the number of elements in LHS. 9240 QualType VecTy = 9241 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9242 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9243 } 9244 9245 return LHSType; 9246 } 9247 9248 // C99 6.5.7 9249 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9250 SourceLocation Loc, BinaryOperatorKind Opc, 9251 bool IsCompAssign) { 9252 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9253 9254 // Vector shifts promote their scalar inputs to vector type. 9255 if (LHS.get()->getType()->isVectorType() || 9256 RHS.get()->getType()->isVectorType()) { 9257 if (LangOpts.ZVector) { 9258 // The shift operators for the z vector extensions work basically 9259 // like general shifts, except that neither the LHS nor the RHS is 9260 // allowed to be a "vector bool". 9261 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9262 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9263 return InvalidOperands(Loc, LHS, RHS); 9264 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9265 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9266 return InvalidOperands(Loc, LHS, RHS); 9267 } 9268 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9269 } 9270 9271 // Shifts don't perform usual arithmetic conversions, they just do integer 9272 // promotions on each operand. C99 6.5.7p3 9273 9274 // For the LHS, do usual unary conversions, but then reset them away 9275 // if this is a compound assignment. 9276 ExprResult OldLHS = LHS; 9277 LHS = UsualUnaryConversions(LHS.get()); 9278 if (LHS.isInvalid()) 9279 return QualType(); 9280 QualType LHSType = LHS.get()->getType(); 9281 if (IsCompAssign) LHS = OldLHS; 9282 9283 // The RHS is simpler. 9284 RHS = UsualUnaryConversions(RHS.get()); 9285 if (RHS.isInvalid()) 9286 return QualType(); 9287 QualType RHSType = RHS.get()->getType(); 9288 9289 // C99 6.5.7p2: Each of the operands shall have integer type. 9290 if (!LHSType->hasIntegerRepresentation() || 9291 !RHSType->hasIntegerRepresentation()) 9292 return InvalidOperands(Loc, LHS, RHS); 9293 9294 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9295 // hasIntegerRepresentation() above instead of this. 9296 if (isScopedEnumerationType(LHSType) || 9297 isScopedEnumerationType(RHSType)) { 9298 return InvalidOperands(Loc, LHS, RHS); 9299 } 9300 // Sanity-check shift operands 9301 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9302 9303 // "The type of the result is that of the promoted left operand." 9304 return LHSType; 9305 } 9306 9307 /// If two different enums are compared, raise a warning. 9308 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9309 Expr *RHS) { 9310 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9311 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9312 9313 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9314 if (!LHSEnumType) 9315 return; 9316 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9317 if (!RHSEnumType) 9318 return; 9319 9320 // Ignore anonymous enums. 9321 if (!LHSEnumType->getDecl()->getIdentifier() && 9322 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9323 return; 9324 if (!RHSEnumType->getDecl()->getIdentifier() && 9325 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9326 return; 9327 9328 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9329 return; 9330 9331 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9332 << LHSStrippedType << RHSStrippedType 9333 << LHS->getSourceRange() << RHS->getSourceRange(); 9334 } 9335 9336 /// \brief Diagnose bad pointer comparisons. 9337 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9338 ExprResult &LHS, ExprResult &RHS, 9339 bool IsError) { 9340 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9341 : diag::ext_typecheck_comparison_of_distinct_pointers) 9342 << LHS.get()->getType() << RHS.get()->getType() 9343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9344 } 9345 9346 /// \brief Returns false if the pointers are converted to a composite type, 9347 /// true otherwise. 9348 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9349 ExprResult &LHS, ExprResult &RHS) { 9350 // C++ [expr.rel]p2: 9351 // [...] Pointer conversions (4.10) and qualification 9352 // conversions (4.4) are performed on pointer operands (or on 9353 // a pointer operand and a null pointer constant) to bring 9354 // them to their composite pointer type. [...] 9355 // 9356 // C++ [expr.eq]p1 uses the same notion for (in)equality 9357 // comparisons of pointers. 9358 9359 QualType LHSType = LHS.get()->getType(); 9360 QualType RHSType = RHS.get()->getType(); 9361 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9362 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9363 9364 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9365 if (T.isNull()) { 9366 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9367 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9368 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9369 else 9370 S.InvalidOperands(Loc, LHS, RHS); 9371 return true; 9372 } 9373 9374 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9375 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9376 return false; 9377 } 9378 9379 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9380 ExprResult &LHS, 9381 ExprResult &RHS, 9382 bool IsError) { 9383 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9384 : diag::ext_typecheck_comparison_of_fptr_to_void) 9385 << LHS.get()->getType() << RHS.get()->getType() 9386 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9387 } 9388 9389 static bool isObjCObjectLiteral(ExprResult &E) { 9390 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9391 case Stmt::ObjCArrayLiteralClass: 9392 case Stmt::ObjCDictionaryLiteralClass: 9393 case Stmt::ObjCStringLiteralClass: 9394 case Stmt::ObjCBoxedExprClass: 9395 return true; 9396 default: 9397 // Note that ObjCBoolLiteral is NOT an object literal! 9398 return false; 9399 } 9400 } 9401 9402 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9403 const ObjCObjectPointerType *Type = 9404 LHS->getType()->getAs<ObjCObjectPointerType>(); 9405 9406 // If this is not actually an Objective-C object, bail out. 9407 if (!Type) 9408 return false; 9409 9410 // Get the LHS object's interface type. 9411 QualType InterfaceType = Type->getPointeeType(); 9412 9413 // If the RHS isn't an Objective-C object, bail out. 9414 if (!RHS->getType()->isObjCObjectPointerType()) 9415 return false; 9416 9417 // Try to find the -isEqual: method. 9418 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9419 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9420 InterfaceType, 9421 /*instance=*/true); 9422 if (!Method) { 9423 if (Type->isObjCIdType()) { 9424 // For 'id', just check the global pool. 9425 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9426 /*receiverId=*/true); 9427 } else { 9428 // Check protocols. 9429 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9430 /*instance=*/true); 9431 } 9432 } 9433 9434 if (!Method) 9435 return false; 9436 9437 QualType T = Method->parameters()[0]->getType(); 9438 if (!T->isObjCObjectPointerType()) 9439 return false; 9440 9441 QualType R = Method->getReturnType(); 9442 if (!R->isScalarType()) 9443 return false; 9444 9445 return true; 9446 } 9447 9448 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9449 FromE = FromE->IgnoreParenImpCasts(); 9450 switch (FromE->getStmtClass()) { 9451 default: 9452 break; 9453 case Stmt::ObjCStringLiteralClass: 9454 // "string literal" 9455 return LK_String; 9456 case Stmt::ObjCArrayLiteralClass: 9457 // "array literal" 9458 return LK_Array; 9459 case Stmt::ObjCDictionaryLiteralClass: 9460 // "dictionary literal" 9461 return LK_Dictionary; 9462 case Stmt::BlockExprClass: 9463 return LK_Block; 9464 case Stmt::ObjCBoxedExprClass: { 9465 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9466 switch (Inner->getStmtClass()) { 9467 case Stmt::IntegerLiteralClass: 9468 case Stmt::FloatingLiteralClass: 9469 case Stmt::CharacterLiteralClass: 9470 case Stmt::ObjCBoolLiteralExprClass: 9471 case Stmt::CXXBoolLiteralExprClass: 9472 // "numeric literal" 9473 return LK_Numeric; 9474 case Stmt::ImplicitCastExprClass: { 9475 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9476 // Boolean literals can be represented by implicit casts. 9477 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9478 return LK_Numeric; 9479 break; 9480 } 9481 default: 9482 break; 9483 } 9484 return LK_Boxed; 9485 } 9486 } 9487 return LK_None; 9488 } 9489 9490 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9491 ExprResult &LHS, ExprResult &RHS, 9492 BinaryOperator::Opcode Opc){ 9493 Expr *Literal; 9494 Expr *Other; 9495 if (isObjCObjectLiteral(LHS)) { 9496 Literal = LHS.get(); 9497 Other = RHS.get(); 9498 } else { 9499 Literal = RHS.get(); 9500 Other = LHS.get(); 9501 } 9502 9503 // Don't warn on comparisons against nil. 9504 Other = Other->IgnoreParenCasts(); 9505 if (Other->isNullPointerConstant(S.getASTContext(), 9506 Expr::NPC_ValueDependentIsNotNull)) 9507 return; 9508 9509 // This should be kept in sync with warn_objc_literal_comparison. 9510 // LK_String should always be after the other literals, since it has its own 9511 // warning flag. 9512 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9513 assert(LiteralKind != Sema::LK_Block); 9514 if (LiteralKind == Sema::LK_None) { 9515 llvm_unreachable("Unknown Objective-C object literal kind"); 9516 } 9517 9518 if (LiteralKind == Sema::LK_String) 9519 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9520 << Literal->getSourceRange(); 9521 else 9522 S.Diag(Loc, diag::warn_objc_literal_comparison) 9523 << LiteralKind << Literal->getSourceRange(); 9524 9525 if (BinaryOperator::isEqualityOp(Opc) && 9526 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9527 SourceLocation Start = LHS.get()->getLocStart(); 9528 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9529 CharSourceRange OpRange = 9530 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9531 9532 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9533 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9534 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9535 << FixItHint::CreateInsertion(End, "]"); 9536 } 9537 } 9538 9539 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9540 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9541 ExprResult &RHS, SourceLocation Loc, 9542 BinaryOperatorKind Opc) { 9543 // Check that left hand side is !something. 9544 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9545 if (!UO || UO->getOpcode() != UO_LNot) return; 9546 9547 // Only check if the right hand side is non-bool arithmetic type. 9548 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9549 9550 // Make sure that the something in !something is not bool. 9551 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9552 if (SubExpr->isKnownToHaveBooleanValue()) return; 9553 9554 // Emit warning. 9555 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9556 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9557 << Loc << IsBitwiseOp; 9558 9559 // First note suggest !(x < y) 9560 SourceLocation FirstOpen = SubExpr->getLocStart(); 9561 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9562 FirstClose = S.getLocForEndOfToken(FirstClose); 9563 if (FirstClose.isInvalid()) 9564 FirstOpen = SourceLocation(); 9565 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9566 << IsBitwiseOp 9567 << FixItHint::CreateInsertion(FirstOpen, "(") 9568 << FixItHint::CreateInsertion(FirstClose, ")"); 9569 9570 // Second note suggests (!x) < y 9571 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9572 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9573 SecondClose = S.getLocForEndOfToken(SecondClose); 9574 if (SecondClose.isInvalid()) 9575 SecondOpen = SourceLocation(); 9576 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9577 << FixItHint::CreateInsertion(SecondOpen, "(") 9578 << FixItHint::CreateInsertion(SecondClose, ")"); 9579 } 9580 9581 // Get the decl for a simple expression: a reference to a variable, 9582 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9583 static ValueDecl *getCompareDecl(Expr *E) { 9584 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9585 return DR->getDecl(); 9586 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9587 if (Ivar->isFreeIvar()) 9588 return Ivar->getDecl(); 9589 } 9590 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9591 if (Mem->isImplicitAccess()) 9592 return Mem->getMemberDecl(); 9593 } 9594 return nullptr; 9595 } 9596 9597 /// Diagnose some forms of syntactically-obvious tautological comparison. 9598 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9599 Expr *LHS, Expr *RHS, 9600 BinaryOperatorKind Opc) { 9601 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9602 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9603 9604 QualType LHSType = LHS->getType(); 9605 if (LHSType->hasFloatingRepresentation() || 9606 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9607 LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() || 9608 S.inTemplateInstantiation()) 9609 return; 9610 9611 // For non-floating point types, check for self-comparisons of the form 9612 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9613 // often indicate logic errors in the program. 9614 // 9615 // NOTE: Don't warn about comparison expressions resulting from macro 9616 // expansion. Also don't warn about comparisons which are only self 9617 // comparisons within a template instantiation. The warnings should catch 9618 // obvious cases in the definition of the template anyways. The idea is to 9619 // warn when the typed comparison operator will always evaluate to the same 9620 // result. 9621 ValueDecl *DL = getCompareDecl(LHSStripped); 9622 ValueDecl *DR = getCompareDecl(RHSStripped); 9623 if (DL && DR && declaresSameEntity(DL, DR)) { 9624 StringRef Result; 9625 switch (Opc) { 9626 case BO_EQ: case BO_LE: case BO_GE: 9627 Result = "true"; 9628 break; 9629 case BO_NE: case BO_LT: case BO_GT: 9630 Result = "false"; 9631 break; 9632 case BO_Cmp: 9633 Result = "'std::strong_ordering::equal'"; 9634 break; 9635 default: 9636 break; 9637 } 9638 S.DiagRuntimeBehavior(Loc, nullptr, 9639 S.PDiag(diag::warn_comparison_always) 9640 << 0 /*self-comparison*/ << !Result.empty() 9641 << Result); 9642 } else if (DL && DR && 9643 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9644 !DL->isWeak() && !DR->isWeak()) { 9645 // What is it always going to evaluate to? 9646 StringRef Result; 9647 switch(Opc) { 9648 case BO_EQ: // e.g. array1 == array2 9649 Result = "false"; 9650 break; 9651 case BO_NE: // e.g. array1 != array2 9652 Result = "true"; 9653 break; 9654 default: // e.g. array1 <= array2 9655 // The best we can say is 'a constant' 9656 break; 9657 } 9658 S.DiagRuntimeBehavior(Loc, nullptr, 9659 S.PDiag(diag::warn_comparison_always) 9660 << 1 /*array comparison*/ 9661 << !Result.empty() << Result); 9662 } 9663 9664 if (isa<CastExpr>(LHSStripped)) 9665 LHSStripped = LHSStripped->IgnoreParenCasts(); 9666 if (isa<CastExpr>(RHSStripped)) 9667 RHSStripped = RHSStripped->IgnoreParenCasts(); 9668 9669 // Warn about comparisons against a string constant (unless the other 9670 // operand is null); the user probably wants strcmp. 9671 Expr *LiteralString = nullptr; 9672 Expr *LiteralStringStripped = nullptr; 9673 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9674 !RHSStripped->isNullPointerConstant(S.Context, 9675 Expr::NPC_ValueDependentIsNull)) { 9676 LiteralString = LHS; 9677 LiteralStringStripped = LHSStripped; 9678 } else if ((isa<StringLiteral>(RHSStripped) || 9679 isa<ObjCEncodeExpr>(RHSStripped)) && 9680 !LHSStripped->isNullPointerConstant(S.Context, 9681 Expr::NPC_ValueDependentIsNull)) { 9682 LiteralString = RHS; 9683 LiteralStringStripped = RHSStripped; 9684 } 9685 9686 if (LiteralString) { 9687 S.DiagRuntimeBehavior(Loc, nullptr, 9688 S.PDiag(diag::warn_stringcompare) 9689 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9690 << LiteralString->getSourceRange()); 9691 } 9692 } 9693 9694 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9695 ExprResult &RHS, 9696 SourceLocation Loc, 9697 BinaryOperatorKind Opc) { 9698 // C99 6.5.8p3 / C99 6.5.9p4 9699 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9700 if (LHS.isInvalid() || RHS.isInvalid()) 9701 return QualType(); 9702 if (Type.isNull()) 9703 return S.InvalidOperands(Loc, LHS, RHS); 9704 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9705 9706 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9707 9708 enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering; 9709 if (Type->isAnyComplexType()) 9710 Ordering = StrongEquality; 9711 else if (Type->isFloatingType()) 9712 Ordering = PartialOrdering; 9713 else 9714 Ordering = StrongOrdering; 9715 9716 if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc)) 9717 return S.InvalidOperands(Loc, LHS, RHS); 9718 9719 // Check for comparisons of floating point operands using != and ==. 9720 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 9721 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9722 9723 // The result of comparisons is 'bool' in C++, 'int' in C. 9724 // FIXME: For BO_Cmp, return the relevant comparison category type. 9725 return S.Context.getLogicalOperationType(); 9726 } 9727 9728 // C99 6.5.8, C++ [expr.rel] 9729 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9730 SourceLocation Loc, BinaryOperatorKind Opc, 9731 bool IsRelational) { 9732 // Comparisons expect an rvalue, so convert to rvalue before any 9733 // type-related checks. 9734 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9735 if (LHS.isInvalid()) 9736 return QualType(); 9737 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9738 if (RHS.isInvalid()) 9739 return QualType(); 9740 9741 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9742 9743 // Handle vector comparisons separately. 9744 if (LHS.get()->getType()->isVectorType() || 9745 RHS.get()->getType()->isVectorType()) 9746 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 9747 9748 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9749 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 9750 9751 QualType LHSType = LHS.get()->getType(); 9752 QualType RHSType = RHS.get()->getType(); 9753 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 9754 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 9755 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 9756 9757 QualType ResultTy = Context.getLogicalOperationType(); 9758 9759 const Expr::NullPointerConstantKind LHSNullKind = 9760 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9761 const Expr::NullPointerConstantKind RHSNullKind = 9762 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9763 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9764 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9765 9766 if (!IsRelational && LHSIsNull != RHSIsNull) { 9767 bool IsEquality = Opc == BO_EQ; 9768 if (RHSIsNull) 9769 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9770 RHS.get()->getSourceRange()); 9771 else 9772 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9773 LHS.get()->getSourceRange()); 9774 } 9775 9776 if ((LHSType->isIntegerType() && !LHSIsNull) || 9777 (RHSType->isIntegerType() && !RHSIsNull)) { 9778 // Skip normal pointer conversion checks in this case; we have better 9779 // diagnostics for this below. 9780 } else if (getLangOpts().CPlusPlus) { 9781 // Equality comparison of a function pointer to a void pointer is invalid, 9782 // but we allow it as an extension. 9783 // FIXME: If we really want to allow this, should it be part of composite 9784 // pointer type computation so it works in conditionals too? 9785 if (!IsRelational && 9786 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9787 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9788 // This is a gcc extension compatibility comparison. 9789 // In a SFINAE context, we treat this as a hard error to maintain 9790 // conformance with the C++ standard. 9791 diagnoseFunctionPointerToVoidComparison( 9792 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9793 9794 if (isSFINAEContext()) 9795 return QualType(); 9796 9797 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9798 return ResultTy; 9799 } 9800 9801 // C++ [expr.eq]p2: 9802 // If at least one operand is a pointer [...] bring them to their 9803 // composite pointer type. 9804 // C++ [expr.rel]p2: 9805 // If both operands are pointers, [...] bring them to their composite 9806 // pointer type. 9807 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9808 (IsRelational ? 2 : 1) && 9809 (!LangOpts.ObjCAutoRefCount || 9810 !(LHSType->isObjCObjectPointerType() || 9811 RHSType->isObjCObjectPointerType()))) { 9812 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9813 return QualType(); 9814 else 9815 return ResultTy; 9816 } 9817 } else if (LHSType->isPointerType() && 9818 RHSType->isPointerType()) { // C99 6.5.8p2 9819 // All of the following pointer-related warnings are GCC extensions, except 9820 // when handling null pointer constants. 9821 QualType LCanPointeeTy = 9822 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9823 QualType RCanPointeeTy = 9824 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9825 9826 // C99 6.5.9p2 and C99 6.5.8p2 9827 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9828 RCanPointeeTy.getUnqualifiedType())) { 9829 // Valid unless a relational comparison of function pointers 9830 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9831 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9832 << LHSType << RHSType << LHS.get()->getSourceRange() 9833 << RHS.get()->getSourceRange(); 9834 } 9835 } else if (!IsRelational && 9836 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9837 // Valid unless comparison between non-null pointer and function pointer 9838 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9839 && !LHSIsNull && !RHSIsNull) 9840 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9841 /*isError*/false); 9842 } else { 9843 // Invalid 9844 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9845 } 9846 if (LCanPointeeTy != RCanPointeeTy) { 9847 // Treat NULL constant as a special case in OpenCL. 9848 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9849 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9850 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9851 Diag(Loc, 9852 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9853 << LHSType << RHSType << 0 /* comparison */ 9854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9855 } 9856 } 9857 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9858 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9859 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9860 : CK_BitCast; 9861 if (LHSIsNull && !RHSIsNull) 9862 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9863 else 9864 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9865 } 9866 return ResultTy; 9867 } 9868 9869 if (getLangOpts().CPlusPlus) { 9870 // C++ [expr.eq]p4: 9871 // Two operands of type std::nullptr_t or one operand of type 9872 // std::nullptr_t and the other a null pointer constant compare equal. 9873 if (!IsRelational && LHSIsNull && RHSIsNull) { 9874 if (LHSType->isNullPtrType()) { 9875 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9876 return ResultTy; 9877 } 9878 if (RHSType->isNullPtrType()) { 9879 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9880 return ResultTy; 9881 } 9882 } 9883 9884 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9885 // These aren't covered by the composite pointer type rules. 9886 if (!IsRelational && RHSType->isNullPtrType() && 9887 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9888 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9889 return ResultTy; 9890 } 9891 if (!IsRelational && LHSType->isNullPtrType() && 9892 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9893 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9894 return ResultTy; 9895 } 9896 9897 if (IsRelational && 9898 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9899 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9900 // HACK: Relational comparison of nullptr_t against a pointer type is 9901 // invalid per DR583, but we allow it within std::less<> and friends, 9902 // since otherwise common uses of it break. 9903 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9904 // friends to have std::nullptr_t overload candidates. 9905 DeclContext *DC = CurContext; 9906 if (isa<FunctionDecl>(DC)) 9907 DC = DC->getParent(); 9908 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9909 if (CTSD->isInStdNamespace() && 9910 llvm::StringSwitch<bool>(CTSD->getName()) 9911 .Cases("less", "less_equal", "greater", "greater_equal", true) 9912 .Default(false)) { 9913 if (RHSType->isNullPtrType()) 9914 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9915 else 9916 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9917 return ResultTy; 9918 } 9919 } 9920 } 9921 9922 // C++ [expr.eq]p2: 9923 // If at least one operand is a pointer to member, [...] bring them to 9924 // their composite pointer type. 9925 if (!IsRelational && 9926 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9927 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9928 return QualType(); 9929 else 9930 return ResultTy; 9931 } 9932 } 9933 9934 // Handle block pointer types. 9935 if (!IsRelational && LHSType->isBlockPointerType() && 9936 RHSType->isBlockPointerType()) { 9937 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9938 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9939 9940 if (!LHSIsNull && !RHSIsNull && 9941 !Context.typesAreCompatible(lpointee, rpointee)) { 9942 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9943 << LHSType << RHSType << LHS.get()->getSourceRange() 9944 << RHS.get()->getSourceRange(); 9945 } 9946 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9947 return ResultTy; 9948 } 9949 9950 // Allow block pointers to be compared with null pointer constants. 9951 if (!IsRelational 9952 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9953 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9954 if (!LHSIsNull && !RHSIsNull) { 9955 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9956 ->getPointeeType()->isVoidType()) 9957 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9958 ->getPointeeType()->isVoidType()))) 9959 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9960 << LHSType << RHSType << LHS.get()->getSourceRange() 9961 << RHS.get()->getSourceRange(); 9962 } 9963 if (LHSIsNull && !RHSIsNull) 9964 LHS = ImpCastExprToType(LHS.get(), RHSType, 9965 RHSType->isPointerType() ? CK_BitCast 9966 : CK_AnyPointerToBlockPointerCast); 9967 else 9968 RHS = ImpCastExprToType(RHS.get(), LHSType, 9969 LHSType->isPointerType() ? CK_BitCast 9970 : CK_AnyPointerToBlockPointerCast); 9971 return ResultTy; 9972 } 9973 9974 if (LHSType->isObjCObjectPointerType() || 9975 RHSType->isObjCObjectPointerType()) { 9976 const PointerType *LPT = LHSType->getAs<PointerType>(); 9977 const PointerType *RPT = RHSType->getAs<PointerType>(); 9978 if (LPT || RPT) { 9979 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9980 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9981 9982 if (!LPtrToVoid && !RPtrToVoid && 9983 !Context.typesAreCompatible(LHSType, RHSType)) { 9984 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9985 /*isError*/false); 9986 } 9987 if (LHSIsNull && !RHSIsNull) { 9988 Expr *E = LHS.get(); 9989 if (getLangOpts().ObjCAutoRefCount) 9990 CheckObjCConversion(SourceRange(), RHSType, E, 9991 CCK_ImplicitConversion); 9992 LHS = ImpCastExprToType(E, RHSType, 9993 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9994 } 9995 else { 9996 Expr *E = RHS.get(); 9997 if (getLangOpts().ObjCAutoRefCount) 9998 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9999 /*Diagnose=*/true, 10000 /*DiagnoseCFAudited=*/false, Opc); 10001 RHS = ImpCastExprToType(E, LHSType, 10002 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10003 } 10004 return ResultTy; 10005 } 10006 if (LHSType->isObjCObjectPointerType() && 10007 RHSType->isObjCObjectPointerType()) { 10008 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10009 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10010 /*isError*/false); 10011 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10012 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10013 10014 if (LHSIsNull && !RHSIsNull) 10015 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10016 else 10017 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10018 return ResultTy; 10019 } 10020 } 10021 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10022 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10023 unsigned DiagID = 0; 10024 bool isError = false; 10025 if (LangOpts.DebuggerSupport) { 10026 // Under a debugger, allow the comparison of pointers to integers, 10027 // since users tend to want to compare addresses. 10028 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10029 (RHSIsNull && RHSType->isIntegerType())) { 10030 if (IsRelational) { 10031 isError = getLangOpts().CPlusPlus; 10032 DiagID = 10033 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10034 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10035 } 10036 } else if (getLangOpts().CPlusPlus) { 10037 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10038 isError = true; 10039 } else if (IsRelational) 10040 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10041 else 10042 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10043 10044 if (DiagID) { 10045 Diag(Loc, DiagID) 10046 << LHSType << RHSType << LHS.get()->getSourceRange() 10047 << RHS.get()->getSourceRange(); 10048 if (isError) 10049 return QualType(); 10050 } 10051 10052 if (LHSType->isIntegerType()) 10053 LHS = ImpCastExprToType(LHS.get(), RHSType, 10054 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10055 else 10056 RHS = ImpCastExprToType(RHS.get(), LHSType, 10057 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10058 return ResultTy; 10059 } 10060 10061 // Handle block pointers. 10062 if (!IsRelational && RHSIsNull 10063 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10064 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10065 return ResultTy; 10066 } 10067 if (!IsRelational && LHSIsNull 10068 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10069 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10070 return ResultTy; 10071 } 10072 10073 if (getLangOpts().OpenCLVersion >= 200) { 10074 if (LHSIsNull && RHSType->isQueueT()) { 10075 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10076 return ResultTy; 10077 } 10078 10079 if (LHSType->isQueueT() && RHSIsNull) { 10080 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10081 return ResultTy; 10082 } 10083 } 10084 10085 return InvalidOperands(Loc, LHS, RHS); 10086 } 10087 10088 // Return a signed ext_vector_type that is of identical size and number of 10089 // elements. For floating point vectors, return an integer type of identical 10090 // size and number of elements. In the non ext_vector_type case, search from 10091 // the largest type to the smallest type to avoid cases where long long == long, 10092 // where long gets picked over long long. 10093 QualType Sema::GetSignedVectorType(QualType V) { 10094 const VectorType *VTy = V->getAs<VectorType>(); 10095 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10096 10097 if (isa<ExtVectorType>(VTy)) { 10098 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10099 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10100 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10101 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10102 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10103 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10104 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10105 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10106 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10107 "Unhandled vector element size in vector compare"); 10108 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10109 } 10110 10111 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10112 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10113 VectorType::GenericVector); 10114 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10115 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10116 VectorType::GenericVector); 10117 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10118 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10119 VectorType::GenericVector); 10120 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10121 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10122 VectorType::GenericVector); 10123 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10124 "Unhandled vector element size in vector compare"); 10125 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10126 VectorType::GenericVector); 10127 } 10128 10129 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10130 /// operates on extended vector types. Instead of producing an IntTy result, 10131 /// like a scalar comparison, a vector comparison produces a vector of integer 10132 /// types. 10133 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10134 SourceLocation Loc, 10135 BinaryOperatorKind Opc) { 10136 // Check to make sure we're operating on vectors of the same type and width, 10137 // Allowing one side to be a scalar of element type. 10138 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10139 /*AllowBothBool*/true, 10140 /*AllowBoolConversions*/getLangOpts().ZVector); 10141 if (vType.isNull()) 10142 return vType; 10143 10144 QualType LHSType = LHS.get()->getType(); 10145 10146 // If AltiVec, the comparison results in a numeric type, i.e. 10147 // bool for C++, int for C 10148 if (getLangOpts().AltiVec && 10149 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10150 return Context.getLogicalOperationType(); 10151 10152 // For non-floating point types, check for self-comparisons of the form 10153 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10154 // often indicate logic errors in the program. 10155 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10156 10157 // Check for comparisons of floating point operands using != and ==. 10158 if (BinaryOperator::isEqualityOp(Opc) && 10159 LHSType->hasFloatingRepresentation()) { 10160 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10161 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10162 } 10163 10164 // Return a signed type for the vector. 10165 return GetSignedVectorType(vType); 10166 } 10167 10168 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10169 SourceLocation Loc) { 10170 // Ensure that either both operands are of the same vector type, or 10171 // one operand is of a vector type and the other is of its element type. 10172 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10173 /*AllowBothBool*/true, 10174 /*AllowBoolConversions*/false); 10175 if (vType.isNull()) 10176 return InvalidOperands(Loc, LHS, RHS); 10177 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10178 vType->hasFloatingRepresentation()) 10179 return InvalidOperands(Loc, LHS, RHS); 10180 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10181 // usage of the logical operators && and || with vectors in C. This 10182 // check could be notionally dropped. 10183 if (!getLangOpts().CPlusPlus && 10184 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10185 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10186 10187 return GetSignedVectorType(LHS.get()->getType()); 10188 } 10189 10190 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10191 SourceLocation Loc, 10192 BinaryOperatorKind Opc) { 10193 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10194 10195 bool IsCompAssign = 10196 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10197 10198 if (LHS.get()->getType()->isVectorType() || 10199 RHS.get()->getType()->isVectorType()) { 10200 if (LHS.get()->getType()->hasIntegerRepresentation() && 10201 RHS.get()->getType()->hasIntegerRepresentation()) 10202 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10203 /*AllowBothBool*/true, 10204 /*AllowBoolConversions*/getLangOpts().ZVector); 10205 return InvalidOperands(Loc, LHS, RHS); 10206 } 10207 10208 if (Opc == BO_And) 10209 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10210 10211 ExprResult LHSResult = LHS, RHSResult = RHS; 10212 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10213 IsCompAssign); 10214 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10215 return QualType(); 10216 LHS = LHSResult.get(); 10217 RHS = RHSResult.get(); 10218 10219 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10220 return compType; 10221 return InvalidOperands(Loc, LHS, RHS); 10222 } 10223 10224 // C99 6.5.[13,14] 10225 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10226 SourceLocation Loc, 10227 BinaryOperatorKind Opc) { 10228 // Check vector operands differently. 10229 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10230 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10231 10232 // Diagnose cases where the user write a logical and/or but probably meant a 10233 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10234 // is a constant. 10235 if (LHS.get()->getType()->isIntegerType() && 10236 !LHS.get()->getType()->isBooleanType() && 10237 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10238 // Don't warn in macros or template instantiations. 10239 !Loc.isMacroID() && !inTemplateInstantiation()) { 10240 // If the RHS can be constant folded, and if it constant folds to something 10241 // that isn't 0 or 1 (which indicate a potential logical operation that 10242 // happened to fold to true/false) then warn. 10243 // Parens on the RHS are ignored. 10244 llvm::APSInt Result; 10245 if (RHS.get()->EvaluateAsInt(Result, Context)) 10246 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10247 !RHS.get()->getExprLoc().isMacroID()) || 10248 (Result != 0 && Result != 1)) { 10249 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10250 << RHS.get()->getSourceRange() 10251 << (Opc == BO_LAnd ? "&&" : "||"); 10252 // Suggest replacing the logical operator with the bitwise version 10253 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10254 << (Opc == BO_LAnd ? "&" : "|") 10255 << FixItHint::CreateReplacement(SourceRange( 10256 Loc, getLocForEndOfToken(Loc)), 10257 Opc == BO_LAnd ? "&" : "|"); 10258 if (Opc == BO_LAnd) 10259 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10260 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10261 << FixItHint::CreateRemoval( 10262 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10263 RHS.get()->getLocEnd())); 10264 } 10265 } 10266 10267 if (!Context.getLangOpts().CPlusPlus) { 10268 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10269 // not operate on the built-in scalar and vector float types. 10270 if (Context.getLangOpts().OpenCL && 10271 Context.getLangOpts().OpenCLVersion < 120) { 10272 if (LHS.get()->getType()->isFloatingType() || 10273 RHS.get()->getType()->isFloatingType()) 10274 return InvalidOperands(Loc, LHS, RHS); 10275 } 10276 10277 LHS = UsualUnaryConversions(LHS.get()); 10278 if (LHS.isInvalid()) 10279 return QualType(); 10280 10281 RHS = UsualUnaryConversions(RHS.get()); 10282 if (RHS.isInvalid()) 10283 return QualType(); 10284 10285 if (!LHS.get()->getType()->isScalarType() || 10286 !RHS.get()->getType()->isScalarType()) 10287 return InvalidOperands(Loc, LHS, RHS); 10288 10289 return Context.IntTy; 10290 } 10291 10292 // The following is safe because we only use this method for 10293 // non-overloadable operands. 10294 10295 // C++ [expr.log.and]p1 10296 // C++ [expr.log.or]p1 10297 // The operands are both contextually converted to type bool. 10298 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10299 if (LHSRes.isInvalid()) 10300 return InvalidOperands(Loc, LHS, RHS); 10301 LHS = LHSRes; 10302 10303 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10304 if (RHSRes.isInvalid()) 10305 return InvalidOperands(Loc, LHS, RHS); 10306 RHS = RHSRes; 10307 10308 // C++ [expr.log.and]p2 10309 // C++ [expr.log.or]p2 10310 // The result is a bool. 10311 return Context.BoolTy; 10312 } 10313 10314 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10315 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10316 if (!ME) return false; 10317 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10318 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10319 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10320 if (!Base) return false; 10321 return Base->getMethodDecl() != nullptr; 10322 } 10323 10324 /// Is the given expression (which must be 'const') a reference to a 10325 /// variable which was originally non-const, but which has become 10326 /// 'const' due to being captured within a block? 10327 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10328 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10329 assert(E->isLValue() && E->getType().isConstQualified()); 10330 E = E->IgnoreParens(); 10331 10332 // Must be a reference to a declaration from an enclosing scope. 10333 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10334 if (!DRE) return NCCK_None; 10335 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10336 10337 // The declaration must be a variable which is not declared 'const'. 10338 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10339 if (!var) return NCCK_None; 10340 if (var->getType().isConstQualified()) return NCCK_None; 10341 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10342 10343 // Decide whether the first capture was for a block or a lambda. 10344 DeclContext *DC = S.CurContext, *Prev = nullptr; 10345 // Decide whether the first capture was for a block or a lambda. 10346 while (DC) { 10347 // For init-capture, it is possible that the variable belongs to the 10348 // template pattern of the current context. 10349 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10350 if (var->isInitCapture() && 10351 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10352 break; 10353 if (DC == var->getDeclContext()) 10354 break; 10355 Prev = DC; 10356 DC = DC->getParent(); 10357 } 10358 // Unless we have an init-capture, we've gone one step too far. 10359 if (!var->isInitCapture()) 10360 DC = Prev; 10361 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10362 } 10363 10364 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10365 Ty = Ty.getNonReferenceType(); 10366 if (IsDereference && Ty->isPointerType()) 10367 Ty = Ty->getPointeeType(); 10368 return !Ty.isConstQualified(); 10369 } 10370 10371 // Update err_typecheck_assign_const and note_typecheck_assign_const 10372 // when this enum is changed. 10373 enum { 10374 ConstFunction, 10375 ConstVariable, 10376 ConstMember, 10377 ConstMethod, 10378 NestedConstMember, 10379 ConstUnknown, // Keep as last element 10380 }; 10381 10382 /// Emit the "read-only variable not assignable" error and print notes to give 10383 /// more information about why the variable is not assignable, such as pointing 10384 /// to the declaration of a const variable, showing that a method is const, or 10385 /// that the function is returning a const reference. 10386 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10387 SourceLocation Loc) { 10388 SourceRange ExprRange = E->getSourceRange(); 10389 10390 // Only emit one error on the first const found. All other consts will emit 10391 // a note to the error. 10392 bool DiagnosticEmitted = false; 10393 10394 // Track if the current expression is the result of a dereference, and if the 10395 // next checked expression is the result of a dereference. 10396 bool IsDereference = false; 10397 bool NextIsDereference = false; 10398 10399 // Loop to process MemberExpr chains. 10400 while (true) { 10401 IsDereference = NextIsDereference; 10402 10403 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10404 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10405 NextIsDereference = ME->isArrow(); 10406 const ValueDecl *VD = ME->getMemberDecl(); 10407 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10408 // Mutable fields can be modified even if the class is const. 10409 if (Field->isMutable()) { 10410 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10411 break; 10412 } 10413 10414 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10415 if (!DiagnosticEmitted) { 10416 S.Diag(Loc, diag::err_typecheck_assign_const) 10417 << ExprRange << ConstMember << false /*static*/ << Field 10418 << Field->getType(); 10419 DiagnosticEmitted = true; 10420 } 10421 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10422 << ConstMember << false /*static*/ << Field << Field->getType() 10423 << Field->getSourceRange(); 10424 } 10425 E = ME->getBase(); 10426 continue; 10427 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10428 if (VDecl->getType().isConstQualified()) { 10429 if (!DiagnosticEmitted) { 10430 S.Diag(Loc, diag::err_typecheck_assign_const) 10431 << ExprRange << ConstMember << true /*static*/ << VDecl 10432 << VDecl->getType(); 10433 DiagnosticEmitted = true; 10434 } 10435 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10436 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10437 << VDecl->getSourceRange(); 10438 } 10439 // Static fields do not inherit constness from parents. 10440 break; 10441 } 10442 break; // End MemberExpr 10443 } else if (const ArraySubscriptExpr *ASE = 10444 dyn_cast<ArraySubscriptExpr>(E)) { 10445 E = ASE->getBase()->IgnoreParenImpCasts(); 10446 continue; 10447 } else if (const ExtVectorElementExpr *EVE = 10448 dyn_cast<ExtVectorElementExpr>(E)) { 10449 E = EVE->getBase()->IgnoreParenImpCasts(); 10450 continue; 10451 } 10452 break; 10453 } 10454 10455 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10456 // Function calls 10457 const FunctionDecl *FD = CE->getDirectCallee(); 10458 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10459 if (!DiagnosticEmitted) { 10460 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10461 << ConstFunction << FD; 10462 DiagnosticEmitted = true; 10463 } 10464 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10465 diag::note_typecheck_assign_const) 10466 << ConstFunction << FD << FD->getReturnType() 10467 << FD->getReturnTypeSourceRange(); 10468 } 10469 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10470 // Point to variable declaration. 10471 if (const ValueDecl *VD = DRE->getDecl()) { 10472 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10473 if (!DiagnosticEmitted) { 10474 S.Diag(Loc, diag::err_typecheck_assign_const) 10475 << ExprRange << ConstVariable << VD << VD->getType(); 10476 DiagnosticEmitted = true; 10477 } 10478 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10479 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10480 } 10481 } 10482 } else if (isa<CXXThisExpr>(E)) { 10483 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10484 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10485 if (MD->isConst()) { 10486 if (!DiagnosticEmitted) { 10487 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10488 << ConstMethod << MD; 10489 DiagnosticEmitted = true; 10490 } 10491 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10492 << ConstMethod << MD << MD->getSourceRange(); 10493 } 10494 } 10495 } 10496 } 10497 10498 if (DiagnosticEmitted) 10499 return; 10500 10501 // Can't determine a more specific message, so display the generic error. 10502 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10503 } 10504 10505 enum OriginalExprKind { 10506 OEK_Variable, 10507 OEK_Member, 10508 OEK_LValue 10509 }; 10510 10511 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10512 const RecordType *Ty, 10513 SourceLocation Loc, SourceRange Range, 10514 OriginalExprKind OEK, 10515 bool &DiagnosticEmitted, 10516 bool IsNested = false) { 10517 // We walk the record hierarchy breadth-first to ensure that we print 10518 // diagnostics in field nesting order. 10519 // First, check every field for constness. 10520 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10521 if (Field->getType().isConstQualified()) { 10522 if (!DiagnosticEmitted) { 10523 S.Diag(Loc, diag::err_typecheck_assign_const) 10524 << Range << NestedConstMember << OEK << VD 10525 << IsNested << Field; 10526 DiagnosticEmitted = true; 10527 } 10528 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10529 << NestedConstMember << IsNested << Field 10530 << Field->getType() << Field->getSourceRange(); 10531 } 10532 } 10533 // Then, recurse. 10534 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10535 QualType FTy = Field->getType(); 10536 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10537 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10538 OEK, DiagnosticEmitted, true); 10539 } 10540 } 10541 10542 /// Emit an error for the case where a record we are trying to assign to has a 10543 /// const-qualified field somewhere in its hierarchy. 10544 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10545 SourceLocation Loc) { 10546 QualType Ty = E->getType(); 10547 assert(Ty->isRecordType() && "lvalue was not record?"); 10548 SourceRange Range = E->getSourceRange(); 10549 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10550 bool DiagEmitted = false; 10551 10552 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10553 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10554 Range, OEK_Member, DiagEmitted); 10555 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10556 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10557 Range, OEK_Variable, DiagEmitted); 10558 else 10559 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10560 Range, OEK_LValue, DiagEmitted); 10561 if (!DiagEmitted) 10562 DiagnoseConstAssignment(S, E, Loc); 10563 } 10564 10565 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10566 /// emit an error and return true. If so, return false. 10567 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10568 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10569 10570 S.CheckShadowingDeclModification(E, Loc); 10571 10572 SourceLocation OrigLoc = Loc; 10573 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10574 &Loc); 10575 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10576 IsLV = Expr::MLV_InvalidMessageExpression; 10577 if (IsLV == Expr::MLV_Valid) 10578 return false; 10579 10580 unsigned DiagID = 0; 10581 bool NeedType = false; 10582 switch (IsLV) { // C99 6.5.16p2 10583 case Expr::MLV_ConstQualified: 10584 // Use a specialized diagnostic when we're assigning to an object 10585 // from an enclosing function or block. 10586 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10587 if (NCCK == NCCK_Block) 10588 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10589 else 10590 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10591 break; 10592 } 10593 10594 // In ARC, use some specialized diagnostics for occasions where we 10595 // infer 'const'. These are always pseudo-strong variables. 10596 if (S.getLangOpts().ObjCAutoRefCount) { 10597 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10598 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10599 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10600 10601 // Use the normal diagnostic if it's pseudo-__strong but the 10602 // user actually wrote 'const'. 10603 if (var->isARCPseudoStrong() && 10604 (!var->getTypeSourceInfo() || 10605 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10606 // There are two pseudo-strong cases: 10607 // - self 10608 ObjCMethodDecl *method = S.getCurMethodDecl(); 10609 if (method && var == method->getSelfDecl()) 10610 DiagID = method->isClassMethod() 10611 ? diag::err_typecheck_arc_assign_self_class_method 10612 : diag::err_typecheck_arc_assign_self; 10613 10614 // - fast enumeration variables 10615 else 10616 DiagID = diag::err_typecheck_arr_assign_enumeration; 10617 10618 SourceRange Assign; 10619 if (Loc != OrigLoc) 10620 Assign = SourceRange(OrigLoc, OrigLoc); 10621 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10622 // We need to preserve the AST regardless, so migration tool 10623 // can do its job. 10624 return false; 10625 } 10626 } 10627 } 10628 10629 // If none of the special cases above are triggered, then this is a 10630 // simple const assignment. 10631 if (DiagID == 0) { 10632 DiagnoseConstAssignment(S, E, Loc); 10633 return true; 10634 } 10635 10636 break; 10637 case Expr::MLV_ConstAddrSpace: 10638 DiagnoseConstAssignment(S, E, Loc); 10639 return true; 10640 case Expr::MLV_ConstQualifiedField: 10641 DiagnoseRecursiveConstFields(S, E, Loc); 10642 return true; 10643 case Expr::MLV_ArrayType: 10644 case Expr::MLV_ArrayTemporary: 10645 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10646 NeedType = true; 10647 break; 10648 case Expr::MLV_NotObjectType: 10649 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10650 NeedType = true; 10651 break; 10652 case Expr::MLV_LValueCast: 10653 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10654 break; 10655 case Expr::MLV_Valid: 10656 llvm_unreachable("did not take early return for MLV_Valid"); 10657 case Expr::MLV_InvalidExpression: 10658 case Expr::MLV_MemberFunction: 10659 case Expr::MLV_ClassTemporary: 10660 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10661 break; 10662 case Expr::MLV_IncompleteType: 10663 case Expr::MLV_IncompleteVoidType: 10664 return S.RequireCompleteType(Loc, E->getType(), 10665 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10666 case Expr::MLV_DuplicateVectorComponents: 10667 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10668 break; 10669 case Expr::MLV_NoSetterProperty: 10670 llvm_unreachable("readonly properties should be processed differently"); 10671 case Expr::MLV_InvalidMessageExpression: 10672 DiagID = diag::err_readonly_message_assignment; 10673 break; 10674 case Expr::MLV_SubObjCPropertySetting: 10675 DiagID = diag::err_no_subobject_property_setting; 10676 break; 10677 } 10678 10679 SourceRange Assign; 10680 if (Loc != OrigLoc) 10681 Assign = SourceRange(OrigLoc, OrigLoc); 10682 if (NeedType) 10683 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10684 else 10685 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10686 return true; 10687 } 10688 10689 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10690 SourceLocation Loc, 10691 Sema &Sema) { 10692 // C / C++ fields 10693 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10694 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10695 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10696 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10697 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10698 } 10699 10700 // Objective-C instance variables 10701 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10702 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10703 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10704 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10705 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10706 if (RL && RR && RL->getDecl() == RR->getDecl()) 10707 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10708 } 10709 } 10710 10711 // C99 6.5.16.1 10712 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10713 SourceLocation Loc, 10714 QualType CompoundType) { 10715 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10716 10717 // Verify that LHS is a modifiable lvalue, and emit error if not. 10718 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10719 return QualType(); 10720 10721 QualType LHSType = LHSExpr->getType(); 10722 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10723 CompoundType; 10724 // OpenCL v1.2 s6.1.1.1 p2: 10725 // The half data type can only be used to declare a pointer to a buffer that 10726 // contains half values 10727 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10728 LHSType->isHalfType()) { 10729 Diag(Loc, diag::err_opencl_half_load_store) << 1 10730 << LHSType.getUnqualifiedType(); 10731 return QualType(); 10732 } 10733 10734 AssignConvertType ConvTy; 10735 if (CompoundType.isNull()) { 10736 Expr *RHSCheck = RHS.get(); 10737 10738 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10739 10740 QualType LHSTy(LHSType); 10741 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10742 if (RHS.isInvalid()) 10743 return QualType(); 10744 // Special case of NSObject attributes on c-style pointer types. 10745 if (ConvTy == IncompatiblePointer && 10746 ((Context.isObjCNSObjectType(LHSType) && 10747 RHSType->isObjCObjectPointerType()) || 10748 (Context.isObjCNSObjectType(RHSType) && 10749 LHSType->isObjCObjectPointerType()))) 10750 ConvTy = Compatible; 10751 10752 if (ConvTy == Compatible && 10753 LHSType->isObjCObjectType()) 10754 Diag(Loc, diag::err_objc_object_assignment) 10755 << LHSType; 10756 10757 // If the RHS is a unary plus or minus, check to see if they = and + are 10758 // right next to each other. If so, the user may have typo'd "x =+ 4" 10759 // instead of "x += 4". 10760 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10761 RHSCheck = ICE->getSubExpr(); 10762 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10763 if ((UO->getOpcode() == UO_Plus || 10764 UO->getOpcode() == UO_Minus) && 10765 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10766 // Only if the two operators are exactly adjacent. 10767 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10768 // And there is a space or other character before the subexpr of the 10769 // unary +/-. We don't want to warn on "x=-1". 10770 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10771 UO->getSubExpr()->getLocStart().isFileID()) { 10772 Diag(Loc, diag::warn_not_compound_assign) 10773 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10774 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10775 } 10776 } 10777 10778 if (ConvTy == Compatible) { 10779 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10780 // Warn about retain cycles where a block captures the LHS, but 10781 // not if the LHS is a simple variable into which the block is 10782 // being stored...unless that variable can be captured by reference! 10783 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10784 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10785 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10786 checkRetainCycles(LHSExpr, RHS.get()); 10787 } 10788 10789 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10790 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10791 // It is safe to assign a weak reference into a strong variable. 10792 // Although this code can still have problems: 10793 // id x = self.weakProp; 10794 // id y = self.weakProp; 10795 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10796 // paths through the function. This should be revisited if 10797 // -Wrepeated-use-of-weak is made flow-sensitive. 10798 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10799 // variable, which will be valid for the current autorelease scope. 10800 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10801 RHS.get()->getLocStart())) 10802 getCurFunction()->markSafeWeakUse(RHS.get()); 10803 10804 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10805 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10806 } 10807 } 10808 } else { 10809 // Compound assignment "x += y" 10810 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10811 } 10812 10813 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10814 RHS.get(), AA_Assigning)) 10815 return QualType(); 10816 10817 CheckForNullPointerDereference(*this, LHSExpr); 10818 10819 // C99 6.5.16p3: The type of an assignment expression is the type of the 10820 // left operand unless the left operand has qualified type, in which case 10821 // it is the unqualified version of the type of the left operand. 10822 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10823 // is converted to the type of the assignment expression (above). 10824 // C++ 5.17p1: the type of the assignment expression is that of its left 10825 // operand. 10826 return (getLangOpts().CPlusPlus 10827 ? LHSType : LHSType.getUnqualifiedType()); 10828 } 10829 10830 // Only ignore explicit casts to void. 10831 static bool IgnoreCommaOperand(const Expr *E) { 10832 E = E->IgnoreParens(); 10833 10834 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10835 if (CE->getCastKind() == CK_ToVoid) { 10836 return true; 10837 } 10838 } 10839 10840 return false; 10841 } 10842 10843 // Look for instances where it is likely the comma operator is confused with 10844 // another operator. There is a whitelist of acceptable expressions for the 10845 // left hand side of the comma operator, otherwise emit a warning. 10846 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10847 // No warnings in macros 10848 if (Loc.isMacroID()) 10849 return; 10850 10851 // Don't warn in template instantiations. 10852 if (inTemplateInstantiation()) 10853 return; 10854 10855 // Scope isn't fine-grained enough to whitelist the specific cases, so 10856 // instead, skip more than needed, then call back into here with the 10857 // CommaVisitor in SemaStmt.cpp. 10858 // The whitelisted locations are the initialization and increment portions 10859 // of a for loop. The additional checks are on the condition of 10860 // if statements, do/while loops, and for loops. 10861 const unsigned ForIncrementFlags = 10862 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10863 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10864 const unsigned ScopeFlags = getCurScope()->getFlags(); 10865 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10866 (ScopeFlags & ForInitFlags) == ForInitFlags) 10867 return; 10868 10869 // If there are multiple comma operators used together, get the RHS of the 10870 // of the comma operator as the LHS. 10871 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10872 if (BO->getOpcode() != BO_Comma) 10873 break; 10874 LHS = BO->getRHS(); 10875 } 10876 10877 // Only allow some expressions on LHS to not warn. 10878 if (IgnoreCommaOperand(LHS)) 10879 return; 10880 10881 Diag(Loc, diag::warn_comma_operator); 10882 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10883 << LHS->getSourceRange() 10884 << FixItHint::CreateInsertion(LHS->getLocStart(), 10885 LangOpts.CPlusPlus ? "static_cast<void>(" 10886 : "(void)(") 10887 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10888 ")"); 10889 } 10890 10891 // C99 6.5.17 10892 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10893 SourceLocation Loc) { 10894 LHS = S.CheckPlaceholderExpr(LHS.get()); 10895 RHS = S.CheckPlaceholderExpr(RHS.get()); 10896 if (LHS.isInvalid() || RHS.isInvalid()) 10897 return QualType(); 10898 10899 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10900 // operands, but not unary promotions. 10901 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10902 10903 // So we treat the LHS as a ignored value, and in C++ we allow the 10904 // containing site to determine what should be done with the RHS. 10905 LHS = S.IgnoredValueConversions(LHS.get()); 10906 if (LHS.isInvalid()) 10907 return QualType(); 10908 10909 S.DiagnoseUnusedExprResult(LHS.get()); 10910 10911 if (!S.getLangOpts().CPlusPlus) { 10912 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10913 if (RHS.isInvalid()) 10914 return QualType(); 10915 if (!RHS.get()->getType()->isVoidType()) 10916 S.RequireCompleteType(Loc, RHS.get()->getType(), 10917 diag::err_incomplete_type); 10918 } 10919 10920 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10921 S.DiagnoseCommaOperator(LHS.get(), Loc); 10922 10923 return RHS.get()->getType(); 10924 } 10925 10926 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10927 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10928 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10929 ExprValueKind &VK, 10930 ExprObjectKind &OK, 10931 SourceLocation OpLoc, 10932 bool IsInc, bool IsPrefix) { 10933 if (Op->isTypeDependent()) 10934 return S.Context.DependentTy; 10935 10936 QualType ResType = Op->getType(); 10937 // Atomic types can be used for increment / decrement where the non-atomic 10938 // versions can, so ignore the _Atomic() specifier for the purpose of 10939 // checking. 10940 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10941 ResType = ResAtomicType->getValueType(); 10942 10943 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10944 10945 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10946 // Decrement of bool is not allowed. 10947 if (!IsInc) { 10948 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10949 return QualType(); 10950 } 10951 // Increment of bool sets it to true, but is deprecated. 10952 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 10953 : diag::warn_increment_bool) 10954 << Op->getSourceRange(); 10955 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10956 // Error on enum increments and decrements in C++ mode 10957 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10958 return QualType(); 10959 } else if (ResType->isRealType()) { 10960 // OK! 10961 } else if (ResType->isPointerType()) { 10962 // C99 6.5.2.4p2, 6.5.6p2 10963 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10964 return QualType(); 10965 } else if (ResType->isObjCObjectPointerType()) { 10966 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10967 // Otherwise, we just need a complete type. 10968 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10969 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10970 return QualType(); 10971 } else if (ResType->isAnyComplexType()) { 10972 // C99 does not support ++/-- on complex types, we allow as an extension. 10973 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10974 << ResType << Op->getSourceRange(); 10975 } else if (ResType->isPlaceholderType()) { 10976 ExprResult PR = S.CheckPlaceholderExpr(Op); 10977 if (PR.isInvalid()) return QualType(); 10978 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10979 IsInc, IsPrefix); 10980 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10981 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10982 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10983 (ResType->getAs<VectorType>()->getVectorKind() != 10984 VectorType::AltiVecBool)) { 10985 // The z vector extensions allow ++ and -- for non-bool vectors. 10986 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10987 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10988 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10989 } else { 10990 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10991 << ResType << int(IsInc) << Op->getSourceRange(); 10992 return QualType(); 10993 } 10994 // At this point, we know we have a real, complex or pointer type. 10995 // Now make sure the operand is a modifiable lvalue. 10996 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10997 return QualType(); 10998 // In C++, a prefix increment is the same type as the operand. Otherwise 10999 // (in C or with postfix), the increment is the unqualified type of the 11000 // operand. 11001 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11002 VK = VK_LValue; 11003 OK = Op->getObjectKind(); 11004 return ResType; 11005 } else { 11006 VK = VK_RValue; 11007 return ResType.getUnqualifiedType(); 11008 } 11009 } 11010 11011 11012 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11013 /// This routine allows us to typecheck complex/recursive expressions 11014 /// where the declaration is needed for type checking. We only need to 11015 /// handle cases when the expression references a function designator 11016 /// or is an lvalue. Here are some examples: 11017 /// - &(x) => x 11018 /// - &*****f => f for f a function designator. 11019 /// - &s.xx => s 11020 /// - &s.zz[1].yy -> s, if zz is an array 11021 /// - *(x + 1) -> x, if x is an array 11022 /// - &"123"[2] -> 0 11023 /// - & __real__ x -> x 11024 static ValueDecl *getPrimaryDecl(Expr *E) { 11025 switch (E->getStmtClass()) { 11026 case Stmt::DeclRefExprClass: 11027 return cast<DeclRefExpr>(E)->getDecl(); 11028 case Stmt::MemberExprClass: 11029 // If this is an arrow operator, the address is an offset from 11030 // the base's value, so the object the base refers to is 11031 // irrelevant. 11032 if (cast<MemberExpr>(E)->isArrow()) 11033 return nullptr; 11034 // Otherwise, the expression refers to a part of the base 11035 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11036 case Stmt::ArraySubscriptExprClass: { 11037 // FIXME: This code shouldn't be necessary! We should catch the implicit 11038 // promotion of register arrays earlier. 11039 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11040 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11041 if (ICE->getSubExpr()->getType()->isArrayType()) 11042 return getPrimaryDecl(ICE->getSubExpr()); 11043 } 11044 return nullptr; 11045 } 11046 case Stmt::UnaryOperatorClass: { 11047 UnaryOperator *UO = cast<UnaryOperator>(E); 11048 11049 switch(UO->getOpcode()) { 11050 case UO_Real: 11051 case UO_Imag: 11052 case UO_Extension: 11053 return getPrimaryDecl(UO->getSubExpr()); 11054 default: 11055 return nullptr; 11056 } 11057 } 11058 case Stmt::ParenExprClass: 11059 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11060 case Stmt::ImplicitCastExprClass: 11061 // If the result of an implicit cast is an l-value, we care about 11062 // the sub-expression; otherwise, the result here doesn't matter. 11063 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11064 default: 11065 return nullptr; 11066 } 11067 } 11068 11069 namespace { 11070 enum { 11071 AO_Bit_Field = 0, 11072 AO_Vector_Element = 1, 11073 AO_Property_Expansion = 2, 11074 AO_Register_Variable = 3, 11075 AO_No_Error = 4 11076 }; 11077 } 11078 /// \brief Diagnose invalid operand for address of operations. 11079 /// 11080 /// \param Type The type of operand which cannot have its address taken. 11081 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11082 Expr *E, unsigned Type) { 11083 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11084 } 11085 11086 /// CheckAddressOfOperand - The operand of & must be either a function 11087 /// designator or an lvalue designating an object. If it is an lvalue, the 11088 /// object cannot be declared with storage class register or be a bit field. 11089 /// Note: The usual conversions are *not* applied to the operand of the & 11090 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11091 /// In C++, the operand might be an overloaded function name, in which case 11092 /// we allow the '&' but retain the overloaded-function type. 11093 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11094 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11095 if (PTy->getKind() == BuiltinType::Overload) { 11096 Expr *E = OrigOp.get()->IgnoreParens(); 11097 if (!isa<OverloadExpr>(E)) { 11098 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11099 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11100 << OrigOp.get()->getSourceRange(); 11101 return QualType(); 11102 } 11103 11104 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11105 if (isa<UnresolvedMemberExpr>(Ovl)) 11106 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11107 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11108 << OrigOp.get()->getSourceRange(); 11109 return QualType(); 11110 } 11111 11112 return Context.OverloadTy; 11113 } 11114 11115 if (PTy->getKind() == BuiltinType::UnknownAny) 11116 return Context.UnknownAnyTy; 11117 11118 if (PTy->getKind() == BuiltinType::BoundMember) { 11119 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11120 << OrigOp.get()->getSourceRange(); 11121 return QualType(); 11122 } 11123 11124 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11125 if (OrigOp.isInvalid()) return QualType(); 11126 } 11127 11128 if (OrigOp.get()->isTypeDependent()) 11129 return Context.DependentTy; 11130 11131 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11132 11133 // Make sure to ignore parentheses in subsequent checks 11134 Expr *op = OrigOp.get()->IgnoreParens(); 11135 11136 // In OpenCL captures for blocks called as lambda functions 11137 // are located in the private address space. Blocks used in 11138 // enqueue_kernel can be located in a different address space 11139 // depending on a vendor implementation. Thus preventing 11140 // taking an address of the capture to avoid invalid AS casts. 11141 if (LangOpts.OpenCL) { 11142 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11143 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11144 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11145 return QualType(); 11146 } 11147 } 11148 11149 if (getLangOpts().C99) { 11150 // Implement C99-only parts of addressof rules. 11151 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11152 if (uOp->getOpcode() == UO_Deref) 11153 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11154 // (assuming the deref expression is valid). 11155 return uOp->getSubExpr()->getType(); 11156 } 11157 // Technically, there should be a check for array subscript 11158 // expressions here, but the result of one is always an lvalue anyway. 11159 } 11160 ValueDecl *dcl = getPrimaryDecl(op); 11161 11162 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11163 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11164 op->getLocStart())) 11165 return QualType(); 11166 11167 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11168 unsigned AddressOfError = AO_No_Error; 11169 11170 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11171 bool sfinae = (bool)isSFINAEContext(); 11172 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11173 : diag::ext_typecheck_addrof_temporary) 11174 << op->getType() << op->getSourceRange(); 11175 if (sfinae) 11176 return QualType(); 11177 // Materialize the temporary as an lvalue so that we can take its address. 11178 OrigOp = op = 11179 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11180 } else if (isa<ObjCSelectorExpr>(op)) { 11181 return Context.getPointerType(op->getType()); 11182 } else if (lval == Expr::LV_MemberFunction) { 11183 // If it's an instance method, make a member pointer. 11184 // The expression must have exactly the form &A::foo. 11185 11186 // If the underlying expression isn't a decl ref, give up. 11187 if (!isa<DeclRefExpr>(op)) { 11188 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11189 << OrigOp.get()->getSourceRange(); 11190 return QualType(); 11191 } 11192 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11193 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11194 11195 // The id-expression was parenthesized. 11196 if (OrigOp.get() != DRE) { 11197 Diag(OpLoc, diag::err_parens_pointer_member_function) 11198 << OrigOp.get()->getSourceRange(); 11199 11200 // The method was named without a qualifier. 11201 } else if (!DRE->getQualifier()) { 11202 if (MD->getParent()->getName().empty()) 11203 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11204 << op->getSourceRange(); 11205 else { 11206 SmallString<32> Str; 11207 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11208 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11209 << op->getSourceRange() 11210 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11211 } 11212 } 11213 11214 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11215 if (isa<CXXDestructorDecl>(MD)) 11216 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11217 11218 QualType MPTy = Context.getMemberPointerType( 11219 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11220 // Under the MS ABI, lock down the inheritance model now. 11221 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11222 (void)isCompleteType(OpLoc, MPTy); 11223 return MPTy; 11224 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11225 // C99 6.5.3.2p1 11226 // The operand must be either an l-value or a function designator 11227 if (!op->getType()->isFunctionType()) { 11228 // Use a special diagnostic for loads from property references. 11229 if (isa<PseudoObjectExpr>(op)) { 11230 AddressOfError = AO_Property_Expansion; 11231 } else { 11232 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11233 << op->getType() << op->getSourceRange(); 11234 return QualType(); 11235 } 11236 } 11237 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11238 // The operand cannot be a bit-field 11239 AddressOfError = AO_Bit_Field; 11240 } else if (op->getObjectKind() == OK_VectorComponent) { 11241 // The operand cannot be an element of a vector 11242 AddressOfError = AO_Vector_Element; 11243 } else if (dcl) { // C99 6.5.3.2p1 11244 // We have an lvalue with a decl. Make sure the decl is not declared 11245 // with the register storage-class specifier. 11246 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11247 // in C++ it is not error to take address of a register 11248 // variable (c++03 7.1.1P3) 11249 if (vd->getStorageClass() == SC_Register && 11250 !getLangOpts().CPlusPlus) { 11251 AddressOfError = AO_Register_Variable; 11252 } 11253 } else if (isa<MSPropertyDecl>(dcl)) { 11254 AddressOfError = AO_Property_Expansion; 11255 } else if (isa<FunctionTemplateDecl>(dcl)) { 11256 return Context.OverloadTy; 11257 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11258 // Okay: we can take the address of a field. 11259 // Could be a pointer to member, though, if there is an explicit 11260 // scope qualifier for the class. 11261 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11262 DeclContext *Ctx = dcl->getDeclContext(); 11263 if (Ctx && Ctx->isRecord()) { 11264 if (dcl->getType()->isReferenceType()) { 11265 Diag(OpLoc, 11266 diag::err_cannot_form_pointer_to_member_of_reference_type) 11267 << dcl->getDeclName() << dcl->getType(); 11268 return QualType(); 11269 } 11270 11271 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11272 Ctx = Ctx->getParent(); 11273 11274 QualType MPTy = Context.getMemberPointerType( 11275 op->getType(), 11276 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11277 // Under the MS ABI, lock down the inheritance model now. 11278 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11279 (void)isCompleteType(OpLoc, MPTy); 11280 return MPTy; 11281 } 11282 } 11283 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11284 !isa<BindingDecl>(dcl)) 11285 llvm_unreachable("Unknown/unexpected decl type"); 11286 } 11287 11288 if (AddressOfError != AO_No_Error) { 11289 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11290 return QualType(); 11291 } 11292 11293 if (lval == Expr::LV_IncompleteVoidType) { 11294 // Taking the address of a void variable is technically illegal, but we 11295 // allow it in cases which are otherwise valid. 11296 // Example: "extern void x; void* y = &x;". 11297 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11298 } 11299 11300 // If the operand has type "type", the result has type "pointer to type". 11301 if (op->getType()->isObjCObjectType()) 11302 return Context.getObjCObjectPointerType(op->getType()); 11303 11304 CheckAddressOfPackedMember(op); 11305 11306 return Context.getPointerType(op->getType()); 11307 } 11308 11309 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11310 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11311 if (!DRE) 11312 return; 11313 const Decl *D = DRE->getDecl(); 11314 if (!D) 11315 return; 11316 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11317 if (!Param) 11318 return; 11319 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11320 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11321 return; 11322 if (FunctionScopeInfo *FD = S.getCurFunction()) 11323 if (!FD->ModifiedNonNullParams.count(Param)) 11324 FD->ModifiedNonNullParams.insert(Param); 11325 } 11326 11327 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11328 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11329 SourceLocation OpLoc) { 11330 if (Op->isTypeDependent()) 11331 return S.Context.DependentTy; 11332 11333 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11334 if (ConvResult.isInvalid()) 11335 return QualType(); 11336 Op = ConvResult.get(); 11337 QualType OpTy = Op->getType(); 11338 QualType Result; 11339 11340 if (isa<CXXReinterpretCastExpr>(Op)) { 11341 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11342 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11343 Op->getSourceRange()); 11344 } 11345 11346 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11347 { 11348 Result = PT->getPointeeType(); 11349 } 11350 else if (const ObjCObjectPointerType *OPT = 11351 OpTy->getAs<ObjCObjectPointerType>()) 11352 Result = OPT->getPointeeType(); 11353 else { 11354 ExprResult PR = S.CheckPlaceholderExpr(Op); 11355 if (PR.isInvalid()) return QualType(); 11356 if (PR.get() != Op) 11357 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11358 } 11359 11360 if (Result.isNull()) { 11361 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11362 << OpTy << Op->getSourceRange(); 11363 return QualType(); 11364 } 11365 11366 // Note that per both C89 and C99, indirection is always legal, even if Result 11367 // is an incomplete type or void. It would be possible to warn about 11368 // dereferencing a void pointer, but it's completely well-defined, and such a 11369 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11370 // for pointers to 'void' but is fine for any other pointer type: 11371 // 11372 // C++ [expr.unary.op]p1: 11373 // [...] the expression to which [the unary * operator] is applied shall 11374 // be a pointer to an object type, or a pointer to a function type 11375 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11376 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11377 << OpTy << Op->getSourceRange(); 11378 11379 // Dereferences are usually l-values... 11380 VK = VK_LValue; 11381 11382 // ...except that certain expressions are never l-values in C. 11383 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11384 VK = VK_RValue; 11385 11386 return Result; 11387 } 11388 11389 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11390 BinaryOperatorKind Opc; 11391 switch (Kind) { 11392 default: llvm_unreachable("Unknown binop!"); 11393 case tok::periodstar: Opc = BO_PtrMemD; break; 11394 case tok::arrowstar: Opc = BO_PtrMemI; break; 11395 case tok::star: Opc = BO_Mul; break; 11396 case tok::slash: Opc = BO_Div; break; 11397 case tok::percent: Opc = BO_Rem; break; 11398 case tok::plus: Opc = BO_Add; break; 11399 case tok::minus: Opc = BO_Sub; break; 11400 case tok::lessless: Opc = BO_Shl; break; 11401 case tok::greatergreater: Opc = BO_Shr; break; 11402 case tok::lessequal: Opc = BO_LE; break; 11403 case tok::less: Opc = BO_LT; break; 11404 case tok::greaterequal: Opc = BO_GE; break; 11405 case tok::greater: Opc = BO_GT; break; 11406 case tok::exclaimequal: Opc = BO_NE; break; 11407 case tok::equalequal: Opc = BO_EQ; break; 11408 case tok::spaceship: Opc = BO_Cmp; break; 11409 case tok::amp: Opc = BO_And; break; 11410 case tok::caret: Opc = BO_Xor; break; 11411 case tok::pipe: Opc = BO_Or; break; 11412 case tok::ampamp: Opc = BO_LAnd; break; 11413 case tok::pipepipe: Opc = BO_LOr; break; 11414 case tok::equal: Opc = BO_Assign; break; 11415 case tok::starequal: Opc = BO_MulAssign; break; 11416 case tok::slashequal: Opc = BO_DivAssign; break; 11417 case tok::percentequal: Opc = BO_RemAssign; break; 11418 case tok::plusequal: Opc = BO_AddAssign; break; 11419 case tok::minusequal: Opc = BO_SubAssign; break; 11420 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11421 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11422 case tok::ampequal: Opc = BO_AndAssign; break; 11423 case tok::caretequal: Opc = BO_XorAssign; break; 11424 case tok::pipeequal: Opc = BO_OrAssign; break; 11425 case tok::comma: Opc = BO_Comma; break; 11426 } 11427 return Opc; 11428 } 11429 11430 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11431 tok::TokenKind Kind) { 11432 UnaryOperatorKind Opc; 11433 switch (Kind) { 11434 default: llvm_unreachable("Unknown unary op!"); 11435 case tok::plusplus: Opc = UO_PreInc; break; 11436 case tok::minusminus: Opc = UO_PreDec; break; 11437 case tok::amp: Opc = UO_AddrOf; break; 11438 case tok::star: Opc = UO_Deref; break; 11439 case tok::plus: Opc = UO_Plus; break; 11440 case tok::minus: Opc = UO_Minus; break; 11441 case tok::tilde: Opc = UO_Not; break; 11442 case tok::exclaim: Opc = UO_LNot; break; 11443 case tok::kw___real: Opc = UO_Real; break; 11444 case tok::kw___imag: Opc = UO_Imag; break; 11445 case tok::kw___extension__: Opc = UO_Extension; break; 11446 } 11447 return Opc; 11448 } 11449 11450 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11451 /// This warning is only emitted for builtin assignment operations. It is also 11452 /// suppressed in the event of macro expansions. 11453 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11454 SourceLocation OpLoc) { 11455 if (S.inTemplateInstantiation()) 11456 return; 11457 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11458 return; 11459 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11460 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11461 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11462 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11463 if (!LHSDeclRef || !RHSDeclRef || 11464 LHSDeclRef->getLocation().isMacroID() || 11465 RHSDeclRef->getLocation().isMacroID()) 11466 return; 11467 const ValueDecl *LHSDecl = 11468 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11469 const ValueDecl *RHSDecl = 11470 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11471 if (LHSDecl != RHSDecl) 11472 return; 11473 if (LHSDecl->getType().isVolatileQualified()) 11474 return; 11475 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11476 if (RefTy->getPointeeType().isVolatileQualified()) 11477 return; 11478 11479 S.Diag(OpLoc, diag::warn_self_assignment) 11480 << LHSDeclRef->getType() 11481 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11482 } 11483 11484 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11485 /// is usually indicative of introspection within the Objective-C pointer. 11486 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11487 SourceLocation OpLoc) { 11488 if (!S.getLangOpts().ObjC1) 11489 return; 11490 11491 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11492 const Expr *LHS = L.get(); 11493 const Expr *RHS = R.get(); 11494 11495 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11496 ObjCPointerExpr = LHS; 11497 OtherExpr = RHS; 11498 } 11499 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11500 ObjCPointerExpr = RHS; 11501 OtherExpr = LHS; 11502 } 11503 11504 // This warning is deliberately made very specific to reduce false 11505 // positives with logic that uses '&' for hashing. This logic mainly 11506 // looks for code trying to introspect into tagged pointers, which 11507 // code should generally never do. 11508 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11509 unsigned Diag = diag::warn_objc_pointer_masking; 11510 // Determine if we are introspecting the result of performSelectorXXX. 11511 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11512 // Special case messages to -performSelector and friends, which 11513 // can return non-pointer values boxed in a pointer value. 11514 // Some clients may wish to silence warnings in this subcase. 11515 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11516 Selector S = ME->getSelector(); 11517 StringRef SelArg0 = S.getNameForSlot(0); 11518 if (SelArg0.startswith("performSelector")) 11519 Diag = diag::warn_objc_pointer_masking_performSelector; 11520 } 11521 11522 S.Diag(OpLoc, Diag) 11523 << ObjCPointerExpr->getSourceRange(); 11524 } 11525 } 11526 11527 static NamedDecl *getDeclFromExpr(Expr *E) { 11528 if (!E) 11529 return nullptr; 11530 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11531 return DRE->getDecl(); 11532 if (auto *ME = dyn_cast<MemberExpr>(E)) 11533 return ME->getMemberDecl(); 11534 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11535 return IRE->getDecl(); 11536 return nullptr; 11537 } 11538 11539 // This helper function promotes a binary operator's operands (which are of a 11540 // half vector type) to a vector of floats and then truncates the result to 11541 // a vector of either half or short. 11542 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11543 BinaryOperatorKind Opc, QualType ResultTy, 11544 ExprValueKind VK, ExprObjectKind OK, 11545 bool IsCompAssign, SourceLocation OpLoc, 11546 FPOptions FPFeatures) { 11547 auto &Context = S.getASTContext(); 11548 assert((isVector(ResultTy, Context.HalfTy) || 11549 isVector(ResultTy, Context.ShortTy)) && 11550 "Result must be a vector of half or short"); 11551 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11552 isVector(RHS.get()->getType(), Context.HalfTy) && 11553 "both operands expected to be a half vector"); 11554 11555 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11556 QualType BinOpResTy = RHS.get()->getType(); 11557 11558 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11559 // change BinOpResTy to a vector of ints. 11560 if (isVector(ResultTy, Context.ShortTy)) 11561 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11562 11563 if (IsCompAssign) 11564 return new (Context) CompoundAssignOperator( 11565 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11566 OpLoc, FPFeatures); 11567 11568 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11569 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11570 VK, OK, OpLoc, FPFeatures); 11571 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11572 } 11573 11574 static std::pair<ExprResult, ExprResult> 11575 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11576 Expr *RHSExpr) { 11577 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11578 if (!S.getLangOpts().CPlusPlus) { 11579 // C cannot handle TypoExpr nodes on either side of a binop because it 11580 // doesn't handle dependent types properly, so make sure any TypoExprs have 11581 // been dealt with before checking the operands. 11582 LHS = S.CorrectDelayedTyposInExpr(LHS); 11583 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11584 if (Opc != BO_Assign) 11585 return ExprResult(E); 11586 // Avoid correcting the RHS to the same Expr as the LHS. 11587 Decl *D = getDeclFromExpr(E); 11588 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11589 }); 11590 } 11591 return std::make_pair(LHS, RHS); 11592 } 11593 11594 /// Returns true if conversion between vectors of halfs and vectors of floats 11595 /// is needed. 11596 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11597 QualType SrcType) { 11598 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11599 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11600 isVector(SrcType, Ctx.HalfTy); 11601 } 11602 11603 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11604 /// operator @p Opc at location @c TokLoc. This routine only supports 11605 /// built-in operations; ActOnBinOp handles overloaded operators. 11606 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11607 BinaryOperatorKind Opc, 11608 Expr *LHSExpr, Expr *RHSExpr) { 11609 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11610 // The syntax only allows initializer lists on the RHS of assignment, 11611 // so we don't need to worry about accepting invalid code for 11612 // non-assignment operators. 11613 // C++11 5.17p9: 11614 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11615 // of x = {} is x = T(). 11616 InitializationKind Kind = InitializationKind::CreateDirectList( 11617 RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11618 InitializedEntity Entity = 11619 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11620 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11621 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11622 if (Init.isInvalid()) 11623 return Init; 11624 RHSExpr = Init.get(); 11625 } 11626 11627 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11628 QualType ResultTy; // Result type of the binary operator. 11629 // The following two variables are used for compound assignment operators 11630 QualType CompLHSTy; // Type of LHS after promotions for computation 11631 QualType CompResultTy; // Type of computation result 11632 ExprValueKind VK = VK_RValue; 11633 ExprObjectKind OK = OK_Ordinary; 11634 bool ConvertHalfVec = false; 11635 11636 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11637 if (!LHS.isUsable() || !RHS.isUsable()) 11638 return ExprError(); 11639 11640 if (getLangOpts().OpenCL) { 11641 QualType LHSTy = LHSExpr->getType(); 11642 QualType RHSTy = RHSExpr->getType(); 11643 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11644 // the ATOMIC_VAR_INIT macro. 11645 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11646 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11647 if (BO_Assign == Opc) 11648 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11649 else 11650 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11651 return ExprError(); 11652 } 11653 11654 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11655 // only with a builtin functions and therefore should be disallowed here. 11656 if (LHSTy->isImageType() || RHSTy->isImageType() || 11657 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11658 LHSTy->isPipeType() || RHSTy->isPipeType() || 11659 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11660 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11661 return ExprError(); 11662 } 11663 } 11664 11665 switch (Opc) { 11666 case BO_Assign: 11667 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11668 if (getLangOpts().CPlusPlus && 11669 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11670 VK = LHS.get()->getValueKind(); 11671 OK = LHS.get()->getObjectKind(); 11672 } 11673 if (!ResultTy.isNull()) { 11674 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11675 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11676 } 11677 RecordModifiableNonNullParam(*this, LHS.get()); 11678 break; 11679 case BO_PtrMemD: 11680 case BO_PtrMemI: 11681 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11682 Opc == BO_PtrMemI); 11683 break; 11684 case BO_Mul: 11685 case BO_Div: 11686 ConvertHalfVec = true; 11687 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11688 Opc == BO_Div); 11689 break; 11690 case BO_Rem: 11691 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11692 break; 11693 case BO_Add: 11694 ConvertHalfVec = true; 11695 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11696 break; 11697 case BO_Sub: 11698 ConvertHalfVec = true; 11699 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11700 break; 11701 case BO_Shl: 11702 case BO_Shr: 11703 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11704 break; 11705 case BO_LE: 11706 case BO_LT: 11707 case BO_GE: 11708 case BO_GT: 11709 ConvertHalfVec = true; 11710 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11711 break; 11712 case BO_EQ: 11713 case BO_NE: 11714 ConvertHalfVec = true; 11715 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11716 break; 11717 case BO_Cmp: 11718 // FIXME: Implement proper semantic checking of '<=>'. 11719 ConvertHalfVec = true; 11720 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11721 if (!ResultTy.isNull()) 11722 ResultTy = Context.VoidTy; 11723 break; 11724 case BO_And: 11725 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11726 LLVM_FALLTHROUGH; 11727 case BO_Xor: 11728 case BO_Or: 11729 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11730 break; 11731 case BO_LAnd: 11732 case BO_LOr: 11733 ConvertHalfVec = true; 11734 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11735 break; 11736 case BO_MulAssign: 11737 case BO_DivAssign: 11738 ConvertHalfVec = true; 11739 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11740 Opc == BO_DivAssign); 11741 CompLHSTy = CompResultTy; 11742 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11743 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11744 break; 11745 case BO_RemAssign: 11746 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11747 CompLHSTy = CompResultTy; 11748 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11749 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11750 break; 11751 case BO_AddAssign: 11752 ConvertHalfVec = true; 11753 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11754 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11755 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11756 break; 11757 case BO_SubAssign: 11758 ConvertHalfVec = true; 11759 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11760 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11761 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11762 break; 11763 case BO_ShlAssign: 11764 case BO_ShrAssign: 11765 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11766 CompLHSTy = CompResultTy; 11767 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11768 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11769 break; 11770 case BO_AndAssign: 11771 case BO_OrAssign: // fallthrough 11772 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11773 LLVM_FALLTHROUGH; 11774 case BO_XorAssign: 11775 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11776 CompLHSTy = CompResultTy; 11777 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11778 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11779 break; 11780 case BO_Comma: 11781 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11782 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11783 VK = RHS.get()->getValueKind(); 11784 OK = RHS.get()->getObjectKind(); 11785 } 11786 break; 11787 } 11788 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11789 return ExprError(); 11790 11791 // Some of the binary operations require promoting operands of half vector to 11792 // float vectors and truncating the result back to half vector. For now, we do 11793 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11794 // arm64). 11795 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11796 isVector(LHS.get()->getType(), Context.HalfTy) && 11797 "both sides are half vectors or neither sides are"); 11798 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11799 LHS.get()->getType()); 11800 11801 // Check for array bounds violations for both sides of the BinaryOperator 11802 CheckArrayAccess(LHS.get()); 11803 CheckArrayAccess(RHS.get()); 11804 11805 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11806 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11807 &Context.Idents.get("object_setClass"), 11808 SourceLocation(), LookupOrdinaryName); 11809 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11810 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11811 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11812 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11813 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11814 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11815 } 11816 else 11817 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11818 } 11819 else if (const ObjCIvarRefExpr *OIRE = 11820 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11821 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11822 11823 // Opc is not a compound assignment if CompResultTy is null. 11824 if (CompResultTy.isNull()) { 11825 if (ConvertHalfVec) 11826 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11827 OpLoc, FPFeatures); 11828 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11829 OK, OpLoc, FPFeatures); 11830 } 11831 11832 // Handle compound assignments. 11833 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11834 OK_ObjCProperty) { 11835 VK = VK_LValue; 11836 OK = LHS.get()->getObjectKind(); 11837 } 11838 11839 if (ConvertHalfVec) 11840 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11841 OpLoc, FPFeatures); 11842 11843 return new (Context) CompoundAssignOperator( 11844 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11845 OpLoc, FPFeatures); 11846 } 11847 11848 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11849 /// operators are mixed in a way that suggests that the programmer forgot that 11850 /// comparison operators have higher precedence. The most typical example of 11851 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11852 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11853 SourceLocation OpLoc, Expr *LHSExpr, 11854 Expr *RHSExpr) { 11855 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11856 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11857 11858 // Check that one of the sides is a comparison operator and the other isn't. 11859 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11860 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11861 if (isLeftComp == isRightComp) 11862 return; 11863 11864 // Bitwise operations are sometimes used as eager logical ops. 11865 // Don't diagnose this. 11866 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11867 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11868 if (isLeftBitwise || isRightBitwise) 11869 return; 11870 11871 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11872 OpLoc) 11873 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11874 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11875 SourceRange ParensRange = isLeftComp ? 11876 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11877 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11878 11879 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11880 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11881 SuggestParentheses(Self, OpLoc, 11882 Self.PDiag(diag::note_precedence_silence) << OpStr, 11883 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11884 SuggestParentheses(Self, OpLoc, 11885 Self.PDiag(diag::note_precedence_bitwise_first) 11886 << BinaryOperator::getOpcodeStr(Opc), 11887 ParensRange); 11888 } 11889 11890 /// \brief It accepts a '&&' expr that is inside a '||' one. 11891 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11892 /// in parentheses. 11893 static void 11894 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11895 BinaryOperator *Bop) { 11896 assert(Bop->getOpcode() == BO_LAnd); 11897 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11898 << Bop->getSourceRange() << OpLoc; 11899 SuggestParentheses(Self, Bop->getOperatorLoc(), 11900 Self.PDiag(diag::note_precedence_silence) 11901 << Bop->getOpcodeStr(), 11902 Bop->getSourceRange()); 11903 } 11904 11905 /// \brief Returns true if the given expression can be evaluated as a constant 11906 /// 'true'. 11907 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11908 bool Res; 11909 return !E->isValueDependent() && 11910 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11911 } 11912 11913 /// \brief Returns true if the given expression can be evaluated as a constant 11914 /// 'false'. 11915 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11916 bool Res; 11917 return !E->isValueDependent() && 11918 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11919 } 11920 11921 /// \brief Look for '&&' in the left hand of a '||' expr. 11922 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11923 Expr *LHSExpr, Expr *RHSExpr) { 11924 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11925 if (Bop->getOpcode() == BO_LAnd) { 11926 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11927 if (EvaluatesAsFalse(S, RHSExpr)) 11928 return; 11929 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11930 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11931 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11932 } else if (Bop->getOpcode() == BO_LOr) { 11933 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11934 // If it's "a || b && 1 || c" we didn't warn earlier for 11935 // "a || b && 1", but warn now. 11936 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11937 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11938 } 11939 } 11940 } 11941 } 11942 11943 /// \brief Look for '&&' in the right hand of a '||' expr. 11944 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11945 Expr *LHSExpr, Expr *RHSExpr) { 11946 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11947 if (Bop->getOpcode() == BO_LAnd) { 11948 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11949 if (EvaluatesAsFalse(S, LHSExpr)) 11950 return; 11951 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11952 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11953 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11954 } 11955 } 11956 } 11957 11958 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11959 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11960 /// the '&' expression in parentheses. 11961 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11962 SourceLocation OpLoc, Expr *SubExpr) { 11963 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11964 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11965 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11966 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11967 << Bop->getSourceRange() << OpLoc; 11968 SuggestParentheses(S, Bop->getOperatorLoc(), 11969 S.PDiag(diag::note_precedence_silence) 11970 << Bop->getOpcodeStr(), 11971 Bop->getSourceRange()); 11972 } 11973 } 11974 } 11975 11976 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11977 Expr *SubExpr, StringRef Shift) { 11978 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11979 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11980 StringRef Op = Bop->getOpcodeStr(); 11981 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11982 << Bop->getSourceRange() << OpLoc << Shift << Op; 11983 SuggestParentheses(S, Bop->getOperatorLoc(), 11984 S.PDiag(diag::note_precedence_silence) << Op, 11985 Bop->getSourceRange()); 11986 } 11987 } 11988 } 11989 11990 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11991 Expr *LHSExpr, Expr *RHSExpr) { 11992 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11993 if (!OCE) 11994 return; 11995 11996 FunctionDecl *FD = OCE->getDirectCallee(); 11997 if (!FD || !FD->isOverloadedOperator()) 11998 return; 11999 12000 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12001 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12002 return; 12003 12004 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12005 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12006 << (Kind == OO_LessLess); 12007 SuggestParentheses(S, OCE->getOperatorLoc(), 12008 S.PDiag(diag::note_precedence_silence) 12009 << (Kind == OO_LessLess ? "<<" : ">>"), 12010 OCE->getSourceRange()); 12011 SuggestParentheses(S, OpLoc, 12012 S.PDiag(diag::note_evaluate_comparison_first), 12013 SourceRange(OCE->getArg(1)->getLocStart(), 12014 RHSExpr->getLocEnd())); 12015 } 12016 12017 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12018 /// precedence. 12019 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12020 SourceLocation OpLoc, Expr *LHSExpr, 12021 Expr *RHSExpr){ 12022 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12023 if (BinaryOperator::isBitwiseOp(Opc)) 12024 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12025 12026 // Diagnose "arg1 & arg2 | arg3" 12027 if ((Opc == BO_Or || Opc == BO_Xor) && 12028 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12029 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12030 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12031 } 12032 12033 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12034 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12035 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12036 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12037 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12038 } 12039 12040 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12041 || Opc == BO_Shr) { 12042 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12043 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12044 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12045 } 12046 12047 // Warn on overloaded shift operators and comparisons, such as: 12048 // cout << 5 == 4; 12049 if (BinaryOperator::isComparisonOp(Opc)) 12050 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12051 } 12052 12053 // Binary Operators. 'Tok' is the token for the operator. 12054 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12055 tok::TokenKind Kind, 12056 Expr *LHSExpr, Expr *RHSExpr) { 12057 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12058 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12059 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12060 12061 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12062 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12063 12064 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12065 } 12066 12067 /// Build an overloaded binary operator expression in the given scope. 12068 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12069 BinaryOperatorKind Opc, 12070 Expr *LHS, Expr *RHS) { 12071 // Find all of the overloaded operators visible from this 12072 // point. We perform both an operator-name lookup from the local 12073 // scope and an argument-dependent lookup based on the types of 12074 // the arguments. 12075 UnresolvedSet<16> Functions; 12076 OverloadedOperatorKind OverOp 12077 = BinaryOperator::getOverloadedOperator(Opc); 12078 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12079 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12080 RHS->getType(), Functions); 12081 12082 // Build the (potentially-overloaded, potentially-dependent) 12083 // binary operation. 12084 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12085 } 12086 12087 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12088 BinaryOperatorKind Opc, 12089 Expr *LHSExpr, Expr *RHSExpr) { 12090 ExprResult LHS, RHS; 12091 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12092 if (!LHS.isUsable() || !RHS.isUsable()) 12093 return ExprError(); 12094 LHSExpr = LHS.get(); 12095 RHSExpr = RHS.get(); 12096 12097 // We want to end up calling one of checkPseudoObjectAssignment 12098 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12099 // both expressions are overloadable or either is type-dependent), 12100 // or CreateBuiltinBinOp (in any other case). We also want to get 12101 // any placeholder types out of the way. 12102 12103 // Handle pseudo-objects in the LHS. 12104 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12105 // Assignments with a pseudo-object l-value need special analysis. 12106 if (pty->getKind() == BuiltinType::PseudoObject && 12107 BinaryOperator::isAssignmentOp(Opc)) 12108 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12109 12110 // Don't resolve overloads if the other type is overloadable. 12111 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12112 // We can't actually test that if we still have a placeholder, 12113 // though. Fortunately, none of the exceptions we see in that 12114 // code below are valid when the LHS is an overload set. Note 12115 // that an overload set can be dependently-typed, but it never 12116 // instantiates to having an overloadable type. 12117 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12118 if (resolvedRHS.isInvalid()) return ExprError(); 12119 RHSExpr = resolvedRHS.get(); 12120 12121 if (RHSExpr->isTypeDependent() || 12122 RHSExpr->getType()->isOverloadableType()) 12123 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12124 } 12125 12126 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12127 // template, diagnose the missing 'template' keyword instead of diagnosing 12128 // an invalid use of a bound member function. 12129 // 12130 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12131 // to C++1z [over.over]/1.4, but we already checked for that case above. 12132 if (Opc == BO_LT && inTemplateInstantiation() && 12133 (pty->getKind() == BuiltinType::BoundMember || 12134 pty->getKind() == BuiltinType::Overload)) { 12135 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12136 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12137 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12138 return isa<FunctionTemplateDecl>(ND); 12139 })) { 12140 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12141 : OE->getNameLoc(), 12142 diag::err_template_kw_missing) 12143 << OE->getName().getAsString() << ""; 12144 return ExprError(); 12145 } 12146 } 12147 12148 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12149 if (LHS.isInvalid()) return ExprError(); 12150 LHSExpr = LHS.get(); 12151 } 12152 12153 // Handle pseudo-objects in the RHS. 12154 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12155 // An overload in the RHS can potentially be resolved by the type 12156 // being assigned to. 12157 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12158 if (getLangOpts().CPlusPlus && 12159 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12160 LHSExpr->getType()->isOverloadableType())) 12161 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12162 12163 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12164 } 12165 12166 // Don't resolve overloads if the other type is overloadable. 12167 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12168 LHSExpr->getType()->isOverloadableType()) 12169 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12170 12171 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12172 if (!resolvedRHS.isUsable()) return ExprError(); 12173 RHSExpr = resolvedRHS.get(); 12174 } 12175 12176 if (getLangOpts().CPlusPlus) { 12177 // If either expression is type-dependent, always build an 12178 // overloaded op. 12179 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12180 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12181 12182 // Otherwise, build an overloaded op if either expression has an 12183 // overloadable type. 12184 if (LHSExpr->getType()->isOverloadableType() || 12185 RHSExpr->getType()->isOverloadableType()) 12186 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12187 } 12188 12189 // Build a built-in binary operation. 12190 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12191 } 12192 12193 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12194 if (T.isNull() || T->isDependentType()) 12195 return false; 12196 12197 if (!T->isPromotableIntegerType()) 12198 return true; 12199 12200 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12201 } 12202 12203 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12204 UnaryOperatorKind Opc, 12205 Expr *InputExpr) { 12206 ExprResult Input = InputExpr; 12207 ExprValueKind VK = VK_RValue; 12208 ExprObjectKind OK = OK_Ordinary; 12209 QualType resultType; 12210 bool CanOverflow = false; 12211 12212 bool ConvertHalfVec = false; 12213 if (getLangOpts().OpenCL) { 12214 QualType Ty = InputExpr->getType(); 12215 // The only legal unary operation for atomics is '&'. 12216 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12217 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12218 // only with a builtin functions and therefore should be disallowed here. 12219 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12220 || Ty->isBlockPointerType())) { 12221 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12222 << InputExpr->getType() 12223 << Input.get()->getSourceRange()); 12224 } 12225 } 12226 switch (Opc) { 12227 case UO_PreInc: 12228 case UO_PreDec: 12229 case UO_PostInc: 12230 case UO_PostDec: 12231 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12232 OpLoc, 12233 Opc == UO_PreInc || 12234 Opc == UO_PostInc, 12235 Opc == UO_PreInc || 12236 Opc == UO_PreDec); 12237 CanOverflow = isOverflowingIntegerType(Context, resultType); 12238 break; 12239 case UO_AddrOf: 12240 resultType = CheckAddressOfOperand(Input, OpLoc); 12241 RecordModifiableNonNullParam(*this, InputExpr); 12242 break; 12243 case UO_Deref: { 12244 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12245 if (Input.isInvalid()) return ExprError(); 12246 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12247 break; 12248 } 12249 case UO_Plus: 12250 case UO_Minus: 12251 CanOverflow = Opc == UO_Minus && 12252 isOverflowingIntegerType(Context, Input.get()->getType()); 12253 Input = UsualUnaryConversions(Input.get()); 12254 if (Input.isInvalid()) return ExprError(); 12255 // Unary plus and minus require promoting an operand of half vector to a 12256 // float vector and truncating the result back to a half vector. For now, we 12257 // do this only when HalfArgsAndReturns is set (that is, when the target is 12258 // arm or arm64). 12259 ConvertHalfVec = 12260 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12261 12262 // If the operand is a half vector, promote it to a float vector. 12263 if (ConvertHalfVec) 12264 Input = convertVector(Input.get(), Context.FloatTy, *this); 12265 resultType = Input.get()->getType(); 12266 if (resultType->isDependentType()) 12267 break; 12268 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12269 break; 12270 else if (resultType->isVectorType() && 12271 // The z vector extensions don't allow + or - with bool vectors. 12272 (!Context.getLangOpts().ZVector || 12273 resultType->getAs<VectorType>()->getVectorKind() != 12274 VectorType::AltiVecBool)) 12275 break; 12276 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12277 Opc == UO_Plus && 12278 resultType->isPointerType()) 12279 break; 12280 12281 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12282 << resultType << Input.get()->getSourceRange()); 12283 12284 case UO_Not: // bitwise complement 12285 Input = UsualUnaryConversions(Input.get()); 12286 if (Input.isInvalid()) 12287 return ExprError(); 12288 resultType = Input.get()->getType(); 12289 12290 if (resultType->isDependentType()) 12291 break; 12292 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12293 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12294 // C99 does not support '~' for complex conjugation. 12295 Diag(OpLoc, diag::ext_integer_complement_complex) 12296 << resultType << Input.get()->getSourceRange(); 12297 else if (resultType->hasIntegerRepresentation()) 12298 break; 12299 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12300 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12301 // on vector float types. 12302 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12303 if (!T->isIntegerType()) 12304 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12305 << resultType << Input.get()->getSourceRange()); 12306 } else { 12307 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12308 << resultType << Input.get()->getSourceRange()); 12309 } 12310 break; 12311 12312 case UO_LNot: // logical negation 12313 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12314 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12315 if (Input.isInvalid()) return ExprError(); 12316 resultType = Input.get()->getType(); 12317 12318 // Though we still have to promote half FP to float... 12319 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12320 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12321 resultType = Context.FloatTy; 12322 } 12323 12324 if (resultType->isDependentType()) 12325 break; 12326 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12327 // C99 6.5.3.3p1: ok, fallthrough; 12328 if (Context.getLangOpts().CPlusPlus) { 12329 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12330 // operand contextually converted to bool. 12331 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12332 ScalarTypeToBooleanCastKind(resultType)); 12333 } else if (Context.getLangOpts().OpenCL && 12334 Context.getLangOpts().OpenCLVersion < 120) { 12335 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12336 // operate on scalar float types. 12337 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12338 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12339 << resultType << Input.get()->getSourceRange()); 12340 } 12341 } else if (resultType->isExtVectorType()) { 12342 if (Context.getLangOpts().OpenCL && 12343 Context.getLangOpts().OpenCLVersion < 120) { 12344 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12345 // operate on vector float types. 12346 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12347 if (!T->isIntegerType()) 12348 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12349 << resultType << Input.get()->getSourceRange()); 12350 } 12351 // Vector logical not returns the signed variant of the operand type. 12352 resultType = GetSignedVectorType(resultType); 12353 break; 12354 } else { 12355 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12356 // type in C++. We should allow that here too. 12357 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12358 << resultType << Input.get()->getSourceRange()); 12359 } 12360 12361 // LNot always has type int. C99 6.5.3.3p5. 12362 // In C++, it's bool. C++ 5.3.1p8 12363 resultType = Context.getLogicalOperationType(); 12364 break; 12365 case UO_Real: 12366 case UO_Imag: 12367 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12368 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12369 // complex l-values to ordinary l-values and all other values to r-values. 12370 if (Input.isInvalid()) return ExprError(); 12371 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12372 if (Input.get()->getValueKind() != VK_RValue && 12373 Input.get()->getObjectKind() == OK_Ordinary) 12374 VK = Input.get()->getValueKind(); 12375 } else if (!getLangOpts().CPlusPlus) { 12376 // In C, a volatile scalar is read by __imag. In C++, it is not. 12377 Input = DefaultLvalueConversion(Input.get()); 12378 } 12379 break; 12380 case UO_Extension: 12381 resultType = Input.get()->getType(); 12382 VK = Input.get()->getValueKind(); 12383 OK = Input.get()->getObjectKind(); 12384 break; 12385 case UO_Coawait: 12386 // It's unnessesary to represent the pass-through operator co_await in the 12387 // AST; just return the input expression instead. 12388 assert(!Input.get()->getType()->isDependentType() && 12389 "the co_await expression must be non-dependant before " 12390 "building operator co_await"); 12391 return Input; 12392 } 12393 if (resultType.isNull() || Input.isInvalid()) 12394 return ExprError(); 12395 12396 // Check for array bounds violations in the operand of the UnaryOperator, 12397 // except for the '*' and '&' operators that have to be handled specially 12398 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12399 // that are explicitly defined as valid by the standard). 12400 if (Opc != UO_AddrOf && Opc != UO_Deref) 12401 CheckArrayAccess(Input.get()); 12402 12403 auto *UO = new (Context) 12404 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12405 // Convert the result back to a half vector. 12406 if (ConvertHalfVec) 12407 return convertVector(UO, Context.HalfTy, *this); 12408 return UO; 12409 } 12410 12411 /// \brief Determine whether the given expression is a qualified member 12412 /// access expression, of a form that could be turned into a pointer to member 12413 /// with the address-of operator. 12414 static bool isQualifiedMemberAccess(Expr *E) { 12415 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12416 if (!DRE->getQualifier()) 12417 return false; 12418 12419 ValueDecl *VD = DRE->getDecl(); 12420 if (!VD->isCXXClassMember()) 12421 return false; 12422 12423 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12424 return true; 12425 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12426 return Method->isInstance(); 12427 12428 return false; 12429 } 12430 12431 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12432 if (!ULE->getQualifier()) 12433 return false; 12434 12435 for (NamedDecl *D : ULE->decls()) { 12436 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12437 if (Method->isInstance()) 12438 return true; 12439 } else { 12440 // Overload set does not contain methods. 12441 break; 12442 } 12443 } 12444 12445 return false; 12446 } 12447 12448 return false; 12449 } 12450 12451 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12452 UnaryOperatorKind Opc, Expr *Input) { 12453 // First things first: handle placeholders so that the 12454 // overloaded-operator check considers the right type. 12455 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12456 // Increment and decrement of pseudo-object references. 12457 if (pty->getKind() == BuiltinType::PseudoObject && 12458 UnaryOperator::isIncrementDecrementOp(Opc)) 12459 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12460 12461 // extension is always a builtin operator. 12462 if (Opc == UO_Extension) 12463 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12464 12465 // & gets special logic for several kinds of placeholder. 12466 // The builtin code knows what to do. 12467 if (Opc == UO_AddrOf && 12468 (pty->getKind() == BuiltinType::Overload || 12469 pty->getKind() == BuiltinType::UnknownAny || 12470 pty->getKind() == BuiltinType::BoundMember)) 12471 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12472 12473 // Anything else needs to be handled now. 12474 ExprResult Result = CheckPlaceholderExpr(Input); 12475 if (Result.isInvalid()) return ExprError(); 12476 Input = Result.get(); 12477 } 12478 12479 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12480 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12481 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12482 // Find all of the overloaded operators visible from this 12483 // point. We perform both an operator-name lookup from the local 12484 // scope and an argument-dependent lookup based on the types of 12485 // the arguments. 12486 UnresolvedSet<16> Functions; 12487 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12488 if (S && OverOp != OO_None) 12489 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12490 Functions); 12491 12492 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12493 } 12494 12495 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12496 } 12497 12498 // Unary Operators. 'Tok' is the token for the operator. 12499 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12500 tok::TokenKind Op, Expr *Input) { 12501 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12502 } 12503 12504 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12505 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12506 LabelDecl *TheDecl) { 12507 TheDecl->markUsed(Context); 12508 // Create the AST node. The address of a label always has type 'void*'. 12509 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12510 Context.getPointerType(Context.VoidTy)); 12511 } 12512 12513 /// Given the last statement in a statement-expression, check whether 12514 /// the result is a producing expression (like a call to an 12515 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12516 /// release out of the full-expression. Otherwise, return null. 12517 /// Cannot fail. 12518 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12519 // Should always be wrapped with one of these. 12520 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12521 if (!cleanups) return nullptr; 12522 12523 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12524 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12525 return nullptr; 12526 12527 // Splice out the cast. This shouldn't modify any interesting 12528 // features of the statement. 12529 Expr *producer = cast->getSubExpr(); 12530 assert(producer->getType() == cast->getType()); 12531 assert(producer->getValueKind() == cast->getValueKind()); 12532 cleanups->setSubExpr(producer); 12533 return cleanups; 12534 } 12535 12536 void Sema::ActOnStartStmtExpr() { 12537 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12538 } 12539 12540 void Sema::ActOnStmtExprError() { 12541 // Note that function is also called by TreeTransform when leaving a 12542 // StmtExpr scope without rebuilding anything. 12543 12544 DiscardCleanupsInEvaluationContext(); 12545 PopExpressionEvaluationContext(); 12546 } 12547 12548 ExprResult 12549 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12550 SourceLocation RPLoc) { // "({..})" 12551 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12552 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12553 12554 if (hasAnyUnrecoverableErrorsInThisFunction()) 12555 DiscardCleanupsInEvaluationContext(); 12556 assert(!Cleanup.exprNeedsCleanups() && 12557 "cleanups within StmtExpr not correctly bound!"); 12558 PopExpressionEvaluationContext(); 12559 12560 // FIXME: there are a variety of strange constraints to enforce here, for 12561 // example, it is not possible to goto into a stmt expression apparently. 12562 // More semantic analysis is needed. 12563 12564 // If there are sub-stmts in the compound stmt, take the type of the last one 12565 // as the type of the stmtexpr. 12566 QualType Ty = Context.VoidTy; 12567 bool StmtExprMayBindToTemp = false; 12568 if (!Compound->body_empty()) { 12569 Stmt *LastStmt = Compound->body_back(); 12570 LabelStmt *LastLabelStmt = nullptr; 12571 // If LastStmt is a label, skip down through into the body. 12572 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12573 LastLabelStmt = Label; 12574 LastStmt = Label->getSubStmt(); 12575 } 12576 12577 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12578 // Do function/array conversion on the last expression, but not 12579 // lvalue-to-rvalue. However, initialize an unqualified type. 12580 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12581 if (LastExpr.isInvalid()) 12582 return ExprError(); 12583 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12584 12585 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12586 // In ARC, if the final expression ends in a consume, splice 12587 // the consume out and bind it later. In the alternate case 12588 // (when dealing with a retainable type), the result 12589 // initialization will create a produce. In both cases the 12590 // result will be +1, and we'll need to balance that out with 12591 // a bind. 12592 if (Expr *rebuiltLastStmt 12593 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12594 LastExpr = rebuiltLastStmt; 12595 } else { 12596 LastExpr = PerformCopyInitialization( 12597 InitializedEntity::InitializeResult(LPLoc, 12598 Ty, 12599 false), 12600 SourceLocation(), 12601 LastExpr); 12602 } 12603 12604 if (LastExpr.isInvalid()) 12605 return ExprError(); 12606 if (LastExpr.get() != nullptr) { 12607 if (!LastLabelStmt) 12608 Compound->setLastStmt(LastExpr.get()); 12609 else 12610 LastLabelStmt->setSubStmt(LastExpr.get()); 12611 StmtExprMayBindToTemp = true; 12612 } 12613 } 12614 } 12615 } 12616 12617 // FIXME: Check that expression type is complete/non-abstract; statement 12618 // expressions are not lvalues. 12619 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12620 if (StmtExprMayBindToTemp) 12621 return MaybeBindToTemporary(ResStmtExpr); 12622 return ResStmtExpr; 12623 } 12624 12625 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12626 TypeSourceInfo *TInfo, 12627 ArrayRef<OffsetOfComponent> Components, 12628 SourceLocation RParenLoc) { 12629 QualType ArgTy = TInfo->getType(); 12630 bool Dependent = ArgTy->isDependentType(); 12631 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12632 12633 // We must have at least one component that refers to the type, and the first 12634 // one is known to be a field designator. Verify that the ArgTy represents 12635 // a struct/union/class. 12636 if (!Dependent && !ArgTy->isRecordType()) 12637 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12638 << ArgTy << TypeRange); 12639 12640 // Type must be complete per C99 7.17p3 because a declaring a variable 12641 // with an incomplete type would be ill-formed. 12642 if (!Dependent 12643 && RequireCompleteType(BuiltinLoc, ArgTy, 12644 diag::err_offsetof_incomplete_type, TypeRange)) 12645 return ExprError(); 12646 12647 bool DidWarnAboutNonPOD = false; 12648 QualType CurrentType = ArgTy; 12649 SmallVector<OffsetOfNode, 4> Comps; 12650 SmallVector<Expr*, 4> Exprs; 12651 for (const OffsetOfComponent &OC : Components) { 12652 if (OC.isBrackets) { 12653 // Offset of an array sub-field. TODO: Should we allow vector elements? 12654 if (!CurrentType->isDependentType()) { 12655 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12656 if(!AT) 12657 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12658 << CurrentType); 12659 CurrentType = AT->getElementType(); 12660 } else 12661 CurrentType = Context.DependentTy; 12662 12663 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12664 if (IdxRval.isInvalid()) 12665 return ExprError(); 12666 Expr *Idx = IdxRval.get(); 12667 12668 // The expression must be an integral expression. 12669 // FIXME: An integral constant expression? 12670 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12671 !Idx->getType()->isIntegerType()) 12672 return ExprError(Diag(Idx->getLocStart(), 12673 diag::err_typecheck_subscript_not_integer) 12674 << Idx->getSourceRange()); 12675 12676 // Record this array index. 12677 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12678 Exprs.push_back(Idx); 12679 continue; 12680 } 12681 12682 // Offset of a field. 12683 if (CurrentType->isDependentType()) { 12684 // We have the offset of a field, but we can't look into the dependent 12685 // type. Just record the identifier of the field. 12686 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12687 CurrentType = Context.DependentTy; 12688 continue; 12689 } 12690 12691 // We need to have a complete type to look into. 12692 if (RequireCompleteType(OC.LocStart, CurrentType, 12693 diag::err_offsetof_incomplete_type)) 12694 return ExprError(); 12695 12696 // Look for the designated field. 12697 const RecordType *RC = CurrentType->getAs<RecordType>(); 12698 if (!RC) 12699 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12700 << CurrentType); 12701 RecordDecl *RD = RC->getDecl(); 12702 12703 // C++ [lib.support.types]p5: 12704 // The macro offsetof accepts a restricted set of type arguments in this 12705 // International Standard. type shall be a POD structure or a POD union 12706 // (clause 9). 12707 // C++11 [support.types]p4: 12708 // If type is not a standard-layout class (Clause 9), the results are 12709 // undefined. 12710 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12711 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12712 unsigned DiagID = 12713 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12714 : diag::ext_offsetof_non_pod_type; 12715 12716 if (!IsSafe && !DidWarnAboutNonPOD && 12717 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12718 PDiag(DiagID) 12719 << SourceRange(Components[0].LocStart, OC.LocEnd) 12720 << CurrentType)) 12721 DidWarnAboutNonPOD = true; 12722 } 12723 12724 // Look for the field. 12725 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12726 LookupQualifiedName(R, RD); 12727 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12728 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12729 if (!MemberDecl) { 12730 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12731 MemberDecl = IndirectMemberDecl->getAnonField(); 12732 } 12733 12734 if (!MemberDecl) 12735 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12736 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12737 OC.LocEnd)); 12738 12739 // C99 7.17p3: 12740 // (If the specified member is a bit-field, the behavior is undefined.) 12741 // 12742 // We diagnose this as an error. 12743 if (MemberDecl->isBitField()) { 12744 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12745 << MemberDecl->getDeclName() 12746 << SourceRange(BuiltinLoc, RParenLoc); 12747 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12748 return ExprError(); 12749 } 12750 12751 RecordDecl *Parent = MemberDecl->getParent(); 12752 if (IndirectMemberDecl) 12753 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12754 12755 // If the member was found in a base class, introduce OffsetOfNodes for 12756 // the base class indirections. 12757 CXXBasePaths Paths; 12758 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12759 Paths)) { 12760 if (Paths.getDetectedVirtual()) { 12761 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12762 << MemberDecl->getDeclName() 12763 << SourceRange(BuiltinLoc, RParenLoc); 12764 return ExprError(); 12765 } 12766 12767 CXXBasePath &Path = Paths.front(); 12768 for (const CXXBasePathElement &B : Path) 12769 Comps.push_back(OffsetOfNode(B.Base)); 12770 } 12771 12772 if (IndirectMemberDecl) { 12773 for (auto *FI : IndirectMemberDecl->chain()) { 12774 assert(isa<FieldDecl>(FI)); 12775 Comps.push_back(OffsetOfNode(OC.LocStart, 12776 cast<FieldDecl>(FI), OC.LocEnd)); 12777 } 12778 } else 12779 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12780 12781 CurrentType = MemberDecl->getType().getNonReferenceType(); 12782 } 12783 12784 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12785 Comps, Exprs, RParenLoc); 12786 } 12787 12788 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12789 SourceLocation BuiltinLoc, 12790 SourceLocation TypeLoc, 12791 ParsedType ParsedArgTy, 12792 ArrayRef<OffsetOfComponent> Components, 12793 SourceLocation RParenLoc) { 12794 12795 TypeSourceInfo *ArgTInfo; 12796 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12797 if (ArgTy.isNull()) 12798 return ExprError(); 12799 12800 if (!ArgTInfo) 12801 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12802 12803 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12804 } 12805 12806 12807 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12808 Expr *CondExpr, 12809 Expr *LHSExpr, Expr *RHSExpr, 12810 SourceLocation RPLoc) { 12811 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12812 12813 ExprValueKind VK = VK_RValue; 12814 ExprObjectKind OK = OK_Ordinary; 12815 QualType resType; 12816 bool ValueDependent = false; 12817 bool CondIsTrue = false; 12818 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12819 resType = Context.DependentTy; 12820 ValueDependent = true; 12821 } else { 12822 // The conditional expression is required to be a constant expression. 12823 llvm::APSInt condEval(32); 12824 ExprResult CondICE 12825 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12826 diag::err_typecheck_choose_expr_requires_constant, false); 12827 if (CondICE.isInvalid()) 12828 return ExprError(); 12829 CondExpr = CondICE.get(); 12830 CondIsTrue = condEval.getZExtValue(); 12831 12832 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12833 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12834 12835 resType = ActiveExpr->getType(); 12836 ValueDependent = ActiveExpr->isValueDependent(); 12837 VK = ActiveExpr->getValueKind(); 12838 OK = ActiveExpr->getObjectKind(); 12839 } 12840 12841 return new (Context) 12842 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12843 CondIsTrue, resType->isDependentType(), ValueDependent); 12844 } 12845 12846 //===----------------------------------------------------------------------===// 12847 // Clang Extensions. 12848 //===----------------------------------------------------------------------===// 12849 12850 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12851 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12852 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12853 12854 if (LangOpts.CPlusPlus) { 12855 Decl *ManglingContextDecl; 12856 if (MangleNumberingContext *MCtx = 12857 getCurrentMangleNumberContext(Block->getDeclContext(), 12858 ManglingContextDecl)) { 12859 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12860 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12861 } 12862 } 12863 12864 PushBlockScope(CurScope, Block); 12865 CurContext->addDecl(Block); 12866 if (CurScope) 12867 PushDeclContext(CurScope, Block); 12868 else 12869 CurContext = Block; 12870 12871 getCurBlock()->HasImplicitReturnType = true; 12872 12873 // Enter a new evaluation context to insulate the block from any 12874 // cleanups from the enclosing full-expression. 12875 PushExpressionEvaluationContext( 12876 ExpressionEvaluationContext::PotentiallyEvaluated); 12877 } 12878 12879 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12880 Scope *CurScope) { 12881 assert(ParamInfo.getIdentifier() == nullptr && 12882 "block-id should have no identifier!"); 12883 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 12884 BlockScopeInfo *CurBlock = getCurBlock(); 12885 12886 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12887 QualType T = Sig->getType(); 12888 12889 // FIXME: We should allow unexpanded parameter packs here, but that would, 12890 // in turn, make the block expression contain unexpanded parameter packs. 12891 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12892 // Drop the parameters. 12893 FunctionProtoType::ExtProtoInfo EPI; 12894 EPI.HasTrailingReturn = false; 12895 EPI.TypeQuals |= DeclSpec::TQ_const; 12896 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12897 Sig = Context.getTrivialTypeSourceInfo(T); 12898 } 12899 12900 // GetTypeForDeclarator always produces a function type for a block 12901 // literal signature. Furthermore, it is always a FunctionProtoType 12902 // unless the function was written with a typedef. 12903 assert(T->isFunctionType() && 12904 "GetTypeForDeclarator made a non-function block signature"); 12905 12906 // Look for an explicit signature in that function type. 12907 FunctionProtoTypeLoc ExplicitSignature; 12908 12909 if ((ExplicitSignature = 12910 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 12911 12912 // Check whether that explicit signature was synthesized by 12913 // GetTypeForDeclarator. If so, don't save that as part of the 12914 // written signature. 12915 if (ExplicitSignature.getLocalRangeBegin() == 12916 ExplicitSignature.getLocalRangeEnd()) { 12917 // This would be much cheaper if we stored TypeLocs instead of 12918 // TypeSourceInfos. 12919 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12920 unsigned Size = Result.getFullDataSize(); 12921 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12922 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12923 12924 ExplicitSignature = FunctionProtoTypeLoc(); 12925 } 12926 } 12927 12928 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12929 CurBlock->FunctionType = T; 12930 12931 const FunctionType *Fn = T->getAs<FunctionType>(); 12932 QualType RetTy = Fn->getReturnType(); 12933 bool isVariadic = 12934 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12935 12936 CurBlock->TheDecl->setIsVariadic(isVariadic); 12937 12938 // Context.DependentTy is used as a placeholder for a missing block 12939 // return type. TODO: what should we do with declarators like: 12940 // ^ * { ... } 12941 // If the answer is "apply template argument deduction".... 12942 if (RetTy != Context.DependentTy) { 12943 CurBlock->ReturnType = RetTy; 12944 CurBlock->TheDecl->setBlockMissingReturnType(false); 12945 CurBlock->HasImplicitReturnType = false; 12946 } 12947 12948 // Push block parameters from the declarator if we had them. 12949 SmallVector<ParmVarDecl*, 8> Params; 12950 if (ExplicitSignature) { 12951 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12952 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12953 if (Param->getIdentifier() == nullptr && 12954 !Param->isImplicit() && 12955 !Param->isInvalidDecl() && 12956 !getLangOpts().CPlusPlus) 12957 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12958 Params.push_back(Param); 12959 } 12960 12961 // Fake up parameter variables if we have a typedef, like 12962 // ^ fntype { ... } 12963 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12964 for (const auto &I : Fn->param_types()) { 12965 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12966 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12967 Params.push_back(Param); 12968 } 12969 } 12970 12971 // Set the parameters on the block decl. 12972 if (!Params.empty()) { 12973 CurBlock->TheDecl->setParams(Params); 12974 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12975 /*CheckParameterNames=*/false); 12976 } 12977 12978 // Finally we can process decl attributes. 12979 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12980 12981 // Put the parameter variables in scope. 12982 for (auto AI : CurBlock->TheDecl->parameters()) { 12983 AI->setOwningFunction(CurBlock->TheDecl); 12984 12985 // If this has an identifier, add it to the scope stack. 12986 if (AI->getIdentifier()) { 12987 CheckShadow(CurBlock->TheScope, AI); 12988 12989 PushOnScopeChains(AI, CurBlock->TheScope); 12990 } 12991 } 12992 } 12993 12994 /// ActOnBlockError - If there is an error parsing a block, this callback 12995 /// is invoked to pop the information about the block from the action impl. 12996 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12997 // Leave the expression-evaluation context. 12998 DiscardCleanupsInEvaluationContext(); 12999 PopExpressionEvaluationContext(); 13000 13001 // Pop off CurBlock, handle nested blocks. 13002 PopDeclContext(); 13003 PopFunctionScopeInfo(); 13004 } 13005 13006 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13007 /// literal was successfully completed. ^(int x){...} 13008 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13009 Stmt *Body, Scope *CurScope) { 13010 // If blocks are disabled, emit an error. 13011 if (!LangOpts.Blocks) 13012 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13013 13014 // Leave the expression-evaluation context. 13015 if (hasAnyUnrecoverableErrorsInThisFunction()) 13016 DiscardCleanupsInEvaluationContext(); 13017 assert(!Cleanup.exprNeedsCleanups() && 13018 "cleanups within block not correctly bound!"); 13019 PopExpressionEvaluationContext(); 13020 13021 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13022 13023 if (BSI->HasImplicitReturnType) 13024 deduceClosureReturnType(*BSI); 13025 13026 PopDeclContext(); 13027 13028 QualType RetTy = Context.VoidTy; 13029 if (!BSI->ReturnType.isNull()) 13030 RetTy = BSI->ReturnType; 13031 13032 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13033 QualType BlockTy; 13034 13035 // Set the captured variables on the block. 13036 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13037 SmallVector<BlockDecl::Capture, 4> Captures; 13038 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 13039 if (Cap.isThisCapture()) 13040 continue; 13041 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13042 Cap.isNested(), Cap.getInitExpr()); 13043 Captures.push_back(NewCap); 13044 } 13045 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13046 13047 // If the user wrote a function type in some form, try to use that. 13048 if (!BSI->FunctionType.isNull()) { 13049 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13050 13051 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13052 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13053 13054 // Turn protoless block types into nullary block types. 13055 if (isa<FunctionNoProtoType>(FTy)) { 13056 FunctionProtoType::ExtProtoInfo EPI; 13057 EPI.ExtInfo = Ext; 13058 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13059 13060 // Otherwise, if we don't need to change anything about the function type, 13061 // preserve its sugar structure. 13062 } else if (FTy->getReturnType() == RetTy && 13063 (!NoReturn || FTy->getNoReturnAttr())) { 13064 BlockTy = BSI->FunctionType; 13065 13066 // Otherwise, make the minimal modifications to the function type. 13067 } else { 13068 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13069 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13070 EPI.TypeQuals = 0; // FIXME: silently? 13071 EPI.ExtInfo = Ext; 13072 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13073 } 13074 13075 // If we don't have a function type, just build one from nothing. 13076 } else { 13077 FunctionProtoType::ExtProtoInfo EPI; 13078 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13079 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13080 } 13081 13082 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13083 BlockTy = Context.getBlockPointerType(BlockTy); 13084 13085 // If needed, diagnose invalid gotos and switches in the block. 13086 if (getCurFunction()->NeedsScopeChecking() && 13087 !PP.isCodeCompletionEnabled()) 13088 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13089 13090 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13091 13092 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13093 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13094 13095 // Try to apply the named return value optimization. We have to check again 13096 // if we can do this, though, because blocks keep return statements around 13097 // to deduce an implicit return type. 13098 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13099 !BSI->TheDecl->isDependentContext()) 13100 computeNRVO(Body, BSI); 13101 13102 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13103 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13104 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13105 13106 // If the block isn't obviously global, i.e. it captures anything at 13107 // all, then we need to do a few things in the surrounding context: 13108 if (Result->getBlockDecl()->hasCaptures()) { 13109 // First, this expression has a new cleanup object. 13110 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13111 Cleanup.setExprNeedsCleanups(true); 13112 13113 // It also gets a branch-protected scope if any of the captured 13114 // variables needs destruction. 13115 for (const auto &CI : Result->getBlockDecl()->captures()) { 13116 const VarDecl *var = CI.getVariable(); 13117 if (var->getType().isDestructedType() != QualType::DK_none) { 13118 getCurFunction()->setHasBranchProtectedScope(); 13119 break; 13120 } 13121 } 13122 } 13123 13124 return Result; 13125 } 13126 13127 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13128 SourceLocation RPLoc) { 13129 TypeSourceInfo *TInfo; 13130 GetTypeFromParser(Ty, &TInfo); 13131 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13132 } 13133 13134 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13135 Expr *E, TypeSourceInfo *TInfo, 13136 SourceLocation RPLoc) { 13137 Expr *OrigExpr = E; 13138 bool IsMS = false; 13139 13140 // CUDA device code does not support varargs. 13141 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13142 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13143 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13144 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13145 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13146 } 13147 } 13148 13149 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13150 // as Microsoft ABI on an actual Microsoft platform, where 13151 // __builtin_ms_va_list and __builtin_va_list are the same.) 13152 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13153 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13154 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13155 if (Context.hasSameType(MSVaListType, E->getType())) { 13156 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13157 return ExprError(); 13158 IsMS = true; 13159 } 13160 } 13161 13162 // Get the va_list type 13163 QualType VaListType = Context.getBuiltinVaListType(); 13164 if (!IsMS) { 13165 if (VaListType->isArrayType()) { 13166 // Deal with implicit array decay; for example, on x86-64, 13167 // va_list is an array, but it's supposed to decay to 13168 // a pointer for va_arg. 13169 VaListType = Context.getArrayDecayedType(VaListType); 13170 // Make sure the input expression also decays appropriately. 13171 ExprResult Result = UsualUnaryConversions(E); 13172 if (Result.isInvalid()) 13173 return ExprError(); 13174 E = Result.get(); 13175 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13176 // If va_list is a record type and we are compiling in C++ mode, 13177 // check the argument using reference binding. 13178 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13179 Context, Context.getLValueReferenceType(VaListType), false); 13180 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13181 if (Init.isInvalid()) 13182 return ExprError(); 13183 E = Init.getAs<Expr>(); 13184 } else { 13185 // Otherwise, the va_list argument must be an l-value because 13186 // it is modified by va_arg. 13187 if (!E->isTypeDependent() && 13188 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13189 return ExprError(); 13190 } 13191 } 13192 13193 if (!IsMS && !E->isTypeDependent() && 13194 !Context.hasSameType(VaListType, E->getType())) 13195 return ExprError(Diag(E->getLocStart(), 13196 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13197 << OrigExpr->getType() << E->getSourceRange()); 13198 13199 if (!TInfo->getType()->isDependentType()) { 13200 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13201 diag::err_second_parameter_to_va_arg_incomplete, 13202 TInfo->getTypeLoc())) 13203 return ExprError(); 13204 13205 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13206 TInfo->getType(), 13207 diag::err_second_parameter_to_va_arg_abstract, 13208 TInfo->getTypeLoc())) 13209 return ExprError(); 13210 13211 if (!TInfo->getType().isPODType(Context)) { 13212 Diag(TInfo->getTypeLoc().getBeginLoc(), 13213 TInfo->getType()->isObjCLifetimeType() 13214 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13215 : diag::warn_second_parameter_to_va_arg_not_pod) 13216 << TInfo->getType() 13217 << TInfo->getTypeLoc().getSourceRange(); 13218 } 13219 13220 // Check for va_arg where arguments of the given type will be promoted 13221 // (i.e. this va_arg is guaranteed to have undefined behavior). 13222 QualType PromoteType; 13223 if (TInfo->getType()->isPromotableIntegerType()) { 13224 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13225 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13226 PromoteType = QualType(); 13227 } 13228 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13229 PromoteType = Context.DoubleTy; 13230 if (!PromoteType.isNull()) 13231 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13232 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13233 << TInfo->getType() 13234 << PromoteType 13235 << TInfo->getTypeLoc().getSourceRange()); 13236 } 13237 13238 QualType T = TInfo->getType().getNonLValueExprType(Context); 13239 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13240 } 13241 13242 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13243 // The type of __null will be int or long, depending on the size of 13244 // pointers on the target. 13245 QualType Ty; 13246 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13247 if (pw == Context.getTargetInfo().getIntWidth()) 13248 Ty = Context.IntTy; 13249 else if (pw == Context.getTargetInfo().getLongWidth()) 13250 Ty = Context.LongTy; 13251 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13252 Ty = Context.LongLongTy; 13253 else { 13254 llvm_unreachable("I don't know size of pointer!"); 13255 } 13256 13257 return new (Context) GNUNullExpr(Ty, TokenLoc); 13258 } 13259 13260 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13261 bool Diagnose) { 13262 if (!getLangOpts().ObjC1) 13263 return false; 13264 13265 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13266 if (!PT) 13267 return false; 13268 13269 if (!PT->isObjCIdType()) { 13270 // Check if the destination is the 'NSString' interface. 13271 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13272 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13273 return false; 13274 } 13275 13276 // Ignore any parens, implicit casts (should only be 13277 // array-to-pointer decays), and not-so-opaque values. The last is 13278 // important for making this trigger for property assignments. 13279 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13280 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13281 if (OV->getSourceExpr()) 13282 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13283 13284 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13285 if (!SL || !SL->isAscii()) 13286 return false; 13287 if (Diagnose) { 13288 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13289 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13290 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13291 } 13292 return true; 13293 } 13294 13295 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13296 const Expr *SrcExpr) { 13297 if (!DstType->isFunctionPointerType() || 13298 !SrcExpr->getType()->isFunctionType()) 13299 return false; 13300 13301 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13302 if (!DRE) 13303 return false; 13304 13305 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13306 if (!FD) 13307 return false; 13308 13309 return !S.checkAddressOfFunctionIsAvailable(FD, 13310 /*Complain=*/true, 13311 SrcExpr->getLocStart()); 13312 } 13313 13314 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13315 SourceLocation Loc, 13316 QualType DstType, QualType SrcType, 13317 Expr *SrcExpr, AssignmentAction Action, 13318 bool *Complained) { 13319 if (Complained) 13320 *Complained = false; 13321 13322 // Decode the result (notice that AST's are still created for extensions). 13323 bool CheckInferredResultType = false; 13324 bool isInvalid = false; 13325 unsigned DiagKind = 0; 13326 FixItHint Hint; 13327 ConversionFixItGenerator ConvHints; 13328 bool MayHaveConvFixit = false; 13329 bool MayHaveFunctionDiff = false; 13330 const ObjCInterfaceDecl *IFace = nullptr; 13331 const ObjCProtocolDecl *PDecl = nullptr; 13332 13333 switch (ConvTy) { 13334 case Compatible: 13335 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13336 return false; 13337 13338 case PointerToInt: 13339 DiagKind = diag::ext_typecheck_convert_pointer_int; 13340 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13341 MayHaveConvFixit = true; 13342 break; 13343 case IntToPointer: 13344 DiagKind = diag::ext_typecheck_convert_int_pointer; 13345 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13346 MayHaveConvFixit = true; 13347 break; 13348 case IncompatiblePointer: 13349 if (Action == AA_Passing_CFAudited) 13350 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13351 else if (SrcType->isFunctionPointerType() && 13352 DstType->isFunctionPointerType()) 13353 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13354 else 13355 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13356 13357 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13358 SrcType->isObjCObjectPointerType(); 13359 if (Hint.isNull() && !CheckInferredResultType) { 13360 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13361 } 13362 else if (CheckInferredResultType) { 13363 SrcType = SrcType.getUnqualifiedType(); 13364 DstType = DstType.getUnqualifiedType(); 13365 } 13366 MayHaveConvFixit = true; 13367 break; 13368 case IncompatiblePointerSign: 13369 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13370 break; 13371 case FunctionVoidPointer: 13372 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13373 break; 13374 case IncompatiblePointerDiscardsQualifiers: { 13375 // Perform array-to-pointer decay if necessary. 13376 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13377 13378 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13379 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13380 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13381 DiagKind = diag::err_typecheck_incompatible_address_space; 13382 break; 13383 13384 13385 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13386 DiagKind = diag::err_typecheck_incompatible_ownership; 13387 break; 13388 } 13389 13390 llvm_unreachable("unknown error case for discarding qualifiers!"); 13391 // fallthrough 13392 } 13393 case CompatiblePointerDiscardsQualifiers: 13394 // If the qualifiers lost were because we were applying the 13395 // (deprecated) C++ conversion from a string literal to a char* 13396 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13397 // Ideally, this check would be performed in 13398 // checkPointerTypesForAssignment. However, that would require a 13399 // bit of refactoring (so that the second argument is an 13400 // expression, rather than a type), which should be done as part 13401 // of a larger effort to fix checkPointerTypesForAssignment for 13402 // C++ semantics. 13403 if (getLangOpts().CPlusPlus && 13404 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13405 return false; 13406 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13407 break; 13408 case IncompatibleNestedPointerQualifiers: 13409 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13410 break; 13411 case IntToBlockPointer: 13412 DiagKind = diag::err_int_to_block_pointer; 13413 break; 13414 case IncompatibleBlockPointer: 13415 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13416 break; 13417 case IncompatibleObjCQualifiedId: { 13418 if (SrcType->isObjCQualifiedIdType()) { 13419 const ObjCObjectPointerType *srcOPT = 13420 SrcType->getAs<ObjCObjectPointerType>(); 13421 for (auto *srcProto : srcOPT->quals()) { 13422 PDecl = srcProto; 13423 break; 13424 } 13425 if (const ObjCInterfaceType *IFaceT = 13426 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13427 IFace = IFaceT->getDecl(); 13428 } 13429 else if (DstType->isObjCQualifiedIdType()) { 13430 const ObjCObjectPointerType *dstOPT = 13431 DstType->getAs<ObjCObjectPointerType>(); 13432 for (auto *dstProto : dstOPT->quals()) { 13433 PDecl = dstProto; 13434 break; 13435 } 13436 if (const ObjCInterfaceType *IFaceT = 13437 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13438 IFace = IFaceT->getDecl(); 13439 } 13440 DiagKind = diag::warn_incompatible_qualified_id; 13441 break; 13442 } 13443 case IncompatibleVectors: 13444 DiagKind = diag::warn_incompatible_vectors; 13445 break; 13446 case IncompatibleObjCWeakRef: 13447 DiagKind = diag::err_arc_weak_unavailable_assign; 13448 break; 13449 case Incompatible: 13450 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13451 if (Complained) 13452 *Complained = true; 13453 return true; 13454 } 13455 13456 DiagKind = diag::err_typecheck_convert_incompatible; 13457 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13458 MayHaveConvFixit = true; 13459 isInvalid = true; 13460 MayHaveFunctionDiff = true; 13461 break; 13462 } 13463 13464 QualType FirstType, SecondType; 13465 switch (Action) { 13466 case AA_Assigning: 13467 case AA_Initializing: 13468 // The destination type comes first. 13469 FirstType = DstType; 13470 SecondType = SrcType; 13471 break; 13472 13473 case AA_Returning: 13474 case AA_Passing: 13475 case AA_Passing_CFAudited: 13476 case AA_Converting: 13477 case AA_Sending: 13478 case AA_Casting: 13479 // The source type comes first. 13480 FirstType = SrcType; 13481 SecondType = DstType; 13482 break; 13483 } 13484 13485 PartialDiagnostic FDiag = PDiag(DiagKind); 13486 if (Action == AA_Passing_CFAudited) 13487 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13488 else 13489 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13490 13491 // If we can fix the conversion, suggest the FixIts. 13492 assert(ConvHints.isNull() || Hint.isNull()); 13493 if (!ConvHints.isNull()) { 13494 for (FixItHint &H : ConvHints.Hints) 13495 FDiag << H; 13496 } else { 13497 FDiag << Hint; 13498 } 13499 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13500 13501 if (MayHaveFunctionDiff) 13502 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13503 13504 Diag(Loc, FDiag); 13505 if (DiagKind == diag::warn_incompatible_qualified_id && 13506 PDecl && IFace && !IFace->hasDefinition()) 13507 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13508 << IFace->getName() << PDecl->getName(); 13509 13510 if (SecondType == Context.OverloadTy) 13511 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13512 FirstType, /*TakingAddress=*/true); 13513 13514 if (CheckInferredResultType) 13515 EmitRelatedResultTypeNote(SrcExpr); 13516 13517 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13518 EmitRelatedResultTypeNoteForReturn(DstType); 13519 13520 if (Complained) 13521 *Complained = true; 13522 return isInvalid; 13523 } 13524 13525 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13526 llvm::APSInt *Result) { 13527 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13528 public: 13529 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13530 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13531 } 13532 } Diagnoser; 13533 13534 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13535 } 13536 13537 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13538 llvm::APSInt *Result, 13539 unsigned DiagID, 13540 bool AllowFold) { 13541 class IDDiagnoser : public VerifyICEDiagnoser { 13542 unsigned DiagID; 13543 13544 public: 13545 IDDiagnoser(unsigned DiagID) 13546 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13547 13548 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13549 S.Diag(Loc, DiagID) << SR; 13550 } 13551 } Diagnoser(DiagID); 13552 13553 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13554 } 13555 13556 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13557 SourceRange SR) { 13558 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13559 } 13560 13561 ExprResult 13562 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13563 VerifyICEDiagnoser &Diagnoser, 13564 bool AllowFold) { 13565 SourceLocation DiagLoc = E->getLocStart(); 13566 13567 if (getLangOpts().CPlusPlus11) { 13568 // C++11 [expr.const]p5: 13569 // If an expression of literal class type is used in a context where an 13570 // integral constant expression is required, then that class type shall 13571 // have a single non-explicit conversion function to an integral or 13572 // unscoped enumeration type 13573 ExprResult Converted; 13574 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13575 public: 13576 CXX11ConvertDiagnoser(bool Silent) 13577 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13578 Silent, true) {} 13579 13580 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13581 QualType T) override { 13582 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13583 } 13584 13585 SemaDiagnosticBuilder diagnoseIncomplete( 13586 Sema &S, SourceLocation Loc, QualType T) override { 13587 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13588 } 13589 13590 SemaDiagnosticBuilder diagnoseExplicitConv( 13591 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13592 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13593 } 13594 13595 SemaDiagnosticBuilder noteExplicitConv( 13596 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13597 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13598 << ConvTy->isEnumeralType() << ConvTy; 13599 } 13600 13601 SemaDiagnosticBuilder diagnoseAmbiguous( 13602 Sema &S, SourceLocation Loc, QualType T) override { 13603 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13604 } 13605 13606 SemaDiagnosticBuilder noteAmbiguous( 13607 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13608 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13609 << ConvTy->isEnumeralType() << ConvTy; 13610 } 13611 13612 SemaDiagnosticBuilder diagnoseConversion( 13613 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13614 llvm_unreachable("conversion functions are permitted"); 13615 } 13616 } ConvertDiagnoser(Diagnoser.Suppress); 13617 13618 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13619 ConvertDiagnoser); 13620 if (Converted.isInvalid()) 13621 return Converted; 13622 E = Converted.get(); 13623 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13624 return ExprError(); 13625 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13626 // An ICE must be of integral or unscoped enumeration type. 13627 if (!Diagnoser.Suppress) 13628 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13629 return ExprError(); 13630 } 13631 13632 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13633 // in the non-ICE case. 13634 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13635 if (Result) 13636 *Result = E->EvaluateKnownConstInt(Context); 13637 return E; 13638 } 13639 13640 Expr::EvalResult EvalResult; 13641 SmallVector<PartialDiagnosticAt, 8> Notes; 13642 EvalResult.Diag = &Notes; 13643 13644 // Try to evaluate the expression, and produce diagnostics explaining why it's 13645 // not a constant expression as a side-effect. 13646 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13647 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13648 13649 // In C++11, we can rely on diagnostics being produced for any expression 13650 // which is not a constant expression. If no diagnostics were produced, then 13651 // this is a constant expression. 13652 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13653 if (Result) 13654 *Result = EvalResult.Val.getInt(); 13655 return E; 13656 } 13657 13658 // If our only note is the usual "invalid subexpression" note, just point 13659 // the caret at its location rather than producing an essentially 13660 // redundant note. 13661 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13662 diag::note_invalid_subexpr_in_const_expr) { 13663 DiagLoc = Notes[0].first; 13664 Notes.clear(); 13665 } 13666 13667 if (!Folded || !AllowFold) { 13668 if (!Diagnoser.Suppress) { 13669 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13670 for (const PartialDiagnosticAt &Note : Notes) 13671 Diag(Note.first, Note.second); 13672 } 13673 13674 return ExprError(); 13675 } 13676 13677 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13678 for (const PartialDiagnosticAt &Note : Notes) 13679 Diag(Note.first, Note.second); 13680 13681 if (Result) 13682 *Result = EvalResult.Val.getInt(); 13683 return E; 13684 } 13685 13686 namespace { 13687 // Handle the case where we conclude a expression which we speculatively 13688 // considered to be unevaluated is actually evaluated. 13689 class TransformToPE : public TreeTransform<TransformToPE> { 13690 typedef TreeTransform<TransformToPE> BaseTransform; 13691 13692 public: 13693 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13694 13695 // Make sure we redo semantic analysis 13696 bool AlwaysRebuild() { return true; } 13697 13698 // Make sure we handle LabelStmts correctly. 13699 // FIXME: This does the right thing, but maybe we need a more general 13700 // fix to TreeTransform? 13701 StmtResult TransformLabelStmt(LabelStmt *S) { 13702 S->getDecl()->setStmt(nullptr); 13703 return BaseTransform::TransformLabelStmt(S); 13704 } 13705 13706 // We need to special-case DeclRefExprs referring to FieldDecls which 13707 // are not part of a member pointer formation; normal TreeTransforming 13708 // doesn't catch this case because of the way we represent them in the AST. 13709 // FIXME: This is a bit ugly; is it really the best way to handle this 13710 // case? 13711 // 13712 // Error on DeclRefExprs referring to FieldDecls. 13713 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13714 if (isa<FieldDecl>(E->getDecl()) && 13715 !SemaRef.isUnevaluatedContext()) 13716 return SemaRef.Diag(E->getLocation(), 13717 diag::err_invalid_non_static_member_use) 13718 << E->getDecl() << E->getSourceRange(); 13719 13720 return BaseTransform::TransformDeclRefExpr(E); 13721 } 13722 13723 // Exception: filter out member pointer formation 13724 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13725 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13726 return E; 13727 13728 return BaseTransform::TransformUnaryOperator(E); 13729 } 13730 13731 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13732 // Lambdas never need to be transformed. 13733 return E; 13734 } 13735 }; 13736 } 13737 13738 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13739 assert(isUnevaluatedContext() && 13740 "Should only transform unevaluated expressions"); 13741 ExprEvalContexts.back().Context = 13742 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13743 if (isUnevaluatedContext()) 13744 return E; 13745 return TransformToPE(*this).TransformExpr(E); 13746 } 13747 13748 void 13749 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13750 Decl *LambdaContextDecl, 13751 bool IsDecltype) { 13752 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13753 LambdaContextDecl, IsDecltype); 13754 Cleanup.reset(); 13755 if (!MaybeODRUseExprs.empty()) 13756 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13757 } 13758 13759 void 13760 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13761 ReuseLambdaContextDecl_t, 13762 bool IsDecltype) { 13763 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13764 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13765 } 13766 13767 void Sema::PopExpressionEvaluationContext() { 13768 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13769 unsigned NumTypos = Rec.NumTypos; 13770 13771 if (!Rec.Lambdas.empty()) { 13772 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13773 unsigned D; 13774 if (Rec.isUnevaluated()) { 13775 // C++11 [expr.prim.lambda]p2: 13776 // A lambda-expression shall not appear in an unevaluated operand 13777 // (Clause 5). 13778 D = diag::err_lambda_unevaluated_operand; 13779 } else { 13780 // C++1y [expr.const]p2: 13781 // A conditional-expression e is a core constant expression unless the 13782 // evaluation of e, following the rules of the abstract machine, would 13783 // evaluate [...] a lambda-expression. 13784 D = diag::err_lambda_in_constant_expression; 13785 } 13786 13787 // C++1z allows lambda expressions as core constant expressions. 13788 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13789 // 1607) from appearing within template-arguments and array-bounds that 13790 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13791 // unevaluated contexts) might lift some of these restrictions in a 13792 // future version. 13793 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) 13794 for (const auto *L : Rec.Lambdas) 13795 Diag(L->getLocStart(), D); 13796 } else { 13797 // Mark the capture expressions odr-used. This was deferred 13798 // during lambda expression creation. 13799 for (auto *Lambda : Rec.Lambdas) { 13800 for (auto *C : Lambda->capture_inits()) 13801 MarkDeclarationsReferencedInExpr(C); 13802 } 13803 } 13804 } 13805 13806 // When are coming out of an unevaluated context, clear out any 13807 // temporaries that we may have created as part of the evaluation of 13808 // the expression in that context: they aren't relevant because they 13809 // will never be constructed. 13810 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13811 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13812 ExprCleanupObjects.end()); 13813 Cleanup = Rec.ParentCleanup; 13814 CleanupVarDeclMarking(); 13815 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13816 // Otherwise, merge the contexts together. 13817 } else { 13818 Cleanup.mergeFrom(Rec.ParentCleanup); 13819 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13820 Rec.SavedMaybeODRUseExprs.end()); 13821 } 13822 13823 // Pop the current expression evaluation context off the stack. 13824 ExprEvalContexts.pop_back(); 13825 13826 if (!ExprEvalContexts.empty()) 13827 ExprEvalContexts.back().NumTypos += NumTypos; 13828 else 13829 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13830 "last ExpressionEvaluationContextRecord"); 13831 } 13832 13833 void Sema::DiscardCleanupsInEvaluationContext() { 13834 ExprCleanupObjects.erase( 13835 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13836 ExprCleanupObjects.end()); 13837 Cleanup.reset(); 13838 MaybeODRUseExprs.clear(); 13839 } 13840 13841 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13842 if (!E->getType()->isVariablyModifiedType()) 13843 return E; 13844 return TransformToPotentiallyEvaluated(E); 13845 } 13846 13847 /// Are we within a context in which some evaluation could be performed (be it 13848 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13849 /// captured by C++'s idea of an "unevaluated context". 13850 static bool isEvaluatableContext(Sema &SemaRef) { 13851 switch (SemaRef.ExprEvalContexts.back().Context) { 13852 case Sema::ExpressionEvaluationContext::Unevaluated: 13853 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13854 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13855 // Expressions in this context are never evaluated. 13856 return false; 13857 13858 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13859 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13860 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13861 // Expressions in this context could be evaluated. 13862 return true; 13863 13864 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13865 // Referenced declarations will only be used if the construct in the 13866 // containing expression is used, at which point we'll be given another 13867 // turn to mark them. 13868 return false; 13869 } 13870 llvm_unreachable("Invalid context"); 13871 } 13872 13873 /// Are we within a context in which references to resolved functions or to 13874 /// variables result in odr-use? 13875 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13876 // An expression in a template is not really an expression until it's been 13877 // instantiated, so it doesn't trigger odr-use. 13878 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13879 return false; 13880 13881 switch (SemaRef.ExprEvalContexts.back().Context) { 13882 case Sema::ExpressionEvaluationContext::Unevaluated: 13883 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13884 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13885 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13886 return false; 13887 13888 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13889 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13890 return true; 13891 13892 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13893 return false; 13894 } 13895 llvm_unreachable("Invalid context"); 13896 } 13897 13898 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13899 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13900 return Func->isConstexpr() && 13901 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13902 } 13903 13904 /// \brief Mark a function referenced, and check whether it is odr-used 13905 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13906 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13907 bool MightBeOdrUse) { 13908 assert(Func && "No function?"); 13909 13910 Func->setReferenced(); 13911 13912 // C++11 [basic.def.odr]p3: 13913 // A function whose name appears as a potentially-evaluated expression is 13914 // odr-used if it is the unique lookup result or the selected member of a 13915 // set of overloaded functions [...]. 13916 // 13917 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13918 // can just check that here. 13919 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13920 13921 // Determine whether we require a function definition to exist, per 13922 // C++11 [temp.inst]p3: 13923 // Unless a function template specialization has been explicitly 13924 // instantiated or explicitly specialized, the function template 13925 // specialization is implicitly instantiated when the specialization is 13926 // referenced in a context that requires a function definition to exist. 13927 // 13928 // That is either when this is an odr-use, or when a usage of a constexpr 13929 // function occurs within an evaluatable context. 13930 bool NeedDefinition = 13931 OdrUse || (isEvaluatableContext(*this) && 13932 isImplicitlyDefinableConstexprFunction(Func)); 13933 13934 // C++14 [temp.expl.spec]p6: 13935 // If a template [...] is explicitly specialized then that specialization 13936 // shall be declared before the first use of that specialization that would 13937 // cause an implicit instantiation to take place, in every translation unit 13938 // in which such a use occurs 13939 if (NeedDefinition && 13940 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13941 Func->getMemberSpecializationInfo())) 13942 checkSpecializationVisibility(Loc, Func); 13943 13944 // C++14 [except.spec]p17: 13945 // An exception-specification is considered to be needed when: 13946 // - the function is odr-used or, if it appears in an unevaluated operand, 13947 // would be odr-used if the expression were potentially-evaluated; 13948 // 13949 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13950 // function is a pure virtual function we're calling, and in that case the 13951 // function was selected by overload resolution and we need to resolve its 13952 // exception specification for a different reason. 13953 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13954 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13955 ResolveExceptionSpec(Loc, FPT); 13956 13957 // If we don't need to mark the function as used, and we don't need to 13958 // try to provide a definition, there's nothing more to do. 13959 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13960 (!NeedDefinition || Func->getBody())) 13961 return; 13962 13963 // Note that this declaration has been used. 13964 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13965 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13966 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13967 if (Constructor->isDefaultConstructor()) { 13968 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13969 return; 13970 DefineImplicitDefaultConstructor(Loc, Constructor); 13971 } else if (Constructor->isCopyConstructor()) { 13972 DefineImplicitCopyConstructor(Loc, Constructor); 13973 } else if (Constructor->isMoveConstructor()) { 13974 DefineImplicitMoveConstructor(Loc, Constructor); 13975 } 13976 } else if (Constructor->getInheritedConstructor()) { 13977 DefineInheritingConstructor(Loc, Constructor); 13978 } 13979 } else if (CXXDestructorDecl *Destructor = 13980 dyn_cast<CXXDestructorDecl>(Func)) { 13981 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13982 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13983 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13984 return; 13985 DefineImplicitDestructor(Loc, Destructor); 13986 } 13987 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13988 MarkVTableUsed(Loc, Destructor->getParent()); 13989 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13990 if (MethodDecl->isOverloadedOperator() && 13991 MethodDecl->getOverloadedOperator() == OO_Equal) { 13992 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13993 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13994 if (MethodDecl->isCopyAssignmentOperator()) 13995 DefineImplicitCopyAssignment(Loc, MethodDecl); 13996 else if (MethodDecl->isMoveAssignmentOperator()) 13997 DefineImplicitMoveAssignment(Loc, MethodDecl); 13998 } 13999 } else if (isa<CXXConversionDecl>(MethodDecl) && 14000 MethodDecl->getParent()->isLambda()) { 14001 CXXConversionDecl *Conversion = 14002 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14003 if (Conversion->isLambdaToBlockPointerConversion()) 14004 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14005 else 14006 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14007 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14008 MarkVTableUsed(Loc, MethodDecl->getParent()); 14009 } 14010 14011 // Recursive functions should be marked when used from another function. 14012 // FIXME: Is this really right? 14013 if (CurContext == Func) return; 14014 14015 // Implicit instantiation of function templates and member functions of 14016 // class templates. 14017 if (Func->isImplicitlyInstantiable()) { 14018 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14019 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14020 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14021 if (FirstInstantiation) { 14022 PointOfInstantiation = Loc; 14023 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14024 } else if (TSK != TSK_ImplicitInstantiation) { 14025 // Use the point of use as the point of instantiation, instead of the 14026 // point of explicit instantiation (which we track as the actual point of 14027 // instantiation). This gives better backtraces in diagnostics. 14028 PointOfInstantiation = Loc; 14029 } 14030 14031 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14032 Func->isConstexpr()) { 14033 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14034 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14035 CodeSynthesisContexts.size()) 14036 PendingLocalImplicitInstantiations.push_back( 14037 std::make_pair(Func, PointOfInstantiation)); 14038 else if (Func->isConstexpr()) 14039 // Do not defer instantiations of constexpr functions, to avoid the 14040 // expression evaluator needing to call back into Sema if it sees a 14041 // call to such a function. 14042 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14043 else { 14044 Func->setInstantiationIsPending(true); 14045 PendingInstantiations.push_back(std::make_pair(Func, 14046 PointOfInstantiation)); 14047 // Notify the consumer that a function was implicitly instantiated. 14048 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14049 } 14050 } 14051 } else { 14052 // Walk redefinitions, as some of them may be instantiable. 14053 for (auto i : Func->redecls()) { 14054 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14055 MarkFunctionReferenced(Loc, i, OdrUse); 14056 } 14057 } 14058 14059 if (!OdrUse) return; 14060 14061 // Keep track of used but undefined functions. 14062 if (!Func->isDefined()) { 14063 if (mightHaveNonExternalLinkage(Func)) 14064 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14065 else if (Func->getMostRecentDecl()->isInlined() && 14066 !LangOpts.GNUInline && 14067 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14068 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14069 else if (isExternalWithNoLinkageType(Func)) 14070 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14071 } 14072 14073 Func->markUsed(Context); 14074 } 14075 14076 static void 14077 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14078 ValueDecl *var, DeclContext *DC) { 14079 DeclContext *VarDC = var->getDeclContext(); 14080 14081 // If the parameter still belongs to the translation unit, then 14082 // we're actually just using one parameter in the declaration of 14083 // the next. 14084 if (isa<ParmVarDecl>(var) && 14085 isa<TranslationUnitDecl>(VarDC)) 14086 return; 14087 14088 // For C code, don't diagnose about capture if we're not actually in code 14089 // right now; it's impossible to write a non-constant expression outside of 14090 // function context, so we'll get other (more useful) diagnostics later. 14091 // 14092 // For C++, things get a bit more nasty... it would be nice to suppress this 14093 // diagnostic for certain cases like using a local variable in an array bound 14094 // for a member of a local class, but the correct predicate is not obvious. 14095 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14096 return; 14097 14098 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14099 unsigned ContextKind = 3; // unknown 14100 if (isa<CXXMethodDecl>(VarDC) && 14101 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14102 ContextKind = 2; 14103 } else if (isa<FunctionDecl>(VarDC)) { 14104 ContextKind = 0; 14105 } else if (isa<BlockDecl>(VarDC)) { 14106 ContextKind = 1; 14107 } 14108 14109 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14110 << var << ValueKind << ContextKind << VarDC; 14111 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14112 << var; 14113 14114 // FIXME: Add additional diagnostic info about class etc. which prevents 14115 // capture. 14116 } 14117 14118 14119 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14120 bool &SubCapturesAreNested, 14121 QualType &CaptureType, 14122 QualType &DeclRefType) { 14123 // Check whether we've already captured it. 14124 if (CSI->CaptureMap.count(Var)) { 14125 // If we found a capture, any subcaptures are nested. 14126 SubCapturesAreNested = true; 14127 14128 // Retrieve the capture type for this variable. 14129 CaptureType = CSI->getCapture(Var).getCaptureType(); 14130 14131 // Compute the type of an expression that refers to this variable. 14132 DeclRefType = CaptureType.getNonReferenceType(); 14133 14134 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14135 // are mutable in the sense that user can change their value - they are 14136 // private instances of the captured declarations. 14137 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 14138 if (Cap.isCopyCapture() && 14139 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14140 !(isa<CapturedRegionScopeInfo>(CSI) && 14141 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14142 DeclRefType.addConst(); 14143 return true; 14144 } 14145 return false; 14146 } 14147 14148 // Only block literals, captured statements, and lambda expressions can 14149 // capture; other scopes don't work. 14150 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14151 SourceLocation Loc, 14152 const bool Diagnose, Sema &S) { 14153 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14154 return getLambdaAwareParentOfDeclContext(DC); 14155 else if (Var->hasLocalStorage()) { 14156 if (Diagnose) 14157 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14158 } 14159 return nullptr; 14160 } 14161 14162 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14163 // certain types of variables (unnamed, variably modified types etc.) 14164 // so check for eligibility. 14165 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14166 SourceLocation Loc, 14167 const bool Diagnose, Sema &S) { 14168 14169 bool IsBlock = isa<BlockScopeInfo>(CSI); 14170 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14171 14172 // Lambdas are not allowed to capture unnamed variables 14173 // (e.g. anonymous unions). 14174 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14175 // assuming that's the intent. 14176 if (IsLambda && !Var->getDeclName()) { 14177 if (Diagnose) { 14178 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14179 S.Diag(Var->getLocation(), diag::note_declared_at); 14180 } 14181 return false; 14182 } 14183 14184 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14185 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14186 if (Diagnose) { 14187 S.Diag(Loc, diag::err_ref_vm_type); 14188 S.Diag(Var->getLocation(), diag::note_previous_decl) 14189 << Var->getDeclName(); 14190 } 14191 return false; 14192 } 14193 // Prohibit structs with flexible array members too. 14194 // We cannot capture what is in the tail end of the struct. 14195 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14196 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14197 if (Diagnose) { 14198 if (IsBlock) 14199 S.Diag(Loc, diag::err_ref_flexarray_type); 14200 else 14201 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14202 << Var->getDeclName(); 14203 S.Diag(Var->getLocation(), diag::note_previous_decl) 14204 << Var->getDeclName(); 14205 } 14206 return false; 14207 } 14208 } 14209 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14210 // Lambdas and captured statements are not allowed to capture __block 14211 // variables; they don't support the expected semantics. 14212 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14213 if (Diagnose) { 14214 S.Diag(Loc, diag::err_capture_block_variable) 14215 << Var->getDeclName() << !IsLambda; 14216 S.Diag(Var->getLocation(), diag::note_previous_decl) 14217 << Var->getDeclName(); 14218 } 14219 return false; 14220 } 14221 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14222 if (S.getLangOpts().OpenCL && IsBlock && 14223 Var->getType()->isBlockPointerType()) { 14224 if (Diagnose) 14225 S.Diag(Loc, diag::err_opencl_block_ref_block); 14226 return false; 14227 } 14228 14229 return true; 14230 } 14231 14232 // Returns true if the capture by block was successful. 14233 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14234 SourceLocation Loc, 14235 const bool BuildAndDiagnose, 14236 QualType &CaptureType, 14237 QualType &DeclRefType, 14238 const bool Nested, 14239 Sema &S) { 14240 Expr *CopyExpr = nullptr; 14241 bool ByRef = false; 14242 14243 // Blocks are not allowed to capture arrays. 14244 if (CaptureType->isArrayType()) { 14245 if (BuildAndDiagnose) { 14246 S.Diag(Loc, diag::err_ref_array_type); 14247 S.Diag(Var->getLocation(), diag::note_previous_decl) 14248 << Var->getDeclName(); 14249 } 14250 return false; 14251 } 14252 14253 // Forbid the block-capture of autoreleasing variables. 14254 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14255 if (BuildAndDiagnose) { 14256 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14257 << /*block*/ 0; 14258 S.Diag(Var->getLocation(), diag::note_previous_decl) 14259 << Var->getDeclName(); 14260 } 14261 return false; 14262 } 14263 14264 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14265 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14266 // This function finds out whether there is an AttributedType of kind 14267 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14268 // attr_objc_ownership implies __autoreleasing was explicitly specified 14269 // rather than being added implicitly by the compiler. 14270 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14271 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14272 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14273 return true; 14274 14275 // Peel off AttributedTypes that are not of kind objc_ownership. 14276 Ty = AttrTy->getModifiedType(); 14277 } 14278 14279 return false; 14280 }; 14281 14282 QualType PointeeTy = PT->getPointeeType(); 14283 14284 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14285 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14286 !IsObjCOwnershipAttributedType(PointeeTy)) { 14287 if (BuildAndDiagnose) { 14288 SourceLocation VarLoc = Var->getLocation(); 14289 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14290 { 14291 auto AddAutoreleaseNote = 14292 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14293 // Provide a fix-it for the '__autoreleasing' keyword at the 14294 // appropriate location in the variable's type. 14295 if (const auto *TSI = Var->getTypeSourceInfo()) { 14296 PointerTypeLoc PTL = 14297 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14298 if (PTL) { 14299 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14300 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14301 S.getLangOpts()); 14302 if (Loc.isValid()) { 14303 StringRef CharAtLoc = Lexer::getSourceText( 14304 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14305 S.getSourceManager(), S.getLangOpts()); 14306 AddAutoreleaseNote << FixItHint::CreateInsertion( 14307 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14308 ? " __autoreleasing " 14309 : " __autoreleasing"); 14310 } 14311 } 14312 } 14313 } 14314 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14315 } 14316 } 14317 } 14318 14319 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14320 if (HasBlocksAttr || CaptureType->isReferenceType() || 14321 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14322 // Block capture by reference does not change the capture or 14323 // declaration reference types. 14324 ByRef = true; 14325 } else { 14326 // Block capture by copy introduces 'const'. 14327 CaptureType = CaptureType.getNonReferenceType().withConst(); 14328 DeclRefType = CaptureType; 14329 14330 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14331 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14332 // The capture logic needs the destructor, so make sure we mark it. 14333 // Usually this is unnecessary because most local variables have 14334 // their destructors marked at declaration time, but parameters are 14335 // an exception because it's technically only the call site that 14336 // actually requires the destructor. 14337 if (isa<ParmVarDecl>(Var)) 14338 S.FinalizeVarWithDestructor(Var, Record); 14339 14340 // Enter a new evaluation context to insulate the copy 14341 // full-expression. 14342 EnterExpressionEvaluationContext scope( 14343 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14344 14345 // According to the blocks spec, the capture of a variable from 14346 // the stack requires a const copy constructor. This is not true 14347 // of the copy/move done to move a __block variable to the heap. 14348 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14349 DeclRefType.withConst(), 14350 VK_LValue, Loc); 14351 14352 ExprResult Result 14353 = S.PerformCopyInitialization( 14354 InitializedEntity::InitializeBlock(Var->getLocation(), 14355 CaptureType, false), 14356 Loc, DeclRef); 14357 14358 // Build a full-expression copy expression if initialization 14359 // succeeded and used a non-trivial constructor. Recover from 14360 // errors by pretending that the copy isn't necessary. 14361 if (!Result.isInvalid() && 14362 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14363 ->isTrivial()) { 14364 Result = S.MaybeCreateExprWithCleanups(Result); 14365 CopyExpr = Result.get(); 14366 } 14367 } 14368 } 14369 } 14370 14371 // Actually capture the variable. 14372 if (BuildAndDiagnose) 14373 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14374 SourceLocation(), CaptureType, CopyExpr); 14375 14376 return true; 14377 14378 } 14379 14380 14381 /// \brief Capture the given variable in the captured region. 14382 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14383 VarDecl *Var, 14384 SourceLocation Loc, 14385 const bool BuildAndDiagnose, 14386 QualType &CaptureType, 14387 QualType &DeclRefType, 14388 const bool RefersToCapturedVariable, 14389 Sema &S) { 14390 // By default, capture variables by reference. 14391 bool ByRef = true; 14392 // Using an LValue reference type is consistent with Lambdas (see below). 14393 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14394 if (S.IsOpenMPCapturedDecl(Var)) { 14395 bool HasConst = DeclRefType.isConstQualified(); 14396 DeclRefType = DeclRefType.getUnqualifiedType(); 14397 // Don't lose diagnostics about assignments to const. 14398 if (HasConst) 14399 DeclRefType.addConst(); 14400 } 14401 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14402 } 14403 14404 if (ByRef) 14405 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14406 else 14407 CaptureType = DeclRefType; 14408 14409 Expr *CopyExpr = nullptr; 14410 if (BuildAndDiagnose) { 14411 // The current implementation assumes that all variables are captured 14412 // by references. Since there is no capture by copy, no expression 14413 // evaluation will be needed. 14414 RecordDecl *RD = RSI->TheRecordDecl; 14415 14416 FieldDecl *Field 14417 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14418 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14419 nullptr, false, ICIS_NoInit); 14420 Field->setImplicit(true); 14421 Field->setAccess(AS_private); 14422 RD->addDecl(Field); 14423 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14424 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14425 14426 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14427 DeclRefType, VK_LValue, Loc); 14428 Var->setReferenced(true); 14429 Var->markUsed(S.Context); 14430 } 14431 14432 // Actually capture the variable. 14433 if (BuildAndDiagnose) 14434 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14435 SourceLocation(), CaptureType, CopyExpr); 14436 14437 14438 return true; 14439 } 14440 14441 /// \brief Create a field within the lambda class for the variable 14442 /// being captured. 14443 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14444 QualType FieldType, QualType DeclRefType, 14445 SourceLocation Loc, 14446 bool RefersToCapturedVariable) { 14447 CXXRecordDecl *Lambda = LSI->Lambda; 14448 14449 // Build the non-static data member. 14450 FieldDecl *Field 14451 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14452 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14453 nullptr, false, ICIS_NoInit); 14454 Field->setImplicit(true); 14455 Field->setAccess(AS_private); 14456 Lambda->addDecl(Field); 14457 } 14458 14459 /// \brief Capture the given variable in the lambda. 14460 static bool captureInLambda(LambdaScopeInfo *LSI, 14461 VarDecl *Var, 14462 SourceLocation Loc, 14463 const bool BuildAndDiagnose, 14464 QualType &CaptureType, 14465 QualType &DeclRefType, 14466 const bool RefersToCapturedVariable, 14467 const Sema::TryCaptureKind Kind, 14468 SourceLocation EllipsisLoc, 14469 const bool IsTopScope, 14470 Sema &S) { 14471 14472 // Determine whether we are capturing by reference or by value. 14473 bool ByRef = false; 14474 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14475 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14476 } else { 14477 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14478 } 14479 14480 // Compute the type of the field that will capture this variable. 14481 if (ByRef) { 14482 // C++11 [expr.prim.lambda]p15: 14483 // An entity is captured by reference if it is implicitly or 14484 // explicitly captured but not captured by copy. It is 14485 // unspecified whether additional unnamed non-static data 14486 // members are declared in the closure type for entities 14487 // captured by reference. 14488 // 14489 // FIXME: It is not clear whether we want to build an lvalue reference 14490 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14491 // to do the former, while EDG does the latter. Core issue 1249 will 14492 // clarify, but for now we follow GCC because it's a more permissive and 14493 // easily defensible position. 14494 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14495 } else { 14496 // C++11 [expr.prim.lambda]p14: 14497 // For each entity captured by copy, an unnamed non-static 14498 // data member is declared in the closure type. The 14499 // declaration order of these members is unspecified. The type 14500 // of such a data member is the type of the corresponding 14501 // captured entity if the entity is not a reference to an 14502 // object, or the referenced type otherwise. [Note: If the 14503 // captured entity is a reference to a function, the 14504 // corresponding data member is also a reference to a 14505 // function. - end note ] 14506 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14507 if (!RefType->getPointeeType()->isFunctionType()) 14508 CaptureType = RefType->getPointeeType(); 14509 } 14510 14511 // Forbid the lambda copy-capture of autoreleasing variables. 14512 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14513 if (BuildAndDiagnose) { 14514 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14515 S.Diag(Var->getLocation(), diag::note_previous_decl) 14516 << Var->getDeclName(); 14517 } 14518 return false; 14519 } 14520 14521 // Make sure that by-copy captures are of a complete and non-abstract type. 14522 if (BuildAndDiagnose) { 14523 if (!CaptureType->isDependentType() && 14524 S.RequireCompleteType(Loc, CaptureType, 14525 diag::err_capture_of_incomplete_type, 14526 Var->getDeclName())) 14527 return false; 14528 14529 if (S.RequireNonAbstractType(Loc, CaptureType, 14530 diag::err_capture_of_abstract_type)) 14531 return false; 14532 } 14533 } 14534 14535 // Capture this variable in the lambda. 14536 if (BuildAndDiagnose) 14537 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14538 RefersToCapturedVariable); 14539 14540 // Compute the type of a reference to this captured variable. 14541 if (ByRef) 14542 DeclRefType = CaptureType.getNonReferenceType(); 14543 else { 14544 // C++ [expr.prim.lambda]p5: 14545 // The closure type for a lambda-expression has a public inline 14546 // function call operator [...]. This function call operator is 14547 // declared const (9.3.1) if and only if the lambda-expression's 14548 // parameter-declaration-clause is not followed by mutable. 14549 DeclRefType = CaptureType.getNonReferenceType(); 14550 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14551 DeclRefType.addConst(); 14552 } 14553 14554 // Add the capture. 14555 if (BuildAndDiagnose) 14556 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14557 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14558 14559 return true; 14560 } 14561 14562 bool Sema::tryCaptureVariable( 14563 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14564 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14565 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14566 // An init-capture is notionally from the context surrounding its 14567 // declaration, but its parent DC is the lambda class. 14568 DeclContext *VarDC = Var->getDeclContext(); 14569 if (Var->isInitCapture()) 14570 VarDC = VarDC->getParent(); 14571 14572 DeclContext *DC = CurContext; 14573 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14574 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14575 // We need to sync up the Declaration Context with the 14576 // FunctionScopeIndexToStopAt 14577 if (FunctionScopeIndexToStopAt) { 14578 unsigned FSIndex = FunctionScopes.size() - 1; 14579 while (FSIndex != MaxFunctionScopesIndex) { 14580 DC = getLambdaAwareParentOfDeclContext(DC); 14581 --FSIndex; 14582 } 14583 } 14584 14585 14586 // If the variable is declared in the current context, there is no need to 14587 // capture it. 14588 if (VarDC == DC) return true; 14589 14590 // Capture global variables if it is required to use private copy of this 14591 // variable. 14592 bool IsGlobal = !Var->hasLocalStorage(); 14593 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14594 return true; 14595 Var = Var->getCanonicalDecl(); 14596 14597 // Walk up the stack to determine whether we can capture the variable, 14598 // performing the "simple" checks that don't depend on type. We stop when 14599 // we've either hit the declared scope of the variable or find an existing 14600 // capture of that variable. We start from the innermost capturing-entity 14601 // (the DC) and ensure that all intervening capturing-entities 14602 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14603 // declcontext can either capture the variable or have already captured 14604 // the variable. 14605 CaptureType = Var->getType(); 14606 DeclRefType = CaptureType.getNonReferenceType(); 14607 bool Nested = false; 14608 bool Explicit = (Kind != TryCapture_Implicit); 14609 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14610 do { 14611 // Only block literals, captured statements, and lambda expressions can 14612 // capture; other scopes don't work. 14613 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14614 ExprLoc, 14615 BuildAndDiagnose, 14616 *this); 14617 // We need to check for the parent *first* because, if we *have* 14618 // private-captured a global variable, we need to recursively capture it in 14619 // intermediate blocks, lambdas, etc. 14620 if (!ParentDC) { 14621 if (IsGlobal) { 14622 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14623 break; 14624 } 14625 return true; 14626 } 14627 14628 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14629 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14630 14631 14632 // Check whether we've already captured it. 14633 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14634 DeclRefType)) { 14635 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14636 break; 14637 } 14638 // If we are instantiating a generic lambda call operator body, 14639 // we do not want to capture new variables. What was captured 14640 // during either a lambdas transformation or initial parsing 14641 // should be used. 14642 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14643 if (BuildAndDiagnose) { 14644 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14645 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14646 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14647 Diag(Var->getLocation(), diag::note_previous_decl) 14648 << Var->getDeclName(); 14649 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14650 } else 14651 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14652 } 14653 return true; 14654 } 14655 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14656 // certain types of variables (unnamed, variably modified types etc.) 14657 // so check for eligibility. 14658 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14659 return true; 14660 14661 // Try to capture variable-length arrays types. 14662 if (Var->getType()->isVariablyModifiedType()) { 14663 // We're going to walk down into the type and look for VLA 14664 // expressions. 14665 QualType QTy = Var->getType(); 14666 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14667 QTy = PVD->getOriginalType(); 14668 captureVariablyModifiedType(Context, QTy, CSI); 14669 } 14670 14671 if (getLangOpts().OpenMP) { 14672 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14673 // OpenMP private variables should not be captured in outer scope, so 14674 // just break here. Similarly, global variables that are captured in a 14675 // target region should not be captured outside the scope of the region. 14676 if (RSI->CapRegionKind == CR_OpenMP) { 14677 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 14678 auto IsTargetCap = !IsOpenMPPrivateDecl && 14679 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14680 // When we detect target captures we are looking from inside the 14681 // target region, therefore we need to propagate the capture from the 14682 // enclosing region. Therefore, the capture is not initially nested. 14683 if (IsTargetCap) 14684 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 14685 14686 if (IsTargetCap || IsOpenMPPrivateDecl) { 14687 Nested = !IsTargetCap; 14688 DeclRefType = DeclRefType.getUnqualifiedType(); 14689 CaptureType = Context.getLValueReferenceType(DeclRefType); 14690 break; 14691 } 14692 } 14693 } 14694 } 14695 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14696 // No capture-default, and this is not an explicit capture 14697 // so cannot capture this variable. 14698 if (BuildAndDiagnose) { 14699 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14700 Diag(Var->getLocation(), diag::note_previous_decl) 14701 << Var->getDeclName(); 14702 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14703 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14704 diag::note_lambda_decl); 14705 // FIXME: If we error out because an outer lambda can not implicitly 14706 // capture a variable that an inner lambda explicitly captures, we 14707 // should have the inner lambda do the explicit capture - because 14708 // it makes for cleaner diagnostics later. This would purely be done 14709 // so that the diagnostic does not misleadingly claim that a variable 14710 // can not be captured by a lambda implicitly even though it is captured 14711 // explicitly. Suggestion: 14712 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14713 // at the function head 14714 // - cache the StartingDeclContext - this must be a lambda 14715 // - captureInLambda in the innermost lambda the variable. 14716 } 14717 return true; 14718 } 14719 14720 FunctionScopesIndex--; 14721 DC = ParentDC; 14722 Explicit = false; 14723 } while (!VarDC->Equals(DC)); 14724 14725 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14726 // computing the type of the capture at each step, checking type-specific 14727 // requirements, and adding captures if requested. 14728 // If the variable had already been captured previously, we start capturing 14729 // at the lambda nested within that one. 14730 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14731 ++I) { 14732 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14733 14734 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14735 if (!captureInBlock(BSI, Var, ExprLoc, 14736 BuildAndDiagnose, CaptureType, 14737 DeclRefType, Nested, *this)) 14738 return true; 14739 Nested = true; 14740 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14741 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14742 BuildAndDiagnose, CaptureType, 14743 DeclRefType, Nested, *this)) 14744 return true; 14745 Nested = true; 14746 } else { 14747 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14748 if (!captureInLambda(LSI, Var, ExprLoc, 14749 BuildAndDiagnose, CaptureType, 14750 DeclRefType, Nested, Kind, EllipsisLoc, 14751 /*IsTopScope*/I == N - 1, *this)) 14752 return true; 14753 Nested = true; 14754 } 14755 } 14756 return false; 14757 } 14758 14759 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14760 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14761 QualType CaptureType; 14762 QualType DeclRefType; 14763 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14764 /*BuildAndDiagnose=*/true, CaptureType, 14765 DeclRefType, nullptr); 14766 } 14767 14768 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14769 QualType CaptureType; 14770 QualType DeclRefType; 14771 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14772 /*BuildAndDiagnose=*/false, CaptureType, 14773 DeclRefType, nullptr); 14774 } 14775 14776 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14777 QualType CaptureType; 14778 QualType DeclRefType; 14779 14780 // Determine whether we can capture this variable. 14781 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14782 /*BuildAndDiagnose=*/false, CaptureType, 14783 DeclRefType, nullptr)) 14784 return QualType(); 14785 14786 return DeclRefType; 14787 } 14788 14789 14790 14791 // If either the type of the variable or the initializer is dependent, 14792 // return false. Otherwise, determine whether the variable is a constant 14793 // expression. Use this if you need to know if a variable that might or 14794 // might not be dependent is truly a constant expression. 14795 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14796 ASTContext &Context) { 14797 14798 if (Var->getType()->isDependentType()) 14799 return false; 14800 const VarDecl *DefVD = nullptr; 14801 Var->getAnyInitializer(DefVD); 14802 if (!DefVD) 14803 return false; 14804 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14805 Expr *Init = cast<Expr>(Eval->Value); 14806 if (Init->isValueDependent()) 14807 return false; 14808 return IsVariableAConstantExpression(Var, Context); 14809 } 14810 14811 14812 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14813 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14814 // an object that satisfies the requirements for appearing in a 14815 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14816 // is immediately applied." This function handles the lvalue-to-rvalue 14817 // conversion part. 14818 MaybeODRUseExprs.erase(E->IgnoreParens()); 14819 14820 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14821 // to a variable that is a constant expression, and if so, identify it as 14822 // a reference to a variable that does not involve an odr-use of that 14823 // variable. 14824 if (LambdaScopeInfo *LSI = getCurLambda()) { 14825 Expr *SansParensExpr = E->IgnoreParens(); 14826 VarDecl *Var = nullptr; 14827 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14828 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14829 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14830 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14831 14832 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14833 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14834 } 14835 } 14836 14837 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14838 Res = CorrectDelayedTyposInExpr(Res); 14839 14840 if (!Res.isUsable()) 14841 return Res; 14842 14843 // If a constant-expression is a reference to a variable where we delay 14844 // deciding whether it is an odr-use, just assume we will apply the 14845 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14846 // (a non-type template argument), we have special handling anyway. 14847 UpdateMarkingForLValueToRValue(Res.get()); 14848 return Res; 14849 } 14850 14851 void Sema::CleanupVarDeclMarking() { 14852 for (Expr *E : MaybeODRUseExprs) { 14853 VarDecl *Var; 14854 SourceLocation Loc; 14855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14856 Var = cast<VarDecl>(DRE->getDecl()); 14857 Loc = DRE->getLocation(); 14858 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14859 Var = cast<VarDecl>(ME->getMemberDecl()); 14860 Loc = ME->getMemberLoc(); 14861 } else { 14862 llvm_unreachable("Unexpected expression"); 14863 } 14864 14865 MarkVarDeclODRUsed(Var, Loc, *this, 14866 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14867 } 14868 14869 MaybeODRUseExprs.clear(); 14870 } 14871 14872 14873 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14874 VarDecl *Var, Expr *E) { 14875 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14876 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14877 Var->setReferenced(); 14878 14879 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14880 14881 bool OdrUseContext = isOdrUseContext(SemaRef); 14882 bool UsableInConstantExpr = 14883 Var->isUsableInConstantExpressions(SemaRef.Context); 14884 bool NeedDefinition = 14885 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 14886 14887 VarTemplateSpecializationDecl *VarSpec = 14888 dyn_cast<VarTemplateSpecializationDecl>(Var); 14889 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14890 "Can't instantiate a partial template specialization."); 14891 14892 // If this might be a member specialization of a static data member, check 14893 // the specialization is visible. We already did the checks for variable 14894 // template specializations when we created them. 14895 if (NeedDefinition && TSK != TSK_Undeclared && 14896 !isa<VarTemplateSpecializationDecl>(Var)) 14897 SemaRef.checkSpecializationVisibility(Loc, Var); 14898 14899 // Perform implicit instantiation of static data members, static data member 14900 // templates of class templates, and variable template specializations. Delay 14901 // instantiations of variable templates, except for those that could be used 14902 // in a constant expression. 14903 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14904 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 14905 // instantiation declaration if a variable is usable in a constant 14906 // expression (among other cases). 14907 bool TryInstantiating = 14908 TSK == TSK_ImplicitInstantiation || 14909 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 14910 14911 if (TryInstantiating) { 14912 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14913 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14914 if (FirstInstantiation) { 14915 PointOfInstantiation = Loc; 14916 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14917 } 14918 14919 bool InstantiationDependent = false; 14920 bool IsNonDependent = 14921 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14922 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14923 : true; 14924 14925 // Do not instantiate specializations that are still type-dependent. 14926 if (IsNonDependent) { 14927 if (UsableInConstantExpr) { 14928 // Do not defer instantiations of variables that could be used in a 14929 // constant expression. 14930 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14931 } else if (FirstInstantiation || 14932 isa<VarTemplateSpecializationDecl>(Var)) { 14933 // FIXME: For a specialization of a variable template, we don't 14934 // distinguish between "declaration and type implicitly instantiated" 14935 // and "implicit instantiation of definition requested", so we have 14936 // no direct way to avoid enqueueing the pending instantiation 14937 // multiple times. 14938 SemaRef.PendingInstantiations 14939 .push_back(std::make_pair(Var, PointOfInstantiation)); 14940 } 14941 } 14942 } 14943 } 14944 14945 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14946 // the requirements for appearing in a constant expression (5.19) and, if 14947 // it is an object, the lvalue-to-rvalue conversion (4.1) 14948 // is immediately applied." We check the first part here, and 14949 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14950 // Note that we use the C++11 definition everywhere because nothing in 14951 // C++03 depends on whether we get the C++03 version correct. The second 14952 // part does not apply to references, since they are not objects. 14953 if (OdrUseContext && E && 14954 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14955 // A reference initialized by a constant expression can never be 14956 // odr-used, so simply ignore it. 14957 if (!Var->getType()->isReferenceType() || 14958 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14959 SemaRef.MaybeODRUseExprs.insert(E); 14960 } else if (OdrUseContext) { 14961 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14962 /*MaxFunctionScopeIndex ptr*/ nullptr); 14963 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14964 // If this is a dependent context, we don't need to mark variables as 14965 // odr-used, but we may still need to track them for lambda capture. 14966 // FIXME: Do we also need to do this inside dependent typeid expressions 14967 // (which are modeled as unevaluated at this point)? 14968 const bool RefersToEnclosingScope = 14969 (SemaRef.CurContext != Var->getDeclContext() && 14970 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14971 if (RefersToEnclosingScope) { 14972 LambdaScopeInfo *const LSI = 14973 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14974 if (LSI && (!LSI->CallOperator || 14975 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 14976 // If a variable could potentially be odr-used, defer marking it so 14977 // until we finish analyzing the full expression for any 14978 // lvalue-to-rvalue 14979 // or discarded value conversions that would obviate odr-use. 14980 // Add it to the list of potential captures that will be analyzed 14981 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14982 // unless the variable is a reference that was initialized by a constant 14983 // expression (this will never need to be captured or odr-used). 14984 assert(E && "Capture variable should be used in an expression."); 14985 if (!Var->getType()->isReferenceType() || 14986 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14987 LSI->addPotentialCapture(E->IgnoreParens()); 14988 } 14989 } 14990 } 14991 } 14992 14993 /// \brief Mark a variable referenced, and check whether it is odr-used 14994 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14995 /// used directly for normal expressions referring to VarDecl. 14996 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14997 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14998 } 14999 15000 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15001 Decl *D, Expr *E, bool MightBeOdrUse) { 15002 if (SemaRef.isInOpenMPDeclareTargetContext()) 15003 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15004 15005 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15006 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15007 return; 15008 } 15009 15010 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15011 15012 // If this is a call to a method via a cast, also mark the method in the 15013 // derived class used in case codegen can devirtualize the call. 15014 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15015 if (!ME) 15016 return; 15017 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15018 if (!MD) 15019 return; 15020 // Only attempt to devirtualize if this is truly a virtual call. 15021 bool IsVirtualCall = MD->isVirtual() && 15022 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15023 if (!IsVirtualCall) 15024 return; 15025 15026 // If it's possible to devirtualize the call, mark the called function 15027 // referenced. 15028 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15029 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15030 if (DM) 15031 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15032 } 15033 15034 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 15035 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15036 // TODO: update this with DR# once a defect report is filed. 15037 // C++11 defect. The address of a pure member should not be an ODR use, even 15038 // if it's a qualified reference. 15039 bool OdrUse = true; 15040 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15041 if (Method->isVirtual() && 15042 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15043 OdrUse = false; 15044 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15045 } 15046 15047 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 15048 void Sema::MarkMemberReferenced(MemberExpr *E) { 15049 // C++11 [basic.def.odr]p2: 15050 // A non-overloaded function whose name appears as a potentially-evaluated 15051 // expression or a member of a set of candidate functions, if selected by 15052 // overload resolution when referred to from a potentially-evaluated 15053 // expression, is odr-used, unless it is a pure virtual function and its 15054 // name is not explicitly qualified. 15055 bool MightBeOdrUse = true; 15056 if (E->performsVirtualDispatch(getLangOpts())) { 15057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15058 if (Method->isPure()) 15059 MightBeOdrUse = false; 15060 } 15061 SourceLocation Loc = E->getMemberLoc().isValid() ? 15062 E->getMemberLoc() : E->getLocStart(); 15063 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15064 } 15065 15066 /// \brief Perform marking for a reference to an arbitrary declaration. It 15067 /// marks the declaration referenced, and performs odr-use checking for 15068 /// functions and variables. This method should not be used when building a 15069 /// normal expression which refers to a variable. 15070 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15071 bool MightBeOdrUse) { 15072 if (MightBeOdrUse) { 15073 if (auto *VD = dyn_cast<VarDecl>(D)) { 15074 MarkVariableReferenced(Loc, VD); 15075 return; 15076 } 15077 } 15078 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15079 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15080 return; 15081 } 15082 D->setReferenced(); 15083 } 15084 15085 namespace { 15086 // Mark all of the declarations used by a type as referenced. 15087 // FIXME: Not fully implemented yet! We need to have a better understanding 15088 // of when we're entering a context we should not recurse into. 15089 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15090 // TreeTransforms rebuilding the type in a new context. Rather than 15091 // duplicating the TreeTransform logic, we should consider reusing it here. 15092 // Currently that causes problems when rebuilding LambdaExprs. 15093 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15094 Sema &S; 15095 SourceLocation Loc; 15096 15097 public: 15098 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15099 15100 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15101 15102 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15103 }; 15104 } 15105 15106 bool MarkReferencedDecls::TraverseTemplateArgument( 15107 const TemplateArgument &Arg) { 15108 { 15109 // A non-type template argument is a constant-evaluated context. 15110 EnterExpressionEvaluationContext Evaluated( 15111 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15112 if (Arg.getKind() == TemplateArgument::Declaration) { 15113 if (Decl *D = Arg.getAsDecl()) 15114 S.MarkAnyDeclReferenced(Loc, D, true); 15115 } else if (Arg.getKind() == TemplateArgument::Expression) { 15116 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15117 } 15118 } 15119 15120 return Inherited::TraverseTemplateArgument(Arg); 15121 } 15122 15123 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15124 MarkReferencedDecls Marker(*this, Loc); 15125 Marker.TraverseType(T); 15126 } 15127 15128 namespace { 15129 /// \brief Helper class that marks all of the declarations referenced by 15130 /// potentially-evaluated subexpressions as "referenced". 15131 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15132 Sema &S; 15133 bool SkipLocalVariables; 15134 15135 public: 15136 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15137 15138 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15139 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15140 15141 void VisitDeclRefExpr(DeclRefExpr *E) { 15142 // If we were asked not to visit local variables, don't. 15143 if (SkipLocalVariables) { 15144 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15145 if (VD->hasLocalStorage()) 15146 return; 15147 } 15148 15149 S.MarkDeclRefReferenced(E); 15150 } 15151 15152 void VisitMemberExpr(MemberExpr *E) { 15153 S.MarkMemberReferenced(E); 15154 Inherited::VisitMemberExpr(E); 15155 } 15156 15157 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15158 S.MarkFunctionReferenced(E->getLocStart(), 15159 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15160 Visit(E->getSubExpr()); 15161 } 15162 15163 void VisitCXXNewExpr(CXXNewExpr *E) { 15164 if (E->getOperatorNew()) 15165 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15166 if (E->getOperatorDelete()) 15167 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15168 Inherited::VisitCXXNewExpr(E); 15169 } 15170 15171 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15172 if (E->getOperatorDelete()) 15173 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15174 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15175 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15176 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15177 S.MarkFunctionReferenced(E->getLocStart(), 15178 S.LookupDestructor(Record)); 15179 } 15180 15181 Inherited::VisitCXXDeleteExpr(E); 15182 } 15183 15184 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15185 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15186 Inherited::VisitCXXConstructExpr(E); 15187 } 15188 15189 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15190 Visit(E->getExpr()); 15191 } 15192 15193 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15194 Inherited::VisitImplicitCastExpr(E); 15195 15196 if (E->getCastKind() == CK_LValueToRValue) 15197 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15198 } 15199 }; 15200 } 15201 15202 /// \brief Mark any declarations that appear within this expression or any 15203 /// potentially-evaluated subexpressions as "referenced". 15204 /// 15205 /// \param SkipLocalVariables If true, don't mark local variables as 15206 /// 'referenced'. 15207 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15208 bool SkipLocalVariables) { 15209 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15210 } 15211 15212 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15213 /// of the program being compiled. 15214 /// 15215 /// This routine emits the given diagnostic when the code currently being 15216 /// type-checked is "potentially evaluated", meaning that there is a 15217 /// possibility that the code will actually be executable. Code in sizeof() 15218 /// expressions, code used only during overload resolution, etc., are not 15219 /// potentially evaluated. This routine will suppress such diagnostics or, 15220 /// in the absolutely nutty case of potentially potentially evaluated 15221 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15222 /// later. 15223 /// 15224 /// This routine should be used for all diagnostics that describe the run-time 15225 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15226 /// Failure to do so will likely result in spurious diagnostics or failures 15227 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15228 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15229 const PartialDiagnostic &PD) { 15230 switch (ExprEvalContexts.back().Context) { 15231 case ExpressionEvaluationContext::Unevaluated: 15232 case ExpressionEvaluationContext::UnevaluatedList: 15233 case ExpressionEvaluationContext::UnevaluatedAbstract: 15234 case ExpressionEvaluationContext::DiscardedStatement: 15235 // The argument will never be evaluated, so don't complain. 15236 break; 15237 15238 case ExpressionEvaluationContext::ConstantEvaluated: 15239 // Relevant diagnostics should be produced by constant evaluation. 15240 break; 15241 15242 case ExpressionEvaluationContext::PotentiallyEvaluated: 15243 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15244 if (Statement && getCurFunctionOrMethodDecl()) { 15245 FunctionScopes.back()->PossiblyUnreachableDiags. 15246 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15247 return true; 15248 } 15249 15250 // The initializer of a constexpr variable or of the first declaration of a 15251 // static data member is not syntactically a constant evaluated constant, 15252 // but nonetheless is always required to be a constant expression, so we 15253 // can skip diagnosing. 15254 // FIXME: Using the mangling context here is a hack. 15255 if (auto *VD = dyn_cast_or_null<VarDecl>( 15256 ExprEvalContexts.back().ManglingContextDecl)) { 15257 if (VD->isConstexpr() || 15258 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15259 break; 15260 // FIXME: For any other kind of variable, we should build a CFG for its 15261 // initializer and check whether the context in question is reachable. 15262 } 15263 15264 Diag(Loc, PD); 15265 return true; 15266 } 15267 15268 return false; 15269 } 15270 15271 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15272 CallExpr *CE, FunctionDecl *FD) { 15273 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15274 return false; 15275 15276 // If we're inside a decltype's expression, don't check for a valid return 15277 // type or construct temporaries until we know whether this is the last call. 15278 if (ExprEvalContexts.back().IsDecltype) { 15279 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15280 return false; 15281 } 15282 15283 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15284 FunctionDecl *FD; 15285 CallExpr *CE; 15286 15287 public: 15288 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15289 : FD(FD), CE(CE) { } 15290 15291 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15292 if (!FD) { 15293 S.Diag(Loc, diag::err_call_incomplete_return) 15294 << T << CE->getSourceRange(); 15295 return; 15296 } 15297 15298 S.Diag(Loc, diag::err_call_function_incomplete_return) 15299 << CE->getSourceRange() << FD->getDeclName() << T; 15300 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15301 << FD->getDeclName(); 15302 } 15303 } Diagnoser(FD, CE); 15304 15305 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15306 return true; 15307 15308 return false; 15309 } 15310 15311 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15312 // will prevent this condition from triggering, which is what we want. 15313 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15314 SourceLocation Loc; 15315 15316 unsigned diagnostic = diag::warn_condition_is_assignment; 15317 bool IsOrAssign = false; 15318 15319 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15320 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15321 return; 15322 15323 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15324 15325 // Greylist some idioms by putting them into a warning subcategory. 15326 if (ObjCMessageExpr *ME 15327 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15328 Selector Sel = ME->getSelector(); 15329 15330 // self = [<foo> init...] 15331 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15332 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15333 15334 // <foo> = [<bar> nextObject] 15335 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15336 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15337 } 15338 15339 Loc = Op->getOperatorLoc(); 15340 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15341 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15342 return; 15343 15344 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15345 Loc = Op->getOperatorLoc(); 15346 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15347 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15348 else { 15349 // Not an assignment. 15350 return; 15351 } 15352 15353 Diag(Loc, diagnostic) << E->getSourceRange(); 15354 15355 SourceLocation Open = E->getLocStart(); 15356 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15357 Diag(Loc, diag::note_condition_assign_silence) 15358 << FixItHint::CreateInsertion(Open, "(") 15359 << FixItHint::CreateInsertion(Close, ")"); 15360 15361 if (IsOrAssign) 15362 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15363 << FixItHint::CreateReplacement(Loc, "!="); 15364 else 15365 Diag(Loc, diag::note_condition_assign_to_comparison) 15366 << FixItHint::CreateReplacement(Loc, "=="); 15367 } 15368 15369 /// \brief Redundant parentheses over an equality comparison can indicate 15370 /// that the user intended an assignment used as condition. 15371 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15372 // Don't warn if the parens came from a macro. 15373 SourceLocation parenLoc = ParenE->getLocStart(); 15374 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15375 return; 15376 // Don't warn for dependent expressions. 15377 if (ParenE->isTypeDependent()) 15378 return; 15379 15380 Expr *E = ParenE->IgnoreParens(); 15381 15382 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15383 if (opE->getOpcode() == BO_EQ && 15384 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15385 == Expr::MLV_Valid) { 15386 SourceLocation Loc = opE->getOperatorLoc(); 15387 15388 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15389 SourceRange ParenERange = ParenE->getSourceRange(); 15390 Diag(Loc, diag::note_equality_comparison_silence) 15391 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15392 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15393 Diag(Loc, diag::note_equality_comparison_to_assign) 15394 << FixItHint::CreateReplacement(Loc, "="); 15395 } 15396 } 15397 15398 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15399 bool IsConstexpr) { 15400 DiagnoseAssignmentAsCondition(E); 15401 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15402 DiagnoseEqualityWithExtraParens(parenE); 15403 15404 ExprResult result = CheckPlaceholderExpr(E); 15405 if (result.isInvalid()) return ExprError(); 15406 E = result.get(); 15407 15408 if (!E->isTypeDependent()) { 15409 if (getLangOpts().CPlusPlus) 15410 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15411 15412 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15413 if (ERes.isInvalid()) 15414 return ExprError(); 15415 E = ERes.get(); 15416 15417 QualType T = E->getType(); 15418 if (!T->isScalarType()) { // C99 6.8.4.1p1 15419 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15420 << T << E->getSourceRange(); 15421 return ExprError(); 15422 } 15423 CheckBoolLikeConversion(E, Loc); 15424 } 15425 15426 return E; 15427 } 15428 15429 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15430 Expr *SubExpr, ConditionKind CK) { 15431 // Empty conditions are valid in for-statements. 15432 if (!SubExpr) 15433 return ConditionResult(); 15434 15435 ExprResult Cond; 15436 switch (CK) { 15437 case ConditionKind::Boolean: 15438 Cond = CheckBooleanCondition(Loc, SubExpr); 15439 break; 15440 15441 case ConditionKind::ConstexprIf: 15442 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15443 break; 15444 15445 case ConditionKind::Switch: 15446 Cond = CheckSwitchCondition(Loc, SubExpr); 15447 break; 15448 } 15449 if (Cond.isInvalid()) 15450 return ConditionError(); 15451 15452 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15453 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15454 if (!FullExpr.get()) 15455 return ConditionError(); 15456 15457 return ConditionResult(*this, nullptr, FullExpr, 15458 CK == ConditionKind::ConstexprIf); 15459 } 15460 15461 namespace { 15462 /// A visitor for rebuilding a call to an __unknown_any expression 15463 /// to have an appropriate type. 15464 struct RebuildUnknownAnyFunction 15465 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15466 15467 Sema &S; 15468 15469 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15470 15471 ExprResult VisitStmt(Stmt *S) { 15472 llvm_unreachable("unexpected statement!"); 15473 } 15474 15475 ExprResult VisitExpr(Expr *E) { 15476 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15477 << E->getSourceRange(); 15478 return ExprError(); 15479 } 15480 15481 /// Rebuild an expression which simply semantically wraps another 15482 /// expression which it shares the type and value kind of. 15483 template <class T> ExprResult rebuildSugarExpr(T *E) { 15484 ExprResult SubResult = Visit(E->getSubExpr()); 15485 if (SubResult.isInvalid()) return ExprError(); 15486 15487 Expr *SubExpr = SubResult.get(); 15488 E->setSubExpr(SubExpr); 15489 E->setType(SubExpr->getType()); 15490 E->setValueKind(SubExpr->getValueKind()); 15491 assert(E->getObjectKind() == OK_Ordinary); 15492 return E; 15493 } 15494 15495 ExprResult VisitParenExpr(ParenExpr *E) { 15496 return rebuildSugarExpr(E); 15497 } 15498 15499 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15500 return rebuildSugarExpr(E); 15501 } 15502 15503 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15504 ExprResult SubResult = Visit(E->getSubExpr()); 15505 if (SubResult.isInvalid()) return ExprError(); 15506 15507 Expr *SubExpr = SubResult.get(); 15508 E->setSubExpr(SubExpr); 15509 E->setType(S.Context.getPointerType(SubExpr->getType())); 15510 assert(E->getValueKind() == VK_RValue); 15511 assert(E->getObjectKind() == OK_Ordinary); 15512 return E; 15513 } 15514 15515 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15516 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15517 15518 E->setType(VD->getType()); 15519 15520 assert(E->getValueKind() == VK_RValue); 15521 if (S.getLangOpts().CPlusPlus && 15522 !(isa<CXXMethodDecl>(VD) && 15523 cast<CXXMethodDecl>(VD)->isInstance())) 15524 E->setValueKind(VK_LValue); 15525 15526 return E; 15527 } 15528 15529 ExprResult VisitMemberExpr(MemberExpr *E) { 15530 return resolveDecl(E, E->getMemberDecl()); 15531 } 15532 15533 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15534 return resolveDecl(E, E->getDecl()); 15535 } 15536 }; 15537 } 15538 15539 /// Given a function expression of unknown-any type, try to rebuild it 15540 /// to have a function type. 15541 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15542 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15543 if (Result.isInvalid()) return ExprError(); 15544 return S.DefaultFunctionArrayConversion(Result.get()); 15545 } 15546 15547 namespace { 15548 /// A visitor for rebuilding an expression of type __unknown_anytype 15549 /// into one which resolves the type directly on the referring 15550 /// expression. Strict preservation of the original source 15551 /// structure is not a goal. 15552 struct RebuildUnknownAnyExpr 15553 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15554 15555 Sema &S; 15556 15557 /// The current destination type. 15558 QualType DestType; 15559 15560 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15561 : S(S), DestType(CastType) {} 15562 15563 ExprResult VisitStmt(Stmt *S) { 15564 llvm_unreachable("unexpected statement!"); 15565 } 15566 15567 ExprResult VisitExpr(Expr *E) { 15568 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15569 << E->getSourceRange(); 15570 return ExprError(); 15571 } 15572 15573 ExprResult VisitCallExpr(CallExpr *E); 15574 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15575 15576 /// Rebuild an expression which simply semantically wraps another 15577 /// expression which it shares the type and value kind of. 15578 template <class T> ExprResult rebuildSugarExpr(T *E) { 15579 ExprResult SubResult = Visit(E->getSubExpr()); 15580 if (SubResult.isInvalid()) return ExprError(); 15581 Expr *SubExpr = SubResult.get(); 15582 E->setSubExpr(SubExpr); 15583 E->setType(SubExpr->getType()); 15584 E->setValueKind(SubExpr->getValueKind()); 15585 assert(E->getObjectKind() == OK_Ordinary); 15586 return E; 15587 } 15588 15589 ExprResult VisitParenExpr(ParenExpr *E) { 15590 return rebuildSugarExpr(E); 15591 } 15592 15593 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15594 return rebuildSugarExpr(E); 15595 } 15596 15597 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15598 const PointerType *Ptr = DestType->getAs<PointerType>(); 15599 if (!Ptr) { 15600 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15601 << E->getSourceRange(); 15602 return ExprError(); 15603 } 15604 15605 if (isa<CallExpr>(E->getSubExpr())) { 15606 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15607 << E->getSourceRange(); 15608 return ExprError(); 15609 } 15610 15611 assert(E->getValueKind() == VK_RValue); 15612 assert(E->getObjectKind() == OK_Ordinary); 15613 E->setType(DestType); 15614 15615 // Build the sub-expression as if it were an object of the pointee type. 15616 DestType = Ptr->getPointeeType(); 15617 ExprResult SubResult = Visit(E->getSubExpr()); 15618 if (SubResult.isInvalid()) return ExprError(); 15619 E->setSubExpr(SubResult.get()); 15620 return E; 15621 } 15622 15623 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15624 15625 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15626 15627 ExprResult VisitMemberExpr(MemberExpr *E) { 15628 return resolveDecl(E, E->getMemberDecl()); 15629 } 15630 15631 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15632 return resolveDecl(E, E->getDecl()); 15633 } 15634 }; 15635 } 15636 15637 /// Rebuilds a call expression which yielded __unknown_anytype. 15638 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15639 Expr *CalleeExpr = E->getCallee(); 15640 15641 enum FnKind { 15642 FK_MemberFunction, 15643 FK_FunctionPointer, 15644 FK_BlockPointer 15645 }; 15646 15647 FnKind Kind; 15648 QualType CalleeType = CalleeExpr->getType(); 15649 if (CalleeType == S.Context.BoundMemberTy) { 15650 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15651 Kind = FK_MemberFunction; 15652 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15653 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15654 CalleeType = Ptr->getPointeeType(); 15655 Kind = FK_FunctionPointer; 15656 } else { 15657 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15658 Kind = FK_BlockPointer; 15659 } 15660 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15661 15662 // Verify that this is a legal result type of a function. 15663 if (DestType->isArrayType() || DestType->isFunctionType()) { 15664 unsigned diagID = diag::err_func_returning_array_function; 15665 if (Kind == FK_BlockPointer) 15666 diagID = diag::err_block_returning_array_function; 15667 15668 S.Diag(E->getExprLoc(), diagID) 15669 << DestType->isFunctionType() << DestType; 15670 return ExprError(); 15671 } 15672 15673 // Otherwise, go ahead and set DestType as the call's result. 15674 E->setType(DestType.getNonLValueExprType(S.Context)); 15675 E->setValueKind(Expr::getValueKindForType(DestType)); 15676 assert(E->getObjectKind() == OK_Ordinary); 15677 15678 // Rebuild the function type, replacing the result type with DestType. 15679 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15680 if (Proto) { 15681 // __unknown_anytype(...) is a special case used by the debugger when 15682 // it has no idea what a function's signature is. 15683 // 15684 // We want to build this call essentially under the K&R 15685 // unprototyped rules, but making a FunctionNoProtoType in C++ 15686 // would foul up all sorts of assumptions. However, we cannot 15687 // simply pass all arguments as variadic arguments, nor can we 15688 // portably just call the function under a non-variadic type; see 15689 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15690 // However, it turns out that in practice it is generally safe to 15691 // call a function declared as "A foo(B,C,D);" under the prototype 15692 // "A foo(B,C,D,...);". The only known exception is with the 15693 // Windows ABI, where any variadic function is implicitly cdecl 15694 // regardless of its normal CC. Therefore we change the parameter 15695 // types to match the types of the arguments. 15696 // 15697 // This is a hack, but it is far superior to moving the 15698 // corresponding target-specific code from IR-gen to Sema/AST. 15699 15700 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15701 SmallVector<QualType, 8> ArgTypes; 15702 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15703 ArgTypes.reserve(E->getNumArgs()); 15704 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15705 Expr *Arg = E->getArg(i); 15706 QualType ArgType = Arg->getType(); 15707 if (E->isLValue()) { 15708 ArgType = S.Context.getLValueReferenceType(ArgType); 15709 } else if (E->isXValue()) { 15710 ArgType = S.Context.getRValueReferenceType(ArgType); 15711 } 15712 ArgTypes.push_back(ArgType); 15713 } 15714 ParamTypes = ArgTypes; 15715 } 15716 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15717 Proto->getExtProtoInfo()); 15718 } else { 15719 DestType = S.Context.getFunctionNoProtoType(DestType, 15720 FnType->getExtInfo()); 15721 } 15722 15723 // Rebuild the appropriate pointer-to-function type. 15724 switch (Kind) { 15725 case FK_MemberFunction: 15726 // Nothing to do. 15727 break; 15728 15729 case FK_FunctionPointer: 15730 DestType = S.Context.getPointerType(DestType); 15731 break; 15732 15733 case FK_BlockPointer: 15734 DestType = S.Context.getBlockPointerType(DestType); 15735 break; 15736 } 15737 15738 // Finally, we can recurse. 15739 ExprResult CalleeResult = Visit(CalleeExpr); 15740 if (!CalleeResult.isUsable()) return ExprError(); 15741 E->setCallee(CalleeResult.get()); 15742 15743 // Bind a temporary if necessary. 15744 return S.MaybeBindToTemporary(E); 15745 } 15746 15747 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15748 // Verify that this is a legal result type of a call. 15749 if (DestType->isArrayType() || DestType->isFunctionType()) { 15750 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15751 << DestType->isFunctionType() << DestType; 15752 return ExprError(); 15753 } 15754 15755 // Rewrite the method result type if available. 15756 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15757 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15758 Method->setReturnType(DestType); 15759 } 15760 15761 // Change the type of the message. 15762 E->setType(DestType.getNonReferenceType()); 15763 E->setValueKind(Expr::getValueKindForType(DestType)); 15764 15765 return S.MaybeBindToTemporary(E); 15766 } 15767 15768 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15769 // The only case we should ever see here is a function-to-pointer decay. 15770 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15771 assert(E->getValueKind() == VK_RValue); 15772 assert(E->getObjectKind() == OK_Ordinary); 15773 15774 E->setType(DestType); 15775 15776 // Rebuild the sub-expression as the pointee (function) type. 15777 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15778 15779 ExprResult Result = Visit(E->getSubExpr()); 15780 if (!Result.isUsable()) return ExprError(); 15781 15782 E->setSubExpr(Result.get()); 15783 return E; 15784 } else if (E->getCastKind() == CK_LValueToRValue) { 15785 assert(E->getValueKind() == VK_RValue); 15786 assert(E->getObjectKind() == OK_Ordinary); 15787 15788 assert(isa<BlockPointerType>(E->getType())); 15789 15790 E->setType(DestType); 15791 15792 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15793 DestType = S.Context.getLValueReferenceType(DestType); 15794 15795 ExprResult Result = Visit(E->getSubExpr()); 15796 if (!Result.isUsable()) return ExprError(); 15797 15798 E->setSubExpr(Result.get()); 15799 return E; 15800 } else { 15801 llvm_unreachable("Unhandled cast type!"); 15802 } 15803 } 15804 15805 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15806 ExprValueKind ValueKind = VK_LValue; 15807 QualType Type = DestType; 15808 15809 // We know how to make this work for certain kinds of decls: 15810 15811 // - functions 15812 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15813 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15814 DestType = Ptr->getPointeeType(); 15815 ExprResult Result = resolveDecl(E, VD); 15816 if (Result.isInvalid()) return ExprError(); 15817 return S.ImpCastExprToType(Result.get(), Type, 15818 CK_FunctionToPointerDecay, VK_RValue); 15819 } 15820 15821 if (!Type->isFunctionType()) { 15822 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15823 << VD << E->getSourceRange(); 15824 return ExprError(); 15825 } 15826 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15827 // We must match the FunctionDecl's type to the hack introduced in 15828 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15829 // type. See the lengthy commentary in that routine. 15830 QualType FDT = FD->getType(); 15831 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15832 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15833 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15834 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15835 SourceLocation Loc = FD->getLocation(); 15836 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15837 FD->getDeclContext(), 15838 Loc, Loc, FD->getNameInfo().getName(), 15839 DestType, FD->getTypeSourceInfo(), 15840 SC_None, false/*isInlineSpecified*/, 15841 FD->hasPrototype(), 15842 false/*isConstexprSpecified*/); 15843 15844 if (FD->getQualifier()) 15845 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15846 15847 SmallVector<ParmVarDecl*, 16> Params; 15848 for (const auto &AI : FT->param_types()) { 15849 ParmVarDecl *Param = 15850 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15851 Param->setScopeInfo(0, Params.size()); 15852 Params.push_back(Param); 15853 } 15854 NewFD->setParams(Params); 15855 DRE->setDecl(NewFD); 15856 VD = DRE->getDecl(); 15857 } 15858 } 15859 15860 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15861 if (MD->isInstance()) { 15862 ValueKind = VK_RValue; 15863 Type = S.Context.BoundMemberTy; 15864 } 15865 15866 // Function references aren't l-values in C. 15867 if (!S.getLangOpts().CPlusPlus) 15868 ValueKind = VK_RValue; 15869 15870 // - variables 15871 } else if (isa<VarDecl>(VD)) { 15872 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15873 Type = RefTy->getPointeeType(); 15874 } else if (Type->isFunctionType()) { 15875 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15876 << VD << E->getSourceRange(); 15877 return ExprError(); 15878 } 15879 15880 // - nothing else 15881 } else { 15882 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15883 << VD << E->getSourceRange(); 15884 return ExprError(); 15885 } 15886 15887 // Modifying the declaration like this is friendly to IR-gen but 15888 // also really dangerous. 15889 VD->setType(DestType); 15890 E->setType(Type); 15891 E->setValueKind(ValueKind); 15892 return E; 15893 } 15894 15895 /// Check a cast of an unknown-any type. We intentionally only 15896 /// trigger this for C-style casts. 15897 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15898 Expr *CastExpr, CastKind &CastKind, 15899 ExprValueKind &VK, CXXCastPath &Path) { 15900 // The type we're casting to must be either void or complete. 15901 if (!CastType->isVoidType() && 15902 RequireCompleteType(TypeRange.getBegin(), CastType, 15903 diag::err_typecheck_cast_to_incomplete)) 15904 return ExprError(); 15905 15906 // Rewrite the casted expression from scratch. 15907 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15908 if (!result.isUsable()) return ExprError(); 15909 15910 CastExpr = result.get(); 15911 VK = CastExpr->getValueKind(); 15912 CastKind = CK_NoOp; 15913 15914 return CastExpr; 15915 } 15916 15917 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15918 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15919 } 15920 15921 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15922 Expr *arg, QualType ¶mType) { 15923 // If the syntactic form of the argument is not an explicit cast of 15924 // any sort, just do default argument promotion. 15925 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15926 if (!castArg) { 15927 ExprResult result = DefaultArgumentPromotion(arg); 15928 if (result.isInvalid()) return ExprError(); 15929 paramType = result.get()->getType(); 15930 return result; 15931 } 15932 15933 // Otherwise, use the type that was written in the explicit cast. 15934 assert(!arg->hasPlaceholderType()); 15935 paramType = castArg->getTypeAsWritten(); 15936 15937 // Copy-initialize a parameter of that type. 15938 InitializedEntity entity = 15939 InitializedEntity::InitializeParameter(Context, paramType, 15940 /*consumed*/ false); 15941 return PerformCopyInitialization(entity, callLoc, arg); 15942 } 15943 15944 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15945 Expr *orig = E; 15946 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15947 while (true) { 15948 E = E->IgnoreParenImpCasts(); 15949 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15950 E = call->getCallee(); 15951 diagID = diag::err_uncasted_call_of_unknown_any; 15952 } else { 15953 break; 15954 } 15955 } 15956 15957 SourceLocation loc; 15958 NamedDecl *d; 15959 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15960 loc = ref->getLocation(); 15961 d = ref->getDecl(); 15962 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15963 loc = mem->getMemberLoc(); 15964 d = mem->getMemberDecl(); 15965 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15966 diagID = diag::err_uncasted_call_of_unknown_any; 15967 loc = msg->getSelectorStartLoc(); 15968 d = msg->getMethodDecl(); 15969 if (!d) { 15970 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15971 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15972 << orig->getSourceRange(); 15973 return ExprError(); 15974 } 15975 } else { 15976 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15977 << E->getSourceRange(); 15978 return ExprError(); 15979 } 15980 15981 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15982 15983 // Never recoverable. 15984 return ExprError(); 15985 } 15986 15987 /// Check for operands with placeholder types and complain if found. 15988 /// Returns ExprError() if there was an error and no recovery was possible. 15989 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15990 if (!getLangOpts().CPlusPlus) { 15991 // C cannot handle TypoExpr nodes on either side of a binop because it 15992 // doesn't handle dependent types properly, so make sure any TypoExprs have 15993 // been dealt with before checking the operands. 15994 ExprResult Result = CorrectDelayedTyposInExpr(E); 15995 if (!Result.isUsable()) return ExprError(); 15996 E = Result.get(); 15997 } 15998 15999 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16000 if (!placeholderType) return E; 16001 16002 switch (placeholderType->getKind()) { 16003 16004 // Overloaded expressions. 16005 case BuiltinType::Overload: { 16006 // Try to resolve a single function template specialization. 16007 // This is obligatory. 16008 ExprResult Result = E; 16009 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16010 return Result; 16011 16012 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16013 // leaves Result unchanged on failure. 16014 Result = E; 16015 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16016 return Result; 16017 16018 // If that failed, try to recover with a call. 16019 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16020 /*complain*/ true); 16021 return Result; 16022 } 16023 16024 // Bound member functions. 16025 case BuiltinType::BoundMember: { 16026 ExprResult result = E; 16027 const Expr *BME = E->IgnoreParens(); 16028 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16029 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16030 if (isa<CXXPseudoDestructorExpr>(BME)) { 16031 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16032 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16033 if (ME->getMemberNameInfo().getName().getNameKind() == 16034 DeclarationName::CXXDestructorName) 16035 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16036 } 16037 tryToRecoverWithCall(result, PD, 16038 /*complain*/ true); 16039 return result; 16040 } 16041 16042 // ARC unbridged casts. 16043 case BuiltinType::ARCUnbridgedCast: { 16044 Expr *realCast = stripARCUnbridgedCast(E); 16045 diagnoseARCUnbridgedCast(realCast); 16046 return realCast; 16047 } 16048 16049 // Expressions of unknown type. 16050 case BuiltinType::UnknownAny: 16051 return diagnoseUnknownAnyExpr(*this, E); 16052 16053 // Pseudo-objects. 16054 case BuiltinType::PseudoObject: 16055 return checkPseudoObjectRValue(E); 16056 16057 case BuiltinType::BuiltinFn: { 16058 // Accept __noop without parens by implicitly converting it to a call expr. 16059 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16060 if (DRE) { 16061 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16062 if (FD->getBuiltinID() == Builtin::BI__noop) { 16063 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16064 CK_BuiltinFnToFnPtr).get(); 16065 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16066 VK_RValue, SourceLocation()); 16067 } 16068 } 16069 16070 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16071 return ExprError(); 16072 } 16073 16074 // Expressions of unknown type. 16075 case BuiltinType::OMPArraySection: 16076 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16077 return ExprError(); 16078 16079 // Everything else should be impossible. 16080 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16081 case BuiltinType::Id: 16082 #include "clang/Basic/OpenCLImageTypes.def" 16083 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16084 #define PLACEHOLDER_TYPE(Id, SingletonId) 16085 #include "clang/AST/BuiltinTypes.def" 16086 break; 16087 } 16088 16089 llvm_unreachable("invalid placeholder type!"); 16090 } 16091 16092 bool Sema::CheckCaseExpression(Expr *E) { 16093 if (E->isTypeDependent()) 16094 return true; 16095 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16096 return E->getType()->isIntegralOrEnumerationType(); 16097 return false; 16098 } 16099 16100 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16101 ExprResult 16102 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16103 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16104 "Unknown Objective-C Boolean value!"); 16105 QualType BoolT = Context.ObjCBuiltinBoolTy; 16106 if (!Context.getBOOLDecl()) { 16107 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16108 Sema::LookupOrdinaryName); 16109 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16110 NamedDecl *ND = Result.getFoundDecl(); 16111 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16112 Context.setBOOLDecl(TD); 16113 } 16114 } 16115 if (Context.getBOOLDecl()) 16116 BoolT = Context.getBOOLType(); 16117 return new (Context) 16118 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16119 } 16120 16121 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16122 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16123 SourceLocation RParen) { 16124 16125 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16126 16127 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16128 [&](const AvailabilitySpec &Spec) { 16129 return Spec.getPlatform() == Platform; 16130 }); 16131 16132 VersionTuple Version; 16133 if (Spec != AvailSpecs.end()) 16134 Version = Spec->getVersion(); 16135 16136 // The use of `@available` in the enclosing function should be analyzed to 16137 // warn when it's used inappropriately (i.e. not if(@available)). 16138 if (getCurFunctionOrMethodDecl()) 16139 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16140 else if (getCurBlock() || getCurLambda()) 16141 getCurFunction()->HasPotentialAvailabilityViolations = true; 16142 16143 return new (Context) 16144 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16145 } 16146