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 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 84 if (DC && !DC->hasAttr<UnusedAttr>()) 85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 86 } 87 } 88 } 89 90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 92 if (!OMD) 93 return false; 94 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 95 if (!OID) 96 return false; 97 98 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 99 if (ObjCMethodDecl *CatMeth = 100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 101 if (!CatMeth->hasAttr<AvailabilityAttr>()) 102 return true; 103 return false; 104 } 105 106 AvailabilityResult Sema::ShouldDiagnoseAvailabilityOfDecl( 107 NamedDecl *&D, VersionTuple ContextVersion, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message, ContextVersion); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(Message, ContextVersion); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(Message, ContextVersion); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(Message, ContextVersion); 136 } 137 138 switch (Result) { 139 case AR_Available: 140 return Result; 141 142 case AR_Unavailable: 143 case AR_Deprecated: 144 return getCurContextAvailability() != Result ? Result : AR_Available; 145 146 case AR_NotYetIntroduced: { 147 // Don't do this for enums, they can't be redeclared. 148 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 149 return AR_Available; 150 151 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 152 // Objective-C method declarations in categories are not modelled as 153 // redeclarations, so manually look for a redeclaration in a category 154 // if necessary. 155 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 156 Warn = false; 157 // In general, D will point to the most recent redeclaration. However, 158 // for `@class A;` decls, this isn't true -- manually go through the 159 // redecl chain in that case. 160 if (Warn && isa<ObjCInterfaceDecl>(D)) 161 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 162 Redecl = Redecl->getPreviousDecl()) 163 if (!Redecl->hasAttr<AvailabilityAttr>() || 164 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 165 Warn = false; 166 167 return Warn ? AR_NotYetIntroduced : AR_Available; 168 } 169 } 170 llvm_unreachable("Unknown availability result!"); 171 } 172 173 static void 174 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 175 const ObjCInterfaceDecl *UnknownObjCClass, 176 bool ObjCPropertyAccess) { 177 VersionTuple ContextVersion; 178 if (const DeclContext *DC = S.getCurObjCLexicalContext()) 179 ContextVersion = S.getVersionForDecl(cast<Decl>(DC)); 180 181 std::string Message; 182 // See if this declaration is unavailable, deprecated, or partial in the 183 // current context. 184 if (AvailabilityResult Result = 185 S.ShouldDiagnoseAvailabilityOfDecl(D, ContextVersion, &Message)) { 186 187 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) { 188 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 189 return; 190 } 191 192 const ObjCPropertyDecl *ObjCPDecl = nullptr; 193 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 194 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 195 AvailabilityResult PDeclResult = 196 PD->getAvailability(nullptr, ContextVersion); 197 if (PDeclResult == Result) 198 ObjCPDecl = PD; 199 } 200 } 201 202 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 203 ObjCPDecl, ObjCPropertyAccess); 204 } 205 } 206 207 /// \brief Emit a note explaining that this function is deleted. 208 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 209 assert(Decl->isDeleted()); 210 211 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 212 213 if (Method && Method->isDeleted() && Method->isDefaulted()) { 214 // If the method was explicitly defaulted, point at that declaration. 215 if (!Method->isImplicit()) 216 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 217 218 // Try to diagnose why this special member function was implicitly 219 // deleted. This might fail, if that reason no longer applies. 220 CXXSpecialMember CSM = getSpecialMember(Method); 221 if (CSM != CXXInvalid) 222 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 223 224 return; 225 } 226 227 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 228 if (Ctor && Ctor->isInheritingConstructor()) 229 return NoteDeletedInheritingConstructor(Ctor); 230 231 Diag(Decl->getLocation(), diag::note_availability_specified_here) 232 << Decl << true; 233 } 234 235 /// \brief Determine whether a FunctionDecl was ever declared with an 236 /// explicit storage class. 237 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 238 for (auto I : D->redecls()) { 239 if (I->getStorageClass() != SC_None) 240 return true; 241 } 242 return false; 243 } 244 245 /// \brief Check whether we're in an extern inline function and referring to a 246 /// variable or function with internal linkage (C11 6.7.4p3). 247 /// 248 /// This is only a warning because we used to silently accept this code, but 249 /// in many cases it will not behave correctly. This is not enabled in C++ mode 250 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 251 /// and so while there may still be user mistakes, most of the time we can't 252 /// prove that there are errors. 253 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 254 const NamedDecl *D, 255 SourceLocation Loc) { 256 // This is disabled under C++; there are too many ways for this to fire in 257 // contexts where the warning is a false positive, or where it is technically 258 // correct but benign. 259 if (S.getLangOpts().CPlusPlus) 260 return; 261 262 // Check if this is an inlined function or method. 263 FunctionDecl *Current = S.getCurFunctionDecl(); 264 if (!Current) 265 return; 266 if (!Current->isInlined()) 267 return; 268 if (!Current->isExternallyVisible()) 269 return; 270 271 // Check if the decl has internal linkage. 272 if (D->getFormalLinkage() != InternalLinkage) 273 return; 274 275 // Downgrade from ExtWarn to Extension if 276 // (1) the supposedly external inline function is in the main file, 277 // and probably won't be included anywhere else. 278 // (2) the thing we're referencing is a pure function. 279 // (3) the thing we're referencing is another inline function. 280 // This last can give us false negatives, but it's better than warning on 281 // wrappers for simple C library functions. 282 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 283 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 284 if (!DowngradeWarning && UsedFn) 285 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 286 287 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 288 : diag::ext_internal_in_extern_inline) 289 << /*IsVar=*/!UsedFn << D; 290 291 S.MaybeSuggestAddingStaticToDecl(Current); 292 293 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 294 << D; 295 } 296 297 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 298 const FunctionDecl *First = Cur->getFirstDecl(); 299 300 // Suggest "static" on the function, if possible. 301 if (!hasAnyExplicitStorageClass(First)) { 302 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 303 Diag(DeclBegin, diag::note_convert_inline_to_static) 304 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 305 } 306 } 307 308 /// \brief Determine whether the use of this declaration is valid, and 309 /// emit any corresponding diagnostics. 310 /// 311 /// This routine diagnoses various problems with referencing 312 /// declarations that can occur when using a declaration. For example, 313 /// it might warn if a deprecated or unavailable declaration is being 314 /// used, or produce an error (and return true) if a C++0x deleted 315 /// function is being used. 316 /// 317 /// \returns true if there was an error (this declaration cannot be 318 /// referenced), false otherwise. 319 /// 320 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 321 const ObjCInterfaceDecl *UnknownObjCClass, 322 bool ObjCPropertyAccess) { 323 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 324 // If there were any diagnostics suppressed by template argument deduction, 325 // emit them now. 326 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 327 if (Pos != SuppressedDiagnostics.end()) { 328 for (const PartialDiagnosticAt &Suppressed : Pos->second) 329 Diag(Suppressed.first, Suppressed.second); 330 331 // Clear out the list of suppressed diagnostics, so that we don't emit 332 // them again for this specialization. However, we don't obsolete this 333 // entry from the table, because we want to avoid ever emitting these 334 // diagnostics again. 335 Pos->second.clear(); 336 } 337 338 // C++ [basic.start.main]p3: 339 // The function 'main' shall not be used within a program. 340 if (cast<FunctionDecl>(D)->isMain()) 341 Diag(Loc, diag::ext_main_used); 342 } 343 344 // See if this is an auto-typed variable whose initializer we are parsing. 345 if (ParsingInitForAutoVars.count(D)) { 346 if (isa<BindingDecl>(D)) { 347 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 348 << D->getDeclName(); 349 } else { 350 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 351 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName() << (unsigned)AT->getKeyword(); 354 } 355 return true; 356 } 357 358 // See if this is a deleted function. 359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 360 if (FD->isDeleted()) { 361 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 362 if (Ctor && Ctor->isInheritingConstructor()) 363 Diag(Loc, diag::err_deleted_inherited_ctor_use) 364 << Ctor->getParent() 365 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 366 else 367 Diag(Loc, diag::err_deleted_function_use); 368 NoteDeletedFunction(FD); 369 return true; 370 } 371 372 // If the function has a deduced return type, and we can't deduce it, 373 // then we can't use it either. 374 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 375 DeduceReturnType(FD, Loc)) 376 return true; 377 378 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 379 return true; 380 } 381 382 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 383 // Only the variables omp_in and omp_out are allowed in the combiner. 384 // Only the variables omp_priv and omp_orig are allowed in the 385 // initializer-clause. 386 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 387 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 388 isa<VarDecl>(D)) { 389 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 390 << getCurFunction()->HasOMPDeclareReductionCombiner; 391 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 392 return true; 393 } 394 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 395 ObjCPropertyAccess); 396 397 DiagnoseUnusedOfDecl(*this, D, Loc); 398 399 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 400 401 return false; 402 } 403 404 /// \brief Retrieve the message suffix that should be added to a 405 /// diagnostic complaining about the given function being deleted or 406 /// unavailable. 407 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 408 std::string Message; 409 if (FD->getAvailability(&Message)) 410 return ": " + Message; 411 412 return std::string(); 413 } 414 415 /// DiagnoseSentinelCalls - This routine checks whether a call or 416 /// message-send is to a declaration with the sentinel attribute, and 417 /// if so, it checks that the requirements of the sentinel are 418 /// satisfied. 419 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 420 ArrayRef<Expr *> Args) { 421 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 422 if (!attr) 423 return; 424 425 // The number of formal parameters of the declaration. 426 unsigned numFormalParams; 427 428 // The kind of declaration. This is also an index into a %select in 429 // the diagnostic. 430 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 431 432 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 433 numFormalParams = MD->param_size(); 434 calleeType = CT_Method; 435 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 436 numFormalParams = FD->param_size(); 437 calleeType = CT_Function; 438 } else if (isa<VarDecl>(D)) { 439 QualType type = cast<ValueDecl>(D)->getType(); 440 const FunctionType *fn = nullptr; 441 if (const PointerType *ptr = type->getAs<PointerType>()) { 442 fn = ptr->getPointeeType()->getAs<FunctionType>(); 443 if (!fn) return; 444 calleeType = CT_Function; 445 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 446 fn = ptr->getPointeeType()->castAs<FunctionType>(); 447 calleeType = CT_Block; 448 } else { 449 return; 450 } 451 452 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 453 numFormalParams = proto->getNumParams(); 454 } else { 455 numFormalParams = 0; 456 } 457 } else { 458 return; 459 } 460 461 // "nullPos" is the number of formal parameters at the end which 462 // effectively count as part of the variadic arguments. This is 463 // useful if you would prefer to not have *any* formal parameters, 464 // but the language forces you to have at least one. 465 unsigned nullPos = attr->getNullPos(); 466 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 467 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 468 469 // The number of arguments which should follow the sentinel. 470 unsigned numArgsAfterSentinel = attr->getSentinel(); 471 472 // If there aren't enough arguments for all the formal parameters, 473 // the sentinel, and the args after the sentinel, complain. 474 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 475 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 476 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 477 return; 478 } 479 480 // Otherwise, find the sentinel expression. 481 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 482 if (!sentinelExpr) return; 483 if (sentinelExpr->isValueDependent()) return; 484 if (Context.isSentinelNullExpr(sentinelExpr)) return; 485 486 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 487 // or 'NULL' if those are actually defined in the context. Only use 488 // 'nil' for ObjC methods, where it's much more likely that the 489 // variadic arguments form a list of object pointers. 490 SourceLocation MissingNilLoc 491 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 492 std::string NullValue; 493 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 494 NullValue = "nil"; 495 else if (getLangOpts().CPlusPlus11) 496 NullValue = "nullptr"; 497 else if (PP.isMacroDefined("NULL")) 498 NullValue = "NULL"; 499 else 500 NullValue = "(void*) 0"; 501 502 if (MissingNilLoc.isInvalid()) 503 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 504 else 505 Diag(MissingNilLoc, diag::warn_missing_sentinel) 506 << int(calleeType) 507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 508 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 509 } 510 511 SourceRange Sema::getExprRange(Expr *E) const { 512 return E ? E->getSourceRange() : SourceRange(); 513 } 514 515 //===----------------------------------------------------------------------===// 516 // Standard Promotions and Conversions 517 //===----------------------------------------------------------------------===// 518 519 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 520 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 521 // Handle any placeholder expressions which made it here. 522 if (E->getType()->isPlaceholderType()) { 523 ExprResult result = CheckPlaceholderExpr(E); 524 if (result.isInvalid()) return ExprError(); 525 E = result.get(); 526 } 527 528 QualType Ty = E->getType(); 529 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 530 531 if (Ty->isFunctionType()) { 532 // If we are here, we are not calling a function but taking 533 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 534 if (getLangOpts().OpenCL) { 535 if (Diagnose) 536 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 537 return ExprError(); 538 } 539 540 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 541 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 542 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 543 return ExprError(); 544 545 E = ImpCastExprToType(E, Context.getPointerType(Ty), 546 CK_FunctionToPointerDecay).get(); 547 } else if (Ty->isArrayType()) { 548 // In C90 mode, arrays only promote to pointers if the array expression is 549 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 550 // type 'array of type' is converted to an expression that has type 'pointer 551 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 552 // that has type 'array of type' ...". The relevant change is "an lvalue" 553 // (C90) to "an expression" (C99). 554 // 555 // C++ 4.2p1: 556 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 557 // T" can be converted to an rvalue of type "pointer to T". 558 // 559 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 560 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 561 CK_ArrayToPointerDecay).get(); 562 } 563 return E; 564 } 565 566 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 567 // Check to see if we are dereferencing a null pointer. If so, 568 // and if not volatile-qualified, this is undefined behavior that the 569 // optimizer will delete, so warn about it. People sometimes try to use this 570 // to get a deterministic trap and are surprised by clang's behavior. This 571 // only handles the pattern "*null", which is a very syntactic check. 572 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 573 if (UO->getOpcode() == UO_Deref && 574 UO->getSubExpr()->IgnoreParenCasts()-> 575 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 576 !UO->getType().isVolatileQualified()) { 577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 578 S.PDiag(diag::warn_indirection_through_null) 579 << UO->getSubExpr()->getSourceRange()); 580 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 581 S.PDiag(diag::note_indirection_through_null)); 582 } 583 } 584 585 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 586 SourceLocation AssignLoc, 587 const Expr* RHS) { 588 const ObjCIvarDecl *IV = OIRE->getDecl(); 589 if (!IV) 590 return; 591 592 DeclarationName MemberName = IV->getDeclName(); 593 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 594 if (!Member || !Member->isStr("isa")) 595 return; 596 597 const Expr *Base = OIRE->getBase(); 598 QualType BaseType = Base->getType(); 599 if (OIRE->isArrow()) 600 BaseType = BaseType->getPointeeType(); 601 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 602 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 603 ObjCInterfaceDecl *ClassDeclared = nullptr; 604 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 605 if (!ClassDeclared->getSuperClass() 606 && (*ClassDeclared->ivar_begin()) == IV) { 607 if (RHS) { 608 NamedDecl *ObjectSetClass = 609 S.LookupSingleName(S.TUScope, 610 &S.Context.Idents.get("object_setClass"), 611 SourceLocation(), S.LookupOrdinaryName); 612 if (ObjectSetClass) { 613 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 616 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 617 AssignLoc), ",") << 618 FixItHint::CreateInsertion(RHSLocEnd, ")"); 619 } 620 else 621 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 622 } else { 623 NamedDecl *ObjectGetClass = 624 S.LookupSingleName(S.TUScope, 625 &S.Context.Idents.get("object_getClass"), 626 SourceLocation(), S.LookupOrdinaryName); 627 if (ObjectGetClass) 628 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 629 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 630 FixItHint::CreateReplacement( 631 SourceRange(OIRE->getOpLoc(), 632 OIRE->getLocEnd()), ")"); 633 else 634 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 635 } 636 S.Diag(IV->getLocation(), diag::note_ivar_decl); 637 } 638 } 639 } 640 641 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 642 // Handle any placeholder expressions which made it here. 643 if (E->getType()->isPlaceholderType()) { 644 ExprResult result = CheckPlaceholderExpr(E); 645 if (result.isInvalid()) return ExprError(); 646 E = result.get(); 647 } 648 649 // C++ [conv.lval]p1: 650 // A glvalue of a non-function, non-array type T can be 651 // converted to a prvalue. 652 if (!E->isGLValue()) return E; 653 654 QualType T = E->getType(); 655 assert(!T.isNull() && "r-value conversion on typeless expression?"); 656 657 // We don't want to throw lvalue-to-rvalue casts on top of 658 // expressions of certain types in C++. 659 if (getLangOpts().CPlusPlus && 660 (E->getType() == Context.OverloadTy || 661 T->isDependentType() || 662 T->isRecordType())) 663 return E; 664 665 // The C standard is actually really unclear on this point, and 666 // DR106 tells us what the result should be but not why. It's 667 // generally best to say that void types just doesn't undergo 668 // lvalue-to-rvalue at all. Note that expressions of unqualified 669 // 'void' type are never l-values, but qualified void can be. 670 if (T->isVoidType()) 671 return E; 672 673 // OpenCL usually rejects direct accesses to values of 'half' type. 674 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 675 T->isHalfType()) { 676 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 677 << 0 << T; 678 return ExprError(); 679 } 680 681 CheckForNullPointerDereference(*this, E); 682 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 683 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 684 &Context.Idents.get("object_getClass"), 685 SourceLocation(), LookupOrdinaryName); 686 if (ObjectGetClass) 687 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 688 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 689 FixItHint::CreateReplacement( 690 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 691 else 692 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 693 } 694 else if (const ObjCIvarRefExpr *OIRE = 695 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 696 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 697 698 // C++ [conv.lval]p1: 699 // [...] If T is a non-class type, the type of the prvalue is the 700 // cv-unqualified version of T. Otherwise, the type of the 701 // rvalue is T. 702 // 703 // C99 6.3.2.1p2: 704 // If the lvalue has qualified type, the value has the unqualified 705 // version of the type of the lvalue; otherwise, the value has the 706 // type of the lvalue. 707 if (T.hasQualifiers()) 708 T = T.getUnqualifiedType(); 709 710 // Under the MS ABI, lock down the inheritance model now. 711 if (T->isMemberPointerType() && 712 Context.getTargetInfo().getCXXABI().isMicrosoft()) 713 (void)isCompleteType(E->getExprLoc(), T); 714 715 UpdateMarkingForLValueToRValue(E); 716 717 // Loading a __weak object implicitly retains the value, so we need a cleanup to 718 // balance that. 719 if (getLangOpts().ObjCAutoRefCount && 720 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 721 Cleanup.setExprNeedsCleanups(true); 722 723 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 724 nullptr, VK_RValue); 725 726 // C11 6.3.2.1p2: 727 // ... if the lvalue has atomic type, the value has the non-atomic version 728 // of the type of the lvalue ... 729 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 730 T = Atomic->getValueType().getUnqualifiedType(); 731 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 732 nullptr, VK_RValue); 733 } 734 735 return Res; 736 } 737 738 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 739 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 740 if (Res.isInvalid()) 741 return ExprError(); 742 Res = DefaultLvalueConversion(Res.get()); 743 if (Res.isInvalid()) 744 return ExprError(); 745 return Res; 746 } 747 748 /// CallExprUnaryConversions - a special case of an unary conversion 749 /// performed on a function designator of a call expression. 750 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 751 QualType Ty = E->getType(); 752 ExprResult Res = E; 753 // Only do implicit cast for a function type, but not for a pointer 754 // to function type. 755 if (Ty->isFunctionType()) { 756 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 757 CK_FunctionToPointerDecay).get(); 758 if (Res.isInvalid()) 759 return ExprError(); 760 } 761 Res = DefaultLvalueConversion(Res.get()); 762 if (Res.isInvalid()) 763 return ExprError(); 764 return Res.get(); 765 } 766 767 /// UsualUnaryConversions - Performs various conversions that are common to most 768 /// operators (C99 6.3). The conversions of array and function types are 769 /// sometimes suppressed. For example, the array->pointer conversion doesn't 770 /// apply if the array is an argument to the sizeof or address (&) operators. 771 /// In these instances, this routine should *not* be called. 772 ExprResult Sema::UsualUnaryConversions(Expr *E) { 773 // First, convert to an r-value. 774 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 775 if (Res.isInvalid()) 776 return ExprError(); 777 E = Res.get(); 778 779 QualType Ty = E->getType(); 780 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 781 782 // Half FP have to be promoted to float unless it is natively supported 783 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 784 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 785 786 // Try to perform integral promotions if the object has a theoretically 787 // promotable type. 788 if (Ty->isIntegralOrUnscopedEnumerationType()) { 789 // C99 6.3.1.1p2: 790 // 791 // The following may be used in an expression wherever an int or 792 // unsigned int may be used: 793 // - an object or expression with an integer type whose integer 794 // conversion rank is less than or equal to the rank of int 795 // and unsigned int. 796 // - A bit-field of type _Bool, int, signed int, or unsigned int. 797 // 798 // If an int can represent all values of the original type, the 799 // value is converted to an int; otherwise, it is converted to an 800 // unsigned int. These are called the integer promotions. All 801 // other types are unchanged by the integer promotions. 802 803 QualType PTy = Context.isPromotableBitField(E); 804 if (!PTy.isNull()) { 805 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 806 return E; 807 } 808 if (Ty->isPromotableIntegerType()) { 809 QualType PT = Context.getPromotedIntegerType(Ty); 810 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 811 return E; 812 } 813 } 814 return E; 815 } 816 817 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 818 /// do not have a prototype. Arguments that have type float or __fp16 819 /// are promoted to double. All other argument types are converted by 820 /// UsualUnaryConversions(). 821 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 822 QualType Ty = E->getType(); 823 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 824 825 ExprResult Res = UsualUnaryConversions(E); 826 if (Res.isInvalid()) 827 return ExprError(); 828 E = Res.get(); 829 830 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 831 // double. 832 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 833 if (BTy && (BTy->getKind() == BuiltinType::Half || 834 BTy->getKind() == BuiltinType::Float)) 835 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 836 837 // C++ performs lvalue-to-rvalue conversion as a default argument 838 // promotion, even on class types, but note: 839 // C++11 [conv.lval]p2: 840 // When an lvalue-to-rvalue conversion occurs in an unevaluated 841 // operand or a subexpression thereof the value contained in the 842 // referenced object is not accessed. Otherwise, if the glvalue 843 // has a class type, the conversion copy-initializes a temporary 844 // of type T from the glvalue and the result of the conversion 845 // is a prvalue for the temporary. 846 // FIXME: add some way to gate this entire thing for correctness in 847 // potentially potentially evaluated contexts. 848 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 849 ExprResult Temp = PerformCopyInitialization( 850 InitializedEntity::InitializeTemporary(E->getType()), 851 E->getExprLoc(), E); 852 if (Temp.isInvalid()) 853 return ExprError(); 854 E = Temp.get(); 855 } 856 857 return E; 858 } 859 860 /// Determine the degree of POD-ness for an expression. 861 /// Incomplete types are considered POD, since this check can be performed 862 /// when we're in an unevaluated context. 863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 864 if (Ty->isIncompleteType()) { 865 // C++11 [expr.call]p7: 866 // After these conversions, if the argument does not have arithmetic, 867 // enumeration, pointer, pointer to member, or class type, the program 868 // is ill-formed. 869 // 870 // Since we've already performed array-to-pointer and function-to-pointer 871 // decay, the only such type in C++ is cv void. This also handles 872 // initializer lists as variadic arguments. 873 if (Ty->isVoidType()) 874 return VAK_Invalid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 return VAK_Valid; 879 } 880 881 if (Ty.isCXX98PODType(Context)) 882 return VAK_Valid; 883 884 // C++11 [expr.call]p7: 885 // Passing a potentially-evaluated argument of class type (Clause 9) 886 // having a non-trivial copy constructor, a non-trivial move constructor, 887 // or a non-trivial destructor, with no corresponding parameter, 888 // is conditionally-supported with implementation-defined semantics. 889 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 890 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 891 if (!Record->hasNonTrivialCopyConstructor() && 892 !Record->hasNonTrivialMoveConstructor() && 893 !Record->hasNonTrivialDestructor()) 894 return VAK_ValidInCXX11; 895 896 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 897 return VAK_Valid; 898 899 if (Ty->isObjCObjectType()) 900 return VAK_Invalid; 901 902 if (getLangOpts().MSVCCompat) 903 return VAK_MSVCUndefined; 904 905 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 906 // permitted to reject them. We should consider doing so. 907 return VAK_Undefined; 908 } 909 910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 911 // Don't allow one to pass an Objective-C interface to a vararg. 912 const QualType &Ty = E->getType(); 913 VarArgKind VAK = isValidVarArgType(Ty); 914 915 // Complain about passing non-POD types through varargs. 916 switch (VAK) { 917 case VAK_ValidInCXX11: 918 DiagRuntimeBehavior( 919 E->getLocStart(), nullptr, 920 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 921 << Ty << CT); 922 // Fall through. 923 case VAK_Valid: 924 if (Ty->isRecordType()) { 925 // This is unlikely to be what the user intended. If the class has a 926 // 'c_str' member function, the user probably meant to call that. 927 DiagRuntimeBehavior(E->getLocStart(), nullptr, 928 PDiag(diag::warn_pass_class_arg_to_vararg) 929 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 930 } 931 break; 932 933 case VAK_Undefined: 934 case VAK_MSVCUndefined: 935 DiagRuntimeBehavior( 936 E->getLocStart(), nullptr, 937 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 938 << getLangOpts().CPlusPlus11 << Ty << CT); 939 break; 940 941 case VAK_Invalid: 942 if (Ty->isObjCObjectType()) 943 DiagRuntimeBehavior( 944 E->getLocStart(), nullptr, 945 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 946 << Ty << CT); 947 else 948 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 949 << isa<InitListExpr>(E) << Ty << CT; 950 break; 951 } 952 } 953 954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 955 /// will create a trap if the resulting type is not a POD type. 956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 957 FunctionDecl *FDecl) { 958 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 959 // Strip the unbridged-cast placeholder expression off, if applicable. 960 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 961 (CT == VariadicMethod || 962 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 963 E = stripARCUnbridgedCast(E); 964 965 // Otherwise, do normal placeholder checking. 966 } else { 967 ExprResult ExprRes = CheckPlaceholderExpr(E); 968 if (ExprRes.isInvalid()) 969 return ExprError(); 970 E = ExprRes.get(); 971 } 972 } 973 974 ExprResult ExprRes = DefaultArgumentPromotion(E); 975 if (ExprRes.isInvalid()) 976 return ExprError(); 977 E = ExprRes.get(); 978 979 // Diagnostics regarding non-POD argument types are 980 // emitted along with format string checking in Sema::CheckFunctionCall(). 981 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 982 // Turn this into a trap. 983 CXXScopeSpec SS; 984 SourceLocation TemplateKWLoc; 985 UnqualifiedId Name; 986 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 987 E->getLocStart()); 988 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 989 Name, true, false); 990 if (TrapFn.isInvalid()) 991 return ExprError(); 992 993 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 994 E->getLocStart(), None, 995 E->getLocEnd()); 996 if (Call.isInvalid()) 997 return ExprError(); 998 999 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 1000 Call.get(), E); 1001 if (Comma.isInvalid()) 1002 return ExprError(); 1003 return Comma.get(); 1004 } 1005 1006 if (!getLangOpts().CPlusPlus && 1007 RequireCompleteType(E->getExprLoc(), E->getType(), 1008 diag::err_call_incomplete_argument)) 1009 return ExprError(); 1010 1011 return E; 1012 } 1013 1014 /// \brief Converts an integer to complex float type. Helper function of 1015 /// UsualArithmeticConversions() 1016 /// 1017 /// \return false if the integer expression is an integer type and is 1018 /// successfully converted to the complex type. 1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1020 ExprResult &ComplexExpr, 1021 QualType IntTy, 1022 QualType ComplexTy, 1023 bool SkipCast) { 1024 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1025 if (SkipCast) return false; 1026 if (IntTy->isIntegerType()) { 1027 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1029 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1030 CK_FloatingRealToComplex); 1031 } else { 1032 assert(IntTy->isComplexIntegerType()); 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1034 CK_IntegralComplexToFloatingComplex); 1035 } 1036 return false; 1037 } 1038 1039 /// \brief Handle arithmetic conversion with complex types. Helper function of 1040 /// UsualArithmeticConversions() 1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1042 ExprResult &RHS, QualType LHSType, 1043 QualType RHSType, 1044 bool IsCompAssign) { 1045 // if we have an integer operand, the result is the complex type. 1046 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1047 /*skipCast*/false)) 1048 return LHSType; 1049 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1050 /*skipCast*/IsCompAssign)) 1051 return RHSType; 1052 1053 // This handles complex/complex, complex/float, or float/complex. 1054 // When both operands are complex, the shorter operand is converted to the 1055 // type of the longer, and that is the type of the result. This corresponds 1056 // to what is done when combining two real floating-point operands. 1057 // The fun begins when size promotion occur across type domains. 1058 // From H&S 6.3.4: When one operand is complex and the other is a real 1059 // floating-point type, the less precise type is converted, within it's 1060 // real or complex domain, to the precision of the other type. For example, 1061 // when combining a "long double" with a "double _Complex", the 1062 // "double _Complex" is promoted to "long double _Complex". 1063 1064 // Compute the rank of the two types, regardless of whether they are complex. 1065 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1066 1067 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1068 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1069 QualType LHSElementType = 1070 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1071 QualType RHSElementType = 1072 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1073 1074 QualType ResultType = S.Context.getComplexType(LHSElementType); 1075 if (Order < 0) { 1076 // Promote the precision of the LHS if not an assignment. 1077 ResultType = S.Context.getComplexType(RHSElementType); 1078 if (!IsCompAssign) { 1079 if (LHSComplexType) 1080 LHS = 1081 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1082 else 1083 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1084 } 1085 } else if (Order > 0) { 1086 // Promote the precision of the RHS. 1087 if (RHSComplexType) 1088 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1089 else 1090 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1091 } 1092 return ResultType; 1093 } 1094 1095 /// \brief Hande arithmetic conversion from integer to float. Helper function 1096 /// of UsualArithmeticConversions() 1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1098 ExprResult &IntExpr, 1099 QualType FloatTy, QualType IntTy, 1100 bool ConvertFloat, bool ConvertInt) { 1101 if (IntTy->isIntegerType()) { 1102 if (ConvertInt) 1103 // Convert intExpr to the lhs floating point type. 1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1105 CK_IntegralToFloating); 1106 return FloatTy; 1107 } 1108 1109 // Convert both sides to the appropriate complex float. 1110 assert(IntTy->isComplexIntegerType()); 1111 QualType result = S.Context.getComplexType(FloatTy); 1112 1113 // _Complex int -> _Complex float 1114 if (ConvertInt) 1115 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1116 CK_IntegralComplexToFloatingComplex); 1117 1118 // float -> _Complex float 1119 if (ConvertFloat) 1120 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1121 CK_FloatingRealToComplex); 1122 1123 return result; 1124 } 1125 1126 /// \brief Handle arithmethic conversion with floating point types. Helper 1127 /// function of UsualArithmeticConversions() 1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1129 ExprResult &RHS, QualType LHSType, 1130 QualType RHSType, bool IsCompAssign) { 1131 bool LHSFloat = LHSType->isRealFloatingType(); 1132 bool RHSFloat = RHSType->isRealFloatingType(); 1133 1134 // If we have two real floating types, convert the smaller operand 1135 // to the bigger result. 1136 if (LHSFloat && RHSFloat) { 1137 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1138 if (order > 0) { 1139 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1140 return LHSType; 1141 } 1142 1143 assert(order < 0 && "illegal float comparison"); 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1146 return RHSType; 1147 } 1148 1149 if (LHSFloat) { 1150 // Half FP has to be promoted to float unless it is natively supported 1151 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1152 LHSType = S.Context.FloatTy; 1153 1154 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1155 /*convertFloat=*/!IsCompAssign, 1156 /*convertInt=*/ true); 1157 } 1158 assert(RHSFloat); 1159 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1160 /*convertInt=*/ true, 1161 /*convertFloat=*/!IsCompAssign); 1162 } 1163 1164 /// \brief Diagnose attempts to convert between __float128 and long double if 1165 /// there is no support for such conversion. Helper function of 1166 /// UsualArithmeticConversions(). 1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1168 QualType RHSType) { 1169 /* No issue converting if at least one of the types is not a floating point 1170 type or the two types have the same rank. 1171 */ 1172 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1173 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1174 return false; 1175 1176 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1177 "The remaining types must be floating point types."); 1178 1179 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1180 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1181 1182 QualType LHSElemType = LHSComplex ? 1183 LHSComplex->getElementType() : LHSType; 1184 QualType RHSElemType = RHSComplex ? 1185 RHSComplex->getElementType() : RHSType; 1186 1187 // No issue if the two types have the same representation 1188 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1189 &S.Context.getFloatTypeSemantics(RHSElemType)) 1190 return false; 1191 1192 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1193 RHSElemType == S.Context.LongDoubleTy); 1194 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1195 RHSElemType == S.Context.Float128Ty); 1196 1197 /* We've handled the situation where __float128 and long double have the same 1198 representation. The only other allowable conversion is if long double is 1199 really just double. 1200 */ 1201 return Float128AndLongDouble && 1202 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1203 &llvm::APFloat::IEEEdouble); 1204 } 1205 1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1207 1208 namespace { 1209 /// These helper callbacks are placed in an anonymous namespace to 1210 /// permit their use as function template parameters. 1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1212 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1213 } 1214 1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1216 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1217 CK_IntegralComplexCast); 1218 } 1219 } 1220 1221 /// \brief Handle integer arithmetic conversions. Helper function of 1222 /// UsualArithmeticConversions() 1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1225 ExprResult &RHS, QualType LHSType, 1226 QualType RHSType, bool IsCompAssign) { 1227 // The rules for this case are in C99 6.3.1.8 1228 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1229 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1230 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1231 if (LHSSigned == RHSSigned) { 1232 // Same signedness; use the higher-ranked type 1233 if (order >= 0) { 1234 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1235 return LHSType; 1236 } else if (!IsCompAssign) 1237 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1238 return RHSType; 1239 } else if (order != (LHSSigned ? 1 : -1)) { 1240 // The unsigned type has greater than or equal rank to the 1241 // signed type, so use the unsigned type 1242 if (RHSSigned) { 1243 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1244 return LHSType; 1245 } else if (!IsCompAssign) 1246 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1247 return RHSType; 1248 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1249 // The two types are different widths; if we are here, that 1250 // means the signed type is larger than the unsigned type, so 1251 // use the signed type. 1252 if (LHSSigned) { 1253 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1254 return LHSType; 1255 } else if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1257 return RHSType; 1258 } else { 1259 // The signed type is higher-ranked than the unsigned type, 1260 // but isn't actually any bigger (like unsigned int and long 1261 // on most 32-bit systems). Use the unsigned type corresponding 1262 // to the signed type. 1263 QualType result = 1264 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1265 RHS = (*doRHSCast)(S, RHS.get(), result); 1266 if (!IsCompAssign) 1267 LHS = (*doLHSCast)(S, LHS.get(), result); 1268 return result; 1269 } 1270 } 1271 1272 /// \brief Handle conversions with GCC complex int extension. Helper function 1273 /// of UsualArithmeticConversions() 1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1275 ExprResult &RHS, QualType LHSType, 1276 QualType RHSType, 1277 bool IsCompAssign) { 1278 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1279 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1280 1281 if (LHSComplexInt && RHSComplexInt) { 1282 QualType LHSEltType = LHSComplexInt->getElementType(); 1283 QualType RHSEltType = RHSComplexInt->getElementType(); 1284 QualType ScalarType = 1285 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1286 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1287 1288 return S.Context.getComplexType(ScalarType); 1289 } 1290 1291 if (LHSComplexInt) { 1292 QualType LHSEltType = LHSComplexInt->getElementType(); 1293 QualType ScalarType = 1294 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1295 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1296 QualType ComplexType = S.Context.getComplexType(ScalarType); 1297 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1298 CK_IntegralRealToComplex); 1299 1300 return ComplexType; 1301 } 1302 1303 assert(RHSComplexInt); 1304 1305 QualType RHSEltType = RHSComplexInt->getElementType(); 1306 QualType ScalarType = 1307 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1308 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1309 QualType ComplexType = S.Context.getComplexType(ScalarType); 1310 1311 if (!IsCompAssign) 1312 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1313 CK_IntegralRealToComplex); 1314 return ComplexType; 1315 } 1316 1317 /// UsualArithmeticConversions - Performs various conversions that are common to 1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1319 /// routine returns the first non-arithmetic type found. The client is 1320 /// responsible for emitting appropriate error diagnostics. 1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1322 bool IsCompAssign) { 1323 if (!IsCompAssign) { 1324 LHS = UsualUnaryConversions(LHS.get()); 1325 if (LHS.isInvalid()) 1326 return QualType(); 1327 } 1328 1329 RHS = UsualUnaryConversions(RHS.get()); 1330 if (RHS.isInvalid()) 1331 return QualType(); 1332 1333 // For conversion purposes, we ignore any qualifiers. 1334 // For example, "const float" and "float" are equivalent. 1335 QualType LHSType = 1336 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1337 QualType RHSType = 1338 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1339 1340 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1341 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1342 LHSType = AtomicLHS->getValueType(); 1343 1344 // If both types are identical, no conversion is needed. 1345 if (LHSType == RHSType) 1346 return LHSType; 1347 1348 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1349 // The caller can deal with this (e.g. pointer + int). 1350 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1351 return QualType(); 1352 1353 // Apply unary and bitfield promotions to the LHS's type. 1354 QualType LHSUnpromotedType = LHSType; 1355 if (LHSType->isPromotableIntegerType()) 1356 LHSType = Context.getPromotedIntegerType(LHSType); 1357 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1358 if (!LHSBitfieldPromoteTy.isNull()) 1359 LHSType = LHSBitfieldPromoteTy; 1360 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1361 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1362 1363 // If both types are identical, no conversion is needed. 1364 if (LHSType == RHSType) 1365 return LHSType; 1366 1367 // At this point, we have two different arithmetic types. 1368 1369 // Diagnose attempts to convert between __float128 and long double where 1370 // such conversions currently can't be handled. 1371 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1372 return QualType(); 1373 1374 // Handle complex types first (C99 6.3.1.8p1). 1375 if (LHSType->isComplexType() || RHSType->isComplexType()) 1376 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1377 IsCompAssign); 1378 1379 // Now handle "real" floating types (i.e. float, double, long double). 1380 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1381 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1382 IsCompAssign); 1383 1384 // Handle GCC complex int extension. 1385 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1386 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1387 IsCompAssign); 1388 1389 // Finally, we have two differing integer types. 1390 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1391 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1392 } 1393 1394 1395 //===----------------------------------------------------------------------===// 1396 // Semantic Analysis for various Expression Types 1397 //===----------------------------------------------------------------------===// 1398 1399 1400 ExprResult 1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1402 SourceLocation DefaultLoc, 1403 SourceLocation RParenLoc, 1404 Expr *ControllingExpr, 1405 ArrayRef<ParsedType> ArgTypes, 1406 ArrayRef<Expr *> ArgExprs) { 1407 unsigned NumAssocs = ArgTypes.size(); 1408 assert(NumAssocs == ArgExprs.size()); 1409 1410 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1411 for (unsigned i = 0; i < NumAssocs; ++i) { 1412 if (ArgTypes[i]) 1413 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1414 else 1415 Types[i] = nullptr; 1416 } 1417 1418 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1419 ControllingExpr, 1420 llvm::makeArrayRef(Types, NumAssocs), 1421 ArgExprs); 1422 delete [] Types; 1423 return ER; 1424 } 1425 1426 ExprResult 1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1428 SourceLocation DefaultLoc, 1429 SourceLocation RParenLoc, 1430 Expr *ControllingExpr, 1431 ArrayRef<TypeSourceInfo *> Types, 1432 ArrayRef<Expr *> Exprs) { 1433 unsigned NumAssocs = Types.size(); 1434 assert(NumAssocs == Exprs.size()); 1435 1436 // Decay and strip qualifiers for the controlling expression type, and handle 1437 // placeholder type replacement. See committee discussion from WG14 DR423. 1438 { 1439 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1440 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1441 if (R.isInvalid()) 1442 return ExprError(); 1443 ControllingExpr = R.get(); 1444 } 1445 1446 // The controlling expression is an unevaluated operand, so side effects are 1447 // likely unintended. 1448 if (ActiveTemplateInstantiations.empty() && 1449 ControllingExpr->HasSideEffects(Context, false)) 1450 Diag(ControllingExpr->getExprLoc(), 1451 diag::warn_side_effects_unevaluated_context); 1452 1453 bool TypeErrorFound = false, 1454 IsResultDependent = ControllingExpr->isTypeDependent(), 1455 ContainsUnexpandedParameterPack 1456 = ControllingExpr->containsUnexpandedParameterPack(); 1457 1458 for (unsigned i = 0; i < NumAssocs; ++i) { 1459 if (Exprs[i]->containsUnexpandedParameterPack()) 1460 ContainsUnexpandedParameterPack = true; 1461 1462 if (Types[i]) { 1463 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1464 ContainsUnexpandedParameterPack = true; 1465 1466 if (Types[i]->getType()->isDependentType()) { 1467 IsResultDependent = true; 1468 } else { 1469 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1470 // complete object type other than a variably modified type." 1471 unsigned D = 0; 1472 if (Types[i]->getType()->isIncompleteType()) 1473 D = diag::err_assoc_type_incomplete; 1474 else if (!Types[i]->getType()->isObjectType()) 1475 D = diag::err_assoc_type_nonobject; 1476 else if (Types[i]->getType()->isVariablyModifiedType()) 1477 D = diag::err_assoc_type_variably_modified; 1478 1479 if (D != 0) { 1480 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1481 << Types[i]->getTypeLoc().getSourceRange() 1482 << Types[i]->getType(); 1483 TypeErrorFound = true; 1484 } 1485 1486 // C11 6.5.1.1p2 "No two generic associations in the same generic 1487 // selection shall specify compatible types." 1488 for (unsigned j = i+1; j < NumAssocs; ++j) 1489 if (Types[j] && !Types[j]->getType()->isDependentType() && 1490 Context.typesAreCompatible(Types[i]->getType(), 1491 Types[j]->getType())) { 1492 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1493 diag::err_assoc_compatible_types) 1494 << Types[j]->getTypeLoc().getSourceRange() 1495 << Types[j]->getType() 1496 << Types[i]->getType(); 1497 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1498 diag::note_compat_assoc) 1499 << Types[i]->getTypeLoc().getSourceRange() 1500 << Types[i]->getType(); 1501 TypeErrorFound = true; 1502 } 1503 } 1504 } 1505 } 1506 if (TypeErrorFound) 1507 return ExprError(); 1508 1509 // If we determined that the generic selection is result-dependent, don't 1510 // try to compute the result expression. 1511 if (IsResultDependent) 1512 return new (Context) GenericSelectionExpr( 1513 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1514 ContainsUnexpandedParameterPack); 1515 1516 SmallVector<unsigned, 1> CompatIndices; 1517 unsigned DefaultIndex = -1U; 1518 for (unsigned i = 0; i < NumAssocs; ++i) { 1519 if (!Types[i]) 1520 DefaultIndex = i; 1521 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1522 Types[i]->getType())) 1523 CompatIndices.push_back(i); 1524 } 1525 1526 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1527 // type compatible with at most one of the types named in its generic 1528 // association list." 1529 if (CompatIndices.size() > 1) { 1530 // We strip parens here because the controlling expression is typically 1531 // parenthesized in macro definitions. 1532 ControllingExpr = ControllingExpr->IgnoreParens(); 1533 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1534 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1535 << (unsigned) CompatIndices.size(); 1536 for (unsigned I : CompatIndices) { 1537 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1538 diag::note_compat_assoc) 1539 << Types[I]->getTypeLoc().getSourceRange() 1540 << Types[I]->getType(); 1541 } 1542 return ExprError(); 1543 } 1544 1545 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1546 // its controlling expression shall have type compatible with exactly one of 1547 // the types named in its generic association list." 1548 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1549 // We strip parens here because the controlling expression is typically 1550 // parenthesized in macro definitions. 1551 ControllingExpr = ControllingExpr->IgnoreParens(); 1552 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1553 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1554 return ExprError(); 1555 } 1556 1557 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1558 // type name that is compatible with the type of the controlling expression, 1559 // then the result expression of the generic selection is the expression 1560 // in that generic association. Otherwise, the result expression of the 1561 // generic selection is the expression in the default generic association." 1562 unsigned ResultIndex = 1563 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1564 1565 return new (Context) GenericSelectionExpr( 1566 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1567 ContainsUnexpandedParameterPack, ResultIndex); 1568 } 1569 1570 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1571 /// location of the token and the offset of the ud-suffix within it. 1572 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1573 unsigned Offset) { 1574 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1575 S.getLangOpts()); 1576 } 1577 1578 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1579 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1580 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1581 IdentifierInfo *UDSuffix, 1582 SourceLocation UDSuffixLoc, 1583 ArrayRef<Expr*> Args, 1584 SourceLocation LitEndLoc) { 1585 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1586 1587 QualType ArgTy[2]; 1588 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1589 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1590 if (ArgTy[ArgIdx]->isArrayType()) 1591 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1592 } 1593 1594 DeclarationName OpName = 1595 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1596 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1597 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1598 1599 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1600 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1601 /*AllowRaw*/false, /*AllowTemplate*/false, 1602 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1603 return ExprError(); 1604 1605 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1606 } 1607 1608 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1609 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1610 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1611 /// multiple tokens. However, the common case is that StringToks points to one 1612 /// string. 1613 /// 1614 ExprResult 1615 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1616 assert(!StringToks.empty() && "Must have at least one string!"); 1617 1618 StringLiteralParser Literal(StringToks, PP); 1619 if (Literal.hadError) 1620 return ExprError(); 1621 1622 SmallVector<SourceLocation, 4> StringTokLocs; 1623 for (const Token &Tok : StringToks) 1624 StringTokLocs.push_back(Tok.getLocation()); 1625 1626 QualType CharTy = Context.CharTy; 1627 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1628 if (Literal.isWide()) { 1629 CharTy = Context.getWideCharType(); 1630 Kind = StringLiteral::Wide; 1631 } else if (Literal.isUTF8()) { 1632 Kind = StringLiteral::UTF8; 1633 } else if (Literal.isUTF16()) { 1634 CharTy = Context.Char16Ty; 1635 Kind = StringLiteral::UTF16; 1636 } else if (Literal.isUTF32()) { 1637 CharTy = Context.Char32Ty; 1638 Kind = StringLiteral::UTF32; 1639 } else if (Literal.isPascal()) { 1640 CharTy = Context.UnsignedCharTy; 1641 } 1642 1643 QualType CharTyConst = CharTy; 1644 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1645 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1646 CharTyConst.addConst(); 1647 1648 // Get an array type for the string, according to C99 6.4.5. This includes 1649 // the nul terminator character as well as the string length for pascal 1650 // strings. 1651 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1652 llvm::APInt(32, Literal.GetNumStringChars()+1), 1653 ArrayType::Normal, 0); 1654 1655 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1656 if (getLangOpts().OpenCL) { 1657 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1658 } 1659 1660 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1661 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1662 Kind, Literal.Pascal, StrTy, 1663 &StringTokLocs[0], 1664 StringTokLocs.size()); 1665 if (Literal.getUDSuffix().empty()) 1666 return Lit; 1667 1668 // We're building a user-defined literal. 1669 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1670 SourceLocation UDSuffixLoc = 1671 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1672 Literal.getUDSuffixOffset()); 1673 1674 // Make sure we're allowed user-defined literals here. 1675 if (!UDLScope) 1676 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1677 1678 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1679 // operator "" X (str, len) 1680 QualType SizeType = Context.getSizeType(); 1681 1682 DeclarationName OpName = 1683 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1684 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1685 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1686 1687 QualType ArgTy[] = { 1688 Context.getArrayDecayedType(StrTy), SizeType 1689 }; 1690 1691 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1692 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1693 /*AllowRaw*/false, /*AllowTemplate*/false, 1694 /*AllowStringTemplate*/true)) { 1695 1696 case LOLR_Cooked: { 1697 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1698 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1699 StringTokLocs[0]); 1700 Expr *Args[] = { Lit, LenArg }; 1701 1702 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1703 } 1704 1705 case LOLR_StringTemplate: { 1706 TemplateArgumentListInfo ExplicitArgs; 1707 1708 unsigned CharBits = Context.getIntWidth(CharTy); 1709 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1710 llvm::APSInt Value(CharBits, CharIsUnsigned); 1711 1712 TemplateArgument TypeArg(CharTy); 1713 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1714 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1715 1716 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1717 Value = Lit->getCodeUnit(I); 1718 TemplateArgument Arg(Context, Value, CharTy); 1719 TemplateArgumentLocInfo ArgInfo; 1720 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1721 } 1722 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1723 &ExplicitArgs); 1724 } 1725 case LOLR_Raw: 1726 case LOLR_Template: 1727 llvm_unreachable("unexpected literal operator lookup result"); 1728 case LOLR_Error: 1729 return ExprError(); 1730 } 1731 llvm_unreachable("unexpected literal operator lookup result"); 1732 } 1733 1734 ExprResult 1735 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1736 SourceLocation Loc, 1737 const CXXScopeSpec *SS) { 1738 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1739 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1740 } 1741 1742 /// BuildDeclRefExpr - Build an expression that references a 1743 /// declaration that does not require a closure capture. 1744 ExprResult 1745 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1746 const DeclarationNameInfo &NameInfo, 1747 const CXXScopeSpec *SS, NamedDecl *FoundD, 1748 const TemplateArgumentListInfo *TemplateArgs) { 1749 bool RefersToCapturedVariable = 1750 isa<VarDecl>(D) && 1751 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1752 1753 DeclRefExpr *E; 1754 if (isa<VarTemplateSpecializationDecl>(D)) { 1755 VarTemplateSpecializationDecl *VarSpec = 1756 cast<VarTemplateSpecializationDecl>(D); 1757 1758 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1759 : NestedNameSpecifierLoc(), 1760 VarSpec->getTemplateKeywordLoc(), D, 1761 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1762 FoundD, TemplateArgs); 1763 } else { 1764 assert(!TemplateArgs && "No template arguments for non-variable" 1765 " template specialization references"); 1766 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1767 : NestedNameSpecifierLoc(), 1768 SourceLocation(), D, RefersToCapturedVariable, 1769 NameInfo, Ty, VK, FoundD); 1770 } 1771 1772 MarkDeclRefReferenced(E); 1773 1774 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1775 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1776 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1777 recordUseOfEvaluatedWeak(E); 1778 1779 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1780 UnusedPrivateFields.remove(FD); 1781 // Just in case we're building an illegal pointer-to-member. 1782 if (FD->isBitField()) 1783 E->setObjectKind(OK_BitField); 1784 } 1785 1786 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1787 // designates a bit-field. 1788 if (auto *BD = dyn_cast<BindingDecl>(D)) 1789 if (auto *BE = BD->getBinding()) 1790 E->setObjectKind(BE->getObjectKind()); 1791 1792 return E; 1793 } 1794 1795 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1796 /// possibly a list of template arguments. 1797 /// 1798 /// If this produces template arguments, it is permitted to call 1799 /// DecomposeTemplateName. 1800 /// 1801 /// This actually loses a lot of source location information for 1802 /// non-standard name kinds; we should consider preserving that in 1803 /// some way. 1804 void 1805 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1806 TemplateArgumentListInfo &Buffer, 1807 DeclarationNameInfo &NameInfo, 1808 const TemplateArgumentListInfo *&TemplateArgs) { 1809 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1810 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1811 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1812 1813 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1814 Id.TemplateId->NumArgs); 1815 translateTemplateArguments(TemplateArgsPtr, Buffer); 1816 1817 TemplateName TName = Id.TemplateId->Template.get(); 1818 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1819 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1820 TemplateArgs = &Buffer; 1821 } else { 1822 NameInfo = GetNameFromUnqualifiedId(Id); 1823 TemplateArgs = nullptr; 1824 } 1825 } 1826 1827 static void emitEmptyLookupTypoDiagnostic( 1828 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1829 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1830 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1831 DeclContext *Ctx = 1832 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1833 if (!TC) { 1834 // Emit a special diagnostic for failed member lookups. 1835 // FIXME: computing the declaration context might fail here (?) 1836 if (Ctx) 1837 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1838 << SS.getRange(); 1839 else 1840 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1841 return; 1842 } 1843 1844 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1845 bool DroppedSpecifier = 1846 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1847 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1848 ? diag::note_implicit_param_decl 1849 : diag::note_previous_decl; 1850 if (!Ctx) 1851 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1852 SemaRef.PDiag(NoteID)); 1853 else 1854 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1855 << Typo << Ctx << DroppedSpecifier 1856 << SS.getRange(), 1857 SemaRef.PDiag(NoteID)); 1858 } 1859 1860 /// Diagnose an empty lookup. 1861 /// 1862 /// \return false if new lookup candidates were found 1863 bool 1864 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1865 std::unique_ptr<CorrectionCandidateCallback> CCC, 1866 TemplateArgumentListInfo *ExplicitTemplateArgs, 1867 ArrayRef<Expr *> Args, TypoExpr **Out) { 1868 DeclarationName Name = R.getLookupName(); 1869 1870 unsigned diagnostic = diag::err_undeclared_var_use; 1871 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1872 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1873 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1874 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1875 diagnostic = diag::err_undeclared_use; 1876 diagnostic_suggest = diag::err_undeclared_use_suggest; 1877 } 1878 1879 // If the original lookup was an unqualified lookup, fake an 1880 // unqualified lookup. This is useful when (for example) the 1881 // original lookup would not have found something because it was a 1882 // dependent name. 1883 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1884 while (DC) { 1885 if (isa<CXXRecordDecl>(DC)) { 1886 LookupQualifiedName(R, DC); 1887 1888 if (!R.empty()) { 1889 // Don't give errors about ambiguities in this lookup. 1890 R.suppressDiagnostics(); 1891 1892 // During a default argument instantiation the CurContext points 1893 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1894 // function parameter list, hence add an explicit check. 1895 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1896 ActiveTemplateInstantiations.back().Kind == 1897 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1898 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1899 bool isInstance = CurMethod && 1900 CurMethod->isInstance() && 1901 DC == CurMethod->getParent() && !isDefaultArgument; 1902 1903 // Give a code modification hint to insert 'this->'. 1904 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1905 // Actually quite difficult! 1906 if (getLangOpts().MSVCCompat) 1907 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1908 if (isInstance) { 1909 Diag(R.getNameLoc(), diagnostic) << Name 1910 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1911 CheckCXXThisCapture(R.getNameLoc()); 1912 } else { 1913 Diag(R.getNameLoc(), diagnostic) << Name; 1914 } 1915 1916 // Do we really want to note all of these? 1917 for (NamedDecl *D : R) 1918 Diag(D->getLocation(), diag::note_dependent_var_use); 1919 1920 // Return true if we are inside a default argument instantiation 1921 // and the found name refers to an instance member function, otherwise 1922 // the function calling DiagnoseEmptyLookup will try to create an 1923 // implicit member call and this is wrong for default argument. 1924 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1925 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1926 return true; 1927 } 1928 1929 // Tell the callee to try to recover. 1930 return false; 1931 } 1932 1933 R.clear(); 1934 } 1935 1936 // In Microsoft mode, if we are performing lookup from within a friend 1937 // function definition declared at class scope then we must set 1938 // DC to the lexical parent to be able to search into the parent 1939 // class. 1940 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1941 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1942 DC->getLexicalParent()->isRecord()) 1943 DC = DC->getLexicalParent(); 1944 else 1945 DC = DC->getParent(); 1946 } 1947 1948 // We didn't find anything, so try to correct for a typo. 1949 TypoCorrection Corrected; 1950 if (S && Out) { 1951 SourceLocation TypoLoc = R.getNameLoc(); 1952 assert(!ExplicitTemplateArgs && 1953 "Diagnosing an empty lookup with explicit template args!"); 1954 *Out = CorrectTypoDelayed( 1955 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1956 [=](const TypoCorrection &TC) { 1957 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1958 diagnostic, diagnostic_suggest); 1959 }, 1960 nullptr, CTK_ErrorRecovery); 1961 if (*Out) 1962 return true; 1963 } else if (S && (Corrected = 1964 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1965 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1966 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1967 bool DroppedSpecifier = 1968 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1969 R.setLookupName(Corrected.getCorrection()); 1970 1971 bool AcceptableWithRecovery = false; 1972 bool AcceptableWithoutRecovery = false; 1973 NamedDecl *ND = Corrected.getFoundDecl(); 1974 if (ND) { 1975 if (Corrected.isOverloaded()) { 1976 OverloadCandidateSet OCS(R.getNameLoc(), 1977 OverloadCandidateSet::CSK_Normal); 1978 OverloadCandidateSet::iterator Best; 1979 for (NamedDecl *CD : Corrected) { 1980 if (FunctionTemplateDecl *FTD = 1981 dyn_cast<FunctionTemplateDecl>(CD)) 1982 AddTemplateOverloadCandidate( 1983 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1984 Args, OCS); 1985 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1986 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1987 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1988 Args, OCS); 1989 } 1990 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1991 case OR_Success: 1992 ND = Best->FoundDecl; 1993 Corrected.setCorrectionDecl(ND); 1994 break; 1995 default: 1996 // FIXME: Arbitrarily pick the first declaration for the note. 1997 Corrected.setCorrectionDecl(ND); 1998 break; 1999 } 2000 } 2001 R.addDecl(ND); 2002 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2003 CXXRecordDecl *Record = nullptr; 2004 if (Corrected.getCorrectionSpecifier()) { 2005 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2006 Record = Ty->getAsCXXRecordDecl(); 2007 } 2008 if (!Record) 2009 Record = cast<CXXRecordDecl>( 2010 ND->getDeclContext()->getRedeclContext()); 2011 R.setNamingClass(Record); 2012 } 2013 2014 auto *UnderlyingND = ND->getUnderlyingDecl(); 2015 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2016 isa<FunctionTemplateDecl>(UnderlyingND); 2017 // FIXME: If we ended up with a typo for a type name or 2018 // Objective-C class name, we're in trouble because the parser 2019 // is in the wrong place to recover. Suggest the typo 2020 // correction, but don't make it a fix-it since we're not going 2021 // to recover well anyway. 2022 AcceptableWithoutRecovery = 2023 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2024 } else { 2025 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2026 // because we aren't able to recover. 2027 AcceptableWithoutRecovery = true; 2028 } 2029 2030 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2031 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2032 ? diag::note_implicit_param_decl 2033 : diag::note_previous_decl; 2034 if (SS.isEmpty()) 2035 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2036 PDiag(NoteID), AcceptableWithRecovery); 2037 else 2038 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2039 << Name << computeDeclContext(SS, false) 2040 << DroppedSpecifier << SS.getRange(), 2041 PDiag(NoteID), AcceptableWithRecovery); 2042 2043 // Tell the callee whether to try to recover. 2044 return !AcceptableWithRecovery; 2045 } 2046 } 2047 R.clear(); 2048 2049 // Emit a special diagnostic for failed member lookups. 2050 // FIXME: computing the declaration context might fail here (?) 2051 if (!SS.isEmpty()) { 2052 Diag(R.getNameLoc(), diag::err_no_member) 2053 << Name << computeDeclContext(SS, false) 2054 << SS.getRange(); 2055 return true; 2056 } 2057 2058 // Give up, we can't recover. 2059 Diag(R.getNameLoc(), diagnostic) << Name; 2060 return true; 2061 } 2062 2063 /// In Microsoft mode, if we are inside a template class whose parent class has 2064 /// dependent base classes, and we can't resolve an unqualified identifier, then 2065 /// assume the identifier is a member of a dependent base class. We can only 2066 /// recover successfully in static methods, instance methods, and other contexts 2067 /// where 'this' is available. This doesn't precisely match MSVC's 2068 /// instantiation model, but it's close enough. 2069 static Expr * 2070 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2071 DeclarationNameInfo &NameInfo, 2072 SourceLocation TemplateKWLoc, 2073 const TemplateArgumentListInfo *TemplateArgs) { 2074 // Only try to recover from lookup into dependent bases in static methods or 2075 // contexts where 'this' is available. 2076 QualType ThisType = S.getCurrentThisType(); 2077 const CXXRecordDecl *RD = nullptr; 2078 if (!ThisType.isNull()) 2079 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2080 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2081 RD = MD->getParent(); 2082 if (!RD || !RD->hasAnyDependentBases()) 2083 return nullptr; 2084 2085 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2086 // is available, suggest inserting 'this->' as a fixit. 2087 SourceLocation Loc = NameInfo.getLoc(); 2088 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2089 DB << NameInfo.getName() << RD; 2090 2091 if (!ThisType.isNull()) { 2092 DB << FixItHint::CreateInsertion(Loc, "this->"); 2093 return CXXDependentScopeMemberExpr::Create( 2094 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2095 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2096 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2097 } 2098 2099 // Synthesize a fake NNS that points to the derived class. This will 2100 // perform name lookup during template instantiation. 2101 CXXScopeSpec SS; 2102 auto *NNS = 2103 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2104 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2105 return DependentScopeDeclRefExpr::Create( 2106 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2107 TemplateArgs); 2108 } 2109 2110 ExprResult 2111 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2112 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2113 bool HasTrailingLParen, bool IsAddressOfOperand, 2114 std::unique_ptr<CorrectionCandidateCallback> CCC, 2115 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2116 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2117 "cannot be direct & operand and have a trailing lparen"); 2118 if (SS.isInvalid()) 2119 return ExprError(); 2120 2121 TemplateArgumentListInfo TemplateArgsBuffer; 2122 2123 // Decompose the UnqualifiedId into the following data. 2124 DeclarationNameInfo NameInfo; 2125 const TemplateArgumentListInfo *TemplateArgs; 2126 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2127 2128 DeclarationName Name = NameInfo.getName(); 2129 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2130 SourceLocation NameLoc = NameInfo.getLoc(); 2131 2132 // C++ [temp.dep.expr]p3: 2133 // An id-expression is type-dependent if it contains: 2134 // -- an identifier that was declared with a dependent type, 2135 // (note: handled after lookup) 2136 // -- a template-id that is dependent, 2137 // (note: handled in BuildTemplateIdExpr) 2138 // -- a conversion-function-id that specifies a dependent type, 2139 // -- a nested-name-specifier that contains a class-name that 2140 // names a dependent type. 2141 // Determine whether this is a member of an unknown specialization; 2142 // we need to handle these differently. 2143 bool DependentID = false; 2144 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2145 Name.getCXXNameType()->isDependentType()) { 2146 DependentID = true; 2147 } else if (SS.isSet()) { 2148 if (DeclContext *DC = computeDeclContext(SS, false)) { 2149 if (RequireCompleteDeclContext(SS, DC)) 2150 return ExprError(); 2151 } else { 2152 DependentID = true; 2153 } 2154 } 2155 2156 if (DependentID) 2157 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2158 IsAddressOfOperand, TemplateArgs); 2159 2160 // Perform the required lookup. 2161 LookupResult R(*this, NameInfo, 2162 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2163 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2164 if (TemplateArgs) { 2165 // Lookup the template name again to correctly establish the context in 2166 // which it was found. This is really unfortunate as we already did the 2167 // lookup to determine that it was a template name in the first place. If 2168 // this becomes a performance hit, we can work harder to preserve those 2169 // results until we get here but it's likely not worth it. 2170 bool MemberOfUnknownSpecialization; 2171 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2172 MemberOfUnknownSpecialization); 2173 2174 if (MemberOfUnknownSpecialization || 2175 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2176 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2177 IsAddressOfOperand, TemplateArgs); 2178 } else { 2179 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2180 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2181 2182 // If the result might be in a dependent base class, this is a dependent 2183 // id-expression. 2184 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2185 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2186 IsAddressOfOperand, TemplateArgs); 2187 2188 // If this reference is in an Objective-C method, then we need to do 2189 // some special Objective-C lookup, too. 2190 if (IvarLookupFollowUp) { 2191 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2192 if (E.isInvalid()) 2193 return ExprError(); 2194 2195 if (Expr *Ex = E.getAs<Expr>()) 2196 return Ex; 2197 } 2198 } 2199 2200 if (R.isAmbiguous()) 2201 return ExprError(); 2202 2203 // This could be an implicitly declared function reference (legal in C90, 2204 // extension in C99, forbidden in C++). 2205 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2206 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2207 if (D) R.addDecl(D); 2208 } 2209 2210 // Determine whether this name might be a candidate for 2211 // argument-dependent lookup. 2212 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2213 2214 if (R.empty() && !ADL) { 2215 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2216 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2217 TemplateKWLoc, TemplateArgs)) 2218 return E; 2219 } 2220 2221 // Don't diagnose an empty lookup for inline assembly. 2222 if (IsInlineAsmIdentifier) 2223 return ExprError(); 2224 2225 // If this name wasn't predeclared and if this is not a function 2226 // call, diagnose the problem. 2227 TypoExpr *TE = nullptr; 2228 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2229 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2230 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2231 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2232 "Typo correction callback misconfigured"); 2233 if (CCC) { 2234 // Make sure the callback knows what the typo being diagnosed is. 2235 CCC->setTypoName(II); 2236 if (SS.isValid()) 2237 CCC->setTypoNNS(SS.getScopeRep()); 2238 } 2239 if (DiagnoseEmptyLookup(S, SS, R, 2240 CCC ? std::move(CCC) : std::move(DefaultValidator), 2241 nullptr, None, &TE)) { 2242 if (TE && KeywordReplacement) { 2243 auto &State = getTypoExprState(TE); 2244 auto BestTC = State.Consumer->getNextCorrection(); 2245 if (BestTC.isKeyword()) { 2246 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2247 if (State.DiagHandler) 2248 State.DiagHandler(BestTC); 2249 KeywordReplacement->startToken(); 2250 KeywordReplacement->setKind(II->getTokenID()); 2251 KeywordReplacement->setIdentifierInfo(II); 2252 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2253 // Clean up the state associated with the TypoExpr, since it has 2254 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2255 clearDelayedTypo(TE); 2256 // Signal that a correction to a keyword was performed by returning a 2257 // valid-but-null ExprResult. 2258 return (Expr*)nullptr; 2259 } 2260 State.Consumer->resetCorrectionStream(); 2261 } 2262 return TE ? TE : ExprError(); 2263 } 2264 2265 assert(!R.empty() && 2266 "DiagnoseEmptyLookup returned false but added no results"); 2267 2268 // If we found an Objective-C instance variable, let 2269 // LookupInObjCMethod build the appropriate expression to 2270 // reference the ivar. 2271 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2272 R.clear(); 2273 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2274 // In a hopelessly buggy code, Objective-C instance variable 2275 // lookup fails and no expression will be built to reference it. 2276 if (!E.isInvalid() && !E.get()) 2277 return ExprError(); 2278 return E; 2279 } 2280 } 2281 2282 // This is guaranteed from this point on. 2283 assert(!R.empty() || ADL); 2284 2285 // Check whether this might be a C++ implicit instance member access. 2286 // C++ [class.mfct.non-static]p3: 2287 // When an id-expression that is not part of a class member access 2288 // syntax and not used to form a pointer to member is used in the 2289 // body of a non-static member function of class X, if name lookup 2290 // resolves the name in the id-expression to a non-static non-type 2291 // member of some class C, the id-expression is transformed into a 2292 // class member access expression using (*this) as the 2293 // postfix-expression to the left of the . operator. 2294 // 2295 // But we don't actually need to do this for '&' operands if R 2296 // resolved to a function or overloaded function set, because the 2297 // expression is ill-formed if it actually works out to be a 2298 // non-static member function: 2299 // 2300 // C++ [expr.ref]p4: 2301 // Otherwise, if E1.E2 refers to a non-static member function. . . 2302 // [t]he expression can be used only as the left-hand operand of a 2303 // member function call. 2304 // 2305 // There are other safeguards against such uses, but it's important 2306 // to get this right here so that we don't end up making a 2307 // spuriously dependent expression if we're inside a dependent 2308 // instance method. 2309 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2310 bool MightBeImplicitMember; 2311 if (!IsAddressOfOperand) 2312 MightBeImplicitMember = true; 2313 else if (!SS.isEmpty()) 2314 MightBeImplicitMember = false; 2315 else if (R.isOverloadedResult()) 2316 MightBeImplicitMember = false; 2317 else if (R.isUnresolvableResult()) 2318 MightBeImplicitMember = true; 2319 else 2320 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2321 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2322 isa<MSPropertyDecl>(R.getFoundDecl()); 2323 2324 if (MightBeImplicitMember) 2325 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2326 R, TemplateArgs, S); 2327 } 2328 2329 if (TemplateArgs || TemplateKWLoc.isValid()) { 2330 2331 // In C++1y, if this is a variable template id, then check it 2332 // in BuildTemplateIdExpr(). 2333 // The single lookup result must be a variable template declaration. 2334 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2335 Id.TemplateId->Kind == TNK_Var_template) { 2336 assert(R.getAsSingle<VarTemplateDecl>() && 2337 "There should only be one declaration found."); 2338 } 2339 2340 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2341 } 2342 2343 return BuildDeclarationNameExpr(SS, R, ADL); 2344 } 2345 2346 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2347 /// declaration name, generally during template instantiation. 2348 /// There's a large number of things which don't need to be done along 2349 /// this path. 2350 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2351 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2352 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2353 DeclContext *DC = computeDeclContext(SS, false); 2354 if (!DC) 2355 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2356 NameInfo, /*TemplateArgs=*/nullptr); 2357 2358 if (RequireCompleteDeclContext(SS, DC)) 2359 return ExprError(); 2360 2361 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2362 LookupQualifiedName(R, DC); 2363 2364 if (R.isAmbiguous()) 2365 return ExprError(); 2366 2367 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2368 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2369 NameInfo, /*TemplateArgs=*/nullptr); 2370 2371 if (R.empty()) { 2372 Diag(NameInfo.getLoc(), diag::err_no_member) 2373 << NameInfo.getName() << DC << SS.getRange(); 2374 return ExprError(); 2375 } 2376 2377 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2378 // Diagnose a missing typename if this resolved unambiguously to a type in 2379 // a dependent context. If we can recover with a type, downgrade this to 2380 // a warning in Microsoft compatibility mode. 2381 unsigned DiagID = diag::err_typename_missing; 2382 if (RecoveryTSI && getLangOpts().MSVCCompat) 2383 DiagID = diag::ext_typename_missing; 2384 SourceLocation Loc = SS.getBeginLoc(); 2385 auto D = Diag(Loc, DiagID); 2386 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2387 << SourceRange(Loc, NameInfo.getEndLoc()); 2388 2389 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2390 // context. 2391 if (!RecoveryTSI) 2392 return ExprError(); 2393 2394 // Only issue the fixit if we're prepared to recover. 2395 D << FixItHint::CreateInsertion(Loc, "typename "); 2396 2397 // Recover by pretending this was an elaborated type. 2398 QualType Ty = Context.getTypeDeclType(TD); 2399 TypeLocBuilder TLB; 2400 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2401 2402 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2403 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2404 QTL.setElaboratedKeywordLoc(SourceLocation()); 2405 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2406 2407 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2408 2409 return ExprEmpty(); 2410 } 2411 2412 // Defend against this resolving to an implicit member access. We usually 2413 // won't get here if this might be a legitimate a class member (we end up in 2414 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2415 // a pointer-to-member or in an unevaluated context in C++11. 2416 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2417 return BuildPossibleImplicitMemberExpr(SS, 2418 /*TemplateKWLoc=*/SourceLocation(), 2419 R, /*TemplateArgs=*/nullptr, S); 2420 2421 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2422 } 2423 2424 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2425 /// detected that we're currently inside an ObjC method. Perform some 2426 /// additional lookup. 2427 /// 2428 /// Ideally, most of this would be done by lookup, but there's 2429 /// actually quite a lot of extra work involved. 2430 /// 2431 /// Returns a null sentinel to indicate trivial success. 2432 ExprResult 2433 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2434 IdentifierInfo *II, bool AllowBuiltinCreation) { 2435 SourceLocation Loc = Lookup.getNameLoc(); 2436 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2437 2438 // Check for error condition which is already reported. 2439 if (!CurMethod) 2440 return ExprError(); 2441 2442 // There are two cases to handle here. 1) scoped lookup could have failed, 2443 // in which case we should look for an ivar. 2) scoped lookup could have 2444 // found a decl, but that decl is outside the current instance method (i.e. 2445 // a global variable). In these two cases, we do a lookup for an ivar with 2446 // this name, if the lookup sucedes, we replace it our current decl. 2447 2448 // If we're in a class method, we don't normally want to look for 2449 // ivars. But if we don't find anything else, and there's an 2450 // ivar, that's an error. 2451 bool IsClassMethod = CurMethod->isClassMethod(); 2452 2453 bool LookForIvars; 2454 if (Lookup.empty()) 2455 LookForIvars = true; 2456 else if (IsClassMethod) 2457 LookForIvars = false; 2458 else 2459 LookForIvars = (Lookup.isSingleResult() && 2460 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2461 ObjCInterfaceDecl *IFace = nullptr; 2462 if (LookForIvars) { 2463 IFace = CurMethod->getClassInterface(); 2464 ObjCInterfaceDecl *ClassDeclared; 2465 ObjCIvarDecl *IV = nullptr; 2466 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2467 // Diagnose using an ivar in a class method. 2468 if (IsClassMethod) 2469 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2470 << IV->getDeclName()); 2471 2472 // If we're referencing an invalid decl, just return this as a silent 2473 // error node. The error diagnostic was already emitted on the decl. 2474 if (IV->isInvalidDecl()) 2475 return ExprError(); 2476 2477 // Check if referencing a field with __attribute__((deprecated)). 2478 if (DiagnoseUseOfDecl(IV, Loc)) 2479 return ExprError(); 2480 2481 // Diagnose the use of an ivar outside of the declaring class. 2482 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2483 !declaresSameEntity(ClassDeclared, IFace) && 2484 !getLangOpts().DebuggerSupport) 2485 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2486 2487 // FIXME: This should use a new expr for a direct reference, don't 2488 // turn this into Self->ivar, just return a BareIVarExpr or something. 2489 IdentifierInfo &II = Context.Idents.get("self"); 2490 UnqualifiedId SelfName; 2491 SelfName.setIdentifier(&II, SourceLocation()); 2492 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2493 CXXScopeSpec SelfScopeSpec; 2494 SourceLocation TemplateKWLoc; 2495 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2496 SelfName, false, false); 2497 if (SelfExpr.isInvalid()) 2498 return ExprError(); 2499 2500 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2501 if (SelfExpr.isInvalid()) 2502 return ExprError(); 2503 2504 MarkAnyDeclReferenced(Loc, IV, true); 2505 2506 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2507 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2508 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2509 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2510 2511 ObjCIvarRefExpr *Result = new (Context) 2512 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2513 IV->getLocation(), SelfExpr.get(), true, true); 2514 2515 if (getLangOpts().ObjCAutoRefCount) { 2516 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2517 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2518 recordUseOfEvaluatedWeak(Result); 2519 } 2520 if (CurContext->isClosure()) 2521 Diag(Loc, diag::warn_implicitly_retains_self) 2522 << FixItHint::CreateInsertion(Loc, "self->"); 2523 } 2524 2525 return Result; 2526 } 2527 } else if (CurMethod->isInstanceMethod()) { 2528 // We should warn if a local variable hides an ivar. 2529 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2530 ObjCInterfaceDecl *ClassDeclared; 2531 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2532 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2533 declaresSameEntity(IFace, ClassDeclared)) 2534 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2535 } 2536 } 2537 } else if (Lookup.isSingleResult() && 2538 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2539 // If accessing a stand-alone ivar in a class method, this is an error. 2540 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2541 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2542 << IV->getDeclName()); 2543 } 2544 2545 if (Lookup.empty() && II && AllowBuiltinCreation) { 2546 // FIXME. Consolidate this with similar code in LookupName. 2547 if (unsigned BuiltinID = II->getBuiltinID()) { 2548 if (!(getLangOpts().CPlusPlus && 2549 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2550 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2551 S, Lookup.isForRedeclaration(), 2552 Lookup.getNameLoc()); 2553 if (D) Lookup.addDecl(D); 2554 } 2555 } 2556 } 2557 // Sentinel value saying that we didn't do anything special. 2558 return ExprResult((Expr *)nullptr); 2559 } 2560 2561 /// \brief Cast a base object to a member's actual type. 2562 /// 2563 /// Logically this happens in three phases: 2564 /// 2565 /// * First we cast from the base type to the naming class. 2566 /// The naming class is the class into which we were looking 2567 /// when we found the member; it's the qualifier type if a 2568 /// qualifier was provided, and otherwise it's the base type. 2569 /// 2570 /// * Next we cast from the naming class to the declaring class. 2571 /// If the member we found was brought into a class's scope by 2572 /// a using declaration, this is that class; otherwise it's 2573 /// the class declaring the member. 2574 /// 2575 /// * Finally we cast from the declaring class to the "true" 2576 /// declaring class of the member. This conversion does not 2577 /// obey access control. 2578 ExprResult 2579 Sema::PerformObjectMemberConversion(Expr *From, 2580 NestedNameSpecifier *Qualifier, 2581 NamedDecl *FoundDecl, 2582 NamedDecl *Member) { 2583 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2584 if (!RD) 2585 return From; 2586 2587 QualType DestRecordType; 2588 QualType DestType; 2589 QualType FromRecordType; 2590 QualType FromType = From->getType(); 2591 bool PointerConversions = false; 2592 if (isa<FieldDecl>(Member)) { 2593 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2594 2595 if (FromType->getAs<PointerType>()) { 2596 DestType = Context.getPointerType(DestRecordType); 2597 FromRecordType = FromType->getPointeeType(); 2598 PointerConversions = true; 2599 } else { 2600 DestType = DestRecordType; 2601 FromRecordType = FromType; 2602 } 2603 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2604 if (Method->isStatic()) 2605 return From; 2606 2607 DestType = Method->getThisType(Context); 2608 DestRecordType = DestType->getPointeeType(); 2609 2610 if (FromType->getAs<PointerType>()) { 2611 FromRecordType = FromType->getPointeeType(); 2612 PointerConversions = true; 2613 } else { 2614 FromRecordType = FromType; 2615 DestType = DestRecordType; 2616 } 2617 } else { 2618 // No conversion necessary. 2619 return From; 2620 } 2621 2622 if (DestType->isDependentType() || FromType->isDependentType()) 2623 return From; 2624 2625 // If the unqualified types are the same, no conversion is necessary. 2626 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2627 return From; 2628 2629 SourceRange FromRange = From->getSourceRange(); 2630 SourceLocation FromLoc = FromRange.getBegin(); 2631 2632 ExprValueKind VK = From->getValueKind(); 2633 2634 // C++ [class.member.lookup]p8: 2635 // [...] Ambiguities can often be resolved by qualifying a name with its 2636 // class name. 2637 // 2638 // If the member was a qualified name and the qualified referred to a 2639 // specific base subobject type, we'll cast to that intermediate type 2640 // first and then to the object in which the member is declared. That allows 2641 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2642 // 2643 // class Base { public: int x; }; 2644 // class Derived1 : public Base { }; 2645 // class Derived2 : public Base { }; 2646 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2647 // 2648 // void VeryDerived::f() { 2649 // x = 17; // error: ambiguous base subobjects 2650 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2651 // } 2652 if (Qualifier && Qualifier->getAsType()) { 2653 QualType QType = QualType(Qualifier->getAsType(), 0); 2654 assert(QType->isRecordType() && "lookup done with non-record type"); 2655 2656 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2657 2658 // In C++98, the qualifier type doesn't actually have to be a base 2659 // type of the object type, in which case we just ignore it. 2660 // Otherwise build the appropriate casts. 2661 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2662 CXXCastPath BasePath; 2663 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2664 FromLoc, FromRange, &BasePath)) 2665 return ExprError(); 2666 2667 if (PointerConversions) 2668 QType = Context.getPointerType(QType); 2669 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2670 VK, &BasePath).get(); 2671 2672 FromType = QType; 2673 FromRecordType = QRecordType; 2674 2675 // If the qualifier type was the same as the destination type, 2676 // we're done. 2677 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2678 return From; 2679 } 2680 } 2681 2682 bool IgnoreAccess = false; 2683 2684 // If we actually found the member through a using declaration, cast 2685 // down to the using declaration's type. 2686 // 2687 // Pointer equality is fine here because only one declaration of a 2688 // class ever has member declarations. 2689 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2690 assert(isa<UsingShadowDecl>(FoundDecl)); 2691 QualType URecordType = Context.getTypeDeclType( 2692 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2693 2694 // We only need to do this if the naming-class to declaring-class 2695 // conversion is non-trivial. 2696 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2697 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2698 CXXCastPath BasePath; 2699 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2700 FromLoc, FromRange, &BasePath)) 2701 return ExprError(); 2702 2703 QualType UType = URecordType; 2704 if (PointerConversions) 2705 UType = Context.getPointerType(UType); 2706 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2707 VK, &BasePath).get(); 2708 FromType = UType; 2709 FromRecordType = URecordType; 2710 } 2711 2712 // We don't do access control for the conversion from the 2713 // declaring class to the true declaring class. 2714 IgnoreAccess = true; 2715 } 2716 2717 CXXCastPath BasePath; 2718 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2719 FromLoc, FromRange, &BasePath, 2720 IgnoreAccess)) 2721 return ExprError(); 2722 2723 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2724 VK, &BasePath); 2725 } 2726 2727 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2728 const LookupResult &R, 2729 bool HasTrailingLParen) { 2730 // Only when used directly as the postfix-expression of a call. 2731 if (!HasTrailingLParen) 2732 return false; 2733 2734 // Never if a scope specifier was provided. 2735 if (SS.isSet()) 2736 return false; 2737 2738 // Only in C++ or ObjC++. 2739 if (!getLangOpts().CPlusPlus) 2740 return false; 2741 2742 // Turn off ADL when we find certain kinds of declarations during 2743 // normal lookup: 2744 for (NamedDecl *D : R) { 2745 // C++0x [basic.lookup.argdep]p3: 2746 // -- a declaration of a class member 2747 // Since using decls preserve this property, we check this on the 2748 // original decl. 2749 if (D->isCXXClassMember()) 2750 return false; 2751 2752 // C++0x [basic.lookup.argdep]p3: 2753 // -- a block-scope function declaration that is not a 2754 // using-declaration 2755 // NOTE: we also trigger this for function templates (in fact, we 2756 // don't check the decl type at all, since all other decl types 2757 // turn off ADL anyway). 2758 if (isa<UsingShadowDecl>(D)) 2759 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2760 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2761 return false; 2762 2763 // C++0x [basic.lookup.argdep]p3: 2764 // -- a declaration that is neither a function or a function 2765 // template 2766 // And also for builtin functions. 2767 if (isa<FunctionDecl>(D)) { 2768 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2769 2770 // But also builtin functions. 2771 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2772 return false; 2773 } else if (!isa<FunctionTemplateDecl>(D)) 2774 return false; 2775 } 2776 2777 return true; 2778 } 2779 2780 2781 /// Diagnoses obvious problems with the use of the given declaration 2782 /// as an expression. This is only actually called for lookups that 2783 /// were not overloaded, and it doesn't promise that the declaration 2784 /// will in fact be used. 2785 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2786 if (isa<TypedefNameDecl>(D)) { 2787 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2788 return true; 2789 } 2790 2791 if (isa<ObjCInterfaceDecl>(D)) { 2792 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2793 return true; 2794 } 2795 2796 if (isa<NamespaceDecl>(D)) { 2797 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2798 return true; 2799 } 2800 2801 return false; 2802 } 2803 2804 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2805 LookupResult &R, bool NeedsADL, 2806 bool AcceptInvalidDecl) { 2807 // If this is a single, fully-resolved result and we don't need ADL, 2808 // just build an ordinary singleton decl ref. 2809 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2810 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2811 R.getRepresentativeDecl(), nullptr, 2812 AcceptInvalidDecl); 2813 2814 // We only need to check the declaration if there's exactly one 2815 // result, because in the overloaded case the results can only be 2816 // functions and function templates. 2817 if (R.isSingleResult() && 2818 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2819 return ExprError(); 2820 2821 // Otherwise, just build an unresolved lookup expression. Suppress 2822 // any lookup-related diagnostics; we'll hash these out later, when 2823 // we've picked a target. 2824 R.suppressDiagnostics(); 2825 2826 UnresolvedLookupExpr *ULE 2827 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2828 SS.getWithLocInContext(Context), 2829 R.getLookupNameInfo(), 2830 NeedsADL, R.isOverloadedResult(), 2831 R.begin(), R.end()); 2832 2833 return ULE; 2834 } 2835 2836 static void 2837 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2838 ValueDecl *var, DeclContext *DC); 2839 2840 /// \brief Complete semantic analysis for a reference to the given declaration. 2841 ExprResult Sema::BuildDeclarationNameExpr( 2842 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2843 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2844 bool AcceptInvalidDecl) { 2845 assert(D && "Cannot refer to a NULL declaration"); 2846 assert(!isa<FunctionTemplateDecl>(D) && 2847 "Cannot refer unambiguously to a function template"); 2848 2849 SourceLocation Loc = NameInfo.getLoc(); 2850 if (CheckDeclInExpr(*this, Loc, D)) 2851 return ExprError(); 2852 2853 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2854 // Specifically diagnose references to class templates that are missing 2855 // a template argument list. 2856 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2857 << Template << SS.getRange(); 2858 Diag(Template->getLocation(), diag::note_template_decl_here); 2859 return ExprError(); 2860 } 2861 2862 // Make sure that we're referring to a value. 2863 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2864 if (!VD) { 2865 Diag(Loc, diag::err_ref_non_value) 2866 << D << SS.getRange(); 2867 Diag(D->getLocation(), diag::note_declared_at); 2868 return ExprError(); 2869 } 2870 2871 // Check whether this declaration can be used. Note that we suppress 2872 // this check when we're going to perform argument-dependent lookup 2873 // on this function name, because this might not be the function 2874 // that overload resolution actually selects. 2875 if (DiagnoseUseOfDecl(VD, Loc)) 2876 return ExprError(); 2877 2878 // Only create DeclRefExpr's for valid Decl's. 2879 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2880 return ExprError(); 2881 2882 // Handle members of anonymous structs and unions. If we got here, 2883 // and the reference is to a class member indirect field, then this 2884 // must be the subject of a pointer-to-member expression. 2885 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2886 if (!indirectField->isCXXClassMember()) 2887 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2888 indirectField); 2889 2890 { 2891 QualType type = VD->getType(); 2892 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2893 // C++ [except.spec]p17: 2894 // An exception-specification is considered to be needed when: 2895 // - in an expression, the function is the unique lookup result or 2896 // the selected member of a set of overloaded functions. 2897 ResolveExceptionSpec(Loc, FPT); 2898 type = VD->getType(); 2899 } 2900 ExprValueKind valueKind = VK_RValue; 2901 2902 switch (D->getKind()) { 2903 // Ignore all the non-ValueDecl kinds. 2904 #define ABSTRACT_DECL(kind) 2905 #define VALUE(type, base) 2906 #define DECL(type, base) \ 2907 case Decl::type: 2908 #include "clang/AST/DeclNodes.inc" 2909 llvm_unreachable("invalid value decl kind"); 2910 2911 // These shouldn't make it here. 2912 case Decl::ObjCAtDefsField: 2913 case Decl::ObjCIvar: 2914 llvm_unreachable("forming non-member reference to ivar?"); 2915 2916 // Enum constants are always r-values and never references. 2917 // Unresolved using declarations are dependent. 2918 case Decl::EnumConstant: 2919 case Decl::UnresolvedUsingValue: 2920 case Decl::OMPDeclareReduction: 2921 valueKind = VK_RValue; 2922 break; 2923 2924 // Fields and indirect fields that got here must be for 2925 // pointer-to-member expressions; we just call them l-values for 2926 // internal consistency, because this subexpression doesn't really 2927 // exist in the high-level semantics. 2928 case Decl::Field: 2929 case Decl::IndirectField: 2930 assert(getLangOpts().CPlusPlus && 2931 "building reference to field in C?"); 2932 2933 // These can't have reference type in well-formed programs, but 2934 // for internal consistency we do this anyway. 2935 type = type.getNonReferenceType(); 2936 valueKind = VK_LValue; 2937 break; 2938 2939 // Non-type template parameters are either l-values or r-values 2940 // depending on the type. 2941 case Decl::NonTypeTemplateParm: { 2942 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2943 type = reftype->getPointeeType(); 2944 valueKind = VK_LValue; // even if the parameter is an r-value reference 2945 break; 2946 } 2947 2948 // For non-references, we need to strip qualifiers just in case 2949 // the template parameter was declared as 'const int' or whatever. 2950 valueKind = VK_RValue; 2951 type = type.getUnqualifiedType(); 2952 break; 2953 } 2954 2955 case Decl::Var: 2956 case Decl::VarTemplateSpecialization: 2957 case Decl::VarTemplatePartialSpecialization: 2958 case Decl::Decomposition: 2959 case Decl::OMPCapturedExpr: 2960 // In C, "extern void blah;" is valid and is an r-value. 2961 if (!getLangOpts().CPlusPlus && 2962 !type.hasQualifiers() && 2963 type->isVoidType()) { 2964 valueKind = VK_RValue; 2965 break; 2966 } 2967 // fallthrough 2968 2969 case Decl::ImplicitParam: 2970 case Decl::ParmVar: { 2971 // These are always l-values. 2972 valueKind = VK_LValue; 2973 type = type.getNonReferenceType(); 2974 2975 // FIXME: Does the addition of const really only apply in 2976 // potentially-evaluated contexts? Since the variable isn't actually 2977 // captured in an unevaluated context, it seems that the answer is no. 2978 if (!isUnevaluatedContext()) { 2979 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2980 if (!CapturedType.isNull()) 2981 type = CapturedType; 2982 } 2983 2984 break; 2985 } 2986 2987 case Decl::Binding: { 2988 // These are always lvalues. 2989 valueKind = VK_LValue; 2990 type = type.getNonReferenceType(); 2991 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2992 // decides how that's supposed to work. 2993 auto *BD = cast<BindingDecl>(VD); 2994 if (BD->getDeclContext()->isFunctionOrMethod() && 2995 BD->getDeclContext() != CurContext) 2996 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2997 break; 2998 } 2999 3000 case Decl::Function: { 3001 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3002 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3003 type = Context.BuiltinFnTy; 3004 valueKind = VK_RValue; 3005 break; 3006 } 3007 } 3008 3009 const FunctionType *fty = type->castAs<FunctionType>(); 3010 3011 // If we're referring to a function with an __unknown_anytype 3012 // result type, make the entire expression __unknown_anytype. 3013 if (fty->getReturnType() == Context.UnknownAnyTy) { 3014 type = Context.UnknownAnyTy; 3015 valueKind = VK_RValue; 3016 break; 3017 } 3018 3019 // Functions are l-values in C++. 3020 if (getLangOpts().CPlusPlus) { 3021 valueKind = VK_LValue; 3022 break; 3023 } 3024 3025 // C99 DR 316 says that, if a function type comes from a 3026 // function definition (without a prototype), that type is only 3027 // used for checking compatibility. Therefore, when referencing 3028 // the function, we pretend that we don't have the full function 3029 // type. 3030 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3031 isa<FunctionProtoType>(fty)) 3032 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3033 fty->getExtInfo()); 3034 3035 // Functions are r-values in C. 3036 valueKind = VK_RValue; 3037 break; 3038 } 3039 3040 case Decl::MSProperty: 3041 valueKind = VK_LValue; 3042 break; 3043 3044 case Decl::CXXMethod: 3045 // If we're referring to a method with an __unknown_anytype 3046 // result type, make the entire expression __unknown_anytype. 3047 // This should only be possible with a type written directly. 3048 if (const FunctionProtoType *proto 3049 = dyn_cast<FunctionProtoType>(VD->getType())) 3050 if (proto->getReturnType() == Context.UnknownAnyTy) { 3051 type = Context.UnknownAnyTy; 3052 valueKind = VK_RValue; 3053 break; 3054 } 3055 3056 // C++ methods are l-values if static, r-values if non-static. 3057 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3058 valueKind = VK_LValue; 3059 break; 3060 } 3061 // fallthrough 3062 3063 case Decl::CXXConversion: 3064 case Decl::CXXDestructor: 3065 case Decl::CXXConstructor: 3066 valueKind = VK_RValue; 3067 break; 3068 } 3069 3070 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3071 TemplateArgs); 3072 } 3073 } 3074 3075 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3076 SmallString<32> &Target) { 3077 Target.resize(CharByteWidth * (Source.size() + 1)); 3078 char *ResultPtr = &Target[0]; 3079 const llvm::UTF8 *ErrorPtr; 3080 bool success = 3081 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3082 (void)success; 3083 assert(success); 3084 Target.resize(ResultPtr - &Target[0]); 3085 } 3086 3087 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3088 PredefinedExpr::IdentType IT) { 3089 // Pick the current block, lambda, captured statement or function. 3090 Decl *currentDecl = nullptr; 3091 if (const BlockScopeInfo *BSI = getCurBlock()) 3092 currentDecl = BSI->TheDecl; 3093 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3094 currentDecl = LSI->CallOperator; 3095 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3096 currentDecl = CSI->TheCapturedDecl; 3097 else 3098 currentDecl = getCurFunctionOrMethodDecl(); 3099 3100 if (!currentDecl) { 3101 Diag(Loc, diag::ext_predef_outside_function); 3102 currentDecl = Context.getTranslationUnitDecl(); 3103 } 3104 3105 QualType ResTy; 3106 StringLiteral *SL = nullptr; 3107 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3108 ResTy = Context.DependentTy; 3109 else { 3110 // Pre-defined identifiers are of type char[x], where x is the length of 3111 // the string. 3112 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3113 unsigned Length = Str.length(); 3114 3115 llvm::APInt LengthI(32, Length + 1); 3116 if (IT == PredefinedExpr::LFunction) { 3117 ResTy = Context.WideCharTy.withConst(); 3118 SmallString<32> RawChars; 3119 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3120 Str, RawChars); 3121 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3122 /*IndexTypeQuals*/ 0); 3123 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3124 /*Pascal*/ false, ResTy, Loc); 3125 } else { 3126 ResTy = Context.CharTy.withConst(); 3127 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3128 /*IndexTypeQuals*/ 0); 3129 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3130 /*Pascal*/ false, ResTy, Loc); 3131 } 3132 } 3133 3134 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3135 } 3136 3137 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3138 PredefinedExpr::IdentType IT; 3139 3140 switch (Kind) { 3141 default: llvm_unreachable("Unknown simple primary expr!"); 3142 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3143 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3144 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3145 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3146 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3147 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3148 } 3149 3150 return BuildPredefinedExpr(Loc, IT); 3151 } 3152 3153 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3154 SmallString<16> CharBuffer; 3155 bool Invalid = false; 3156 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3157 if (Invalid) 3158 return ExprError(); 3159 3160 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3161 PP, Tok.getKind()); 3162 if (Literal.hadError()) 3163 return ExprError(); 3164 3165 QualType Ty; 3166 if (Literal.isWide()) 3167 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3168 else if (Literal.isUTF16()) 3169 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3170 else if (Literal.isUTF32()) 3171 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3172 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3173 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3174 else 3175 Ty = Context.CharTy; // 'x' -> char in C++ 3176 3177 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3178 if (Literal.isWide()) 3179 Kind = CharacterLiteral::Wide; 3180 else if (Literal.isUTF16()) 3181 Kind = CharacterLiteral::UTF16; 3182 else if (Literal.isUTF32()) 3183 Kind = CharacterLiteral::UTF32; 3184 else if (Literal.isUTF8()) 3185 Kind = CharacterLiteral::UTF8; 3186 3187 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3188 Tok.getLocation()); 3189 3190 if (Literal.getUDSuffix().empty()) 3191 return Lit; 3192 3193 // We're building a user-defined literal. 3194 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3195 SourceLocation UDSuffixLoc = 3196 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3197 3198 // Make sure we're allowed user-defined literals here. 3199 if (!UDLScope) 3200 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3201 3202 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3203 // operator "" X (ch) 3204 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3205 Lit, Tok.getLocation()); 3206 } 3207 3208 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3209 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3210 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3211 Context.IntTy, Loc); 3212 } 3213 3214 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3215 QualType Ty, SourceLocation Loc) { 3216 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3217 3218 using llvm::APFloat; 3219 APFloat Val(Format); 3220 3221 APFloat::opStatus result = Literal.GetFloatValue(Val); 3222 3223 // Overflow is always an error, but underflow is only an error if 3224 // we underflowed to zero (APFloat reports denormals as underflow). 3225 if ((result & APFloat::opOverflow) || 3226 ((result & APFloat::opUnderflow) && Val.isZero())) { 3227 unsigned diagnostic; 3228 SmallString<20> buffer; 3229 if (result & APFloat::opOverflow) { 3230 diagnostic = diag::warn_float_overflow; 3231 APFloat::getLargest(Format).toString(buffer); 3232 } else { 3233 diagnostic = diag::warn_float_underflow; 3234 APFloat::getSmallest(Format).toString(buffer); 3235 } 3236 3237 S.Diag(Loc, diagnostic) 3238 << Ty 3239 << StringRef(buffer.data(), buffer.size()); 3240 } 3241 3242 bool isExact = (result == APFloat::opOK); 3243 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3244 } 3245 3246 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3247 assert(E && "Invalid expression"); 3248 3249 if (E->isValueDependent()) 3250 return false; 3251 3252 QualType QT = E->getType(); 3253 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3254 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3255 return true; 3256 } 3257 3258 llvm::APSInt ValueAPS; 3259 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3260 3261 if (R.isInvalid()) 3262 return true; 3263 3264 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3265 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3266 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3267 << ValueAPS.toString(10) << ValueIsPositive; 3268 return true; 3269 } 3270 3271 return false; 3272 } 3273 3274 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3275 // Fast path for a single digit (which is quite common). A single digit 3276 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3277 if (Tok.getLength() == 1) { 3278 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3279 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3280 } 3281 3282 SmallString<128> SpellingBuffer; 3283 // NumericLiteralParser wants to overread by one character. Add padding to 3284 // the buffer in case the token is copied to the buffer. If getSpelling() 3285 // returns a StringRef to the memory buffer, it should have a null char at 3286 // the EOF, so it is also safe. 3287 SpellingBuffer.resize(Tok.getLength() + 1); 3288 3289 // Get the spelling of the token, which eliminates trigraphs, etc. 3290 bool Invalid = false; 3291 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3292 if (Invalid) 3293 return ExprError(); 3294 3295 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3296 if (Literal.hadError) 3297 return ExprError(); 3298 3299 if (Literal.hasUDSuffix()) { 3300 // We're building a user-defined literal. 3301 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3302 SourceLocation UDSuffixLoc = 3303 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3304 3305 // Make sure we're allowed user-defined literals here. 3306 if (!UDLScope) 3307 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3308 3309 QualType CookedTy; 3310 if (Literal.isFloatingLiteral()) { 3311 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3312 // long double, the literal is treated as a call of the form 3313 // operator "" X (f L) 3314 CookedTy = Context.LongDoubleTy; 3315 } else { 3316 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3317 // unsigned long long, the literal is treated as a call of the form 3318 // operator "" X (n ULL) 3319 CookedTy = Context.UnsignedLongLongTy; 3320 } 3321 3322 DeclarationName OpName = 3323 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3324 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3325 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3326 3327 SourceLocation TokLoc = Tok.getLocation(); 3328 3329 // Perform literal operator lookup to determine if we're building a raw 3330 // literal or a cooked one. 3331 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3332 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3333 /*AllowRaw*/true, /*AllowTemplate*/true, 3334 /*AllowStringTemplate*/false)) { 3335 case LOLR_Error: 3336 return ExprError(); 3337 3338 case LOLR_Cooked: { 3339 Expr *Lit; 3340 if (Literal.isFloatingLiteral()) { 3341 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3342 } else { 3343 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3344 if (Literal.GetIntegerValue(ResultVal)) 3345 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3346 << /* Unsigned */ 1; 3347 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3348 Tok.getLocation()); 3349 } 3350 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3351 } 3352 3353 case LOLR_Raw: { 3354 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3355 // literal is treated as a call of the form 3356 // operator "" X ("n") 3357 unsigned Length = Literal.getUDSuffixOffset(); 3358 QualType StrTy = Context.getConstantArrayType( 3359 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3360 ArrayType::Normal, 0); 3361 Expr *Lit = StringLiteral::Create( 3362 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3363 /*Pascal*/false, StrTy, &TokLoc, 1); 3364 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3365 } 3366 3367 case LOLR_Template: { 3368 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3369 // template), L is treated as a call fo the form 3370 // operator "" X <'c1', 'c2', ... 'ck'>() 3371 // where n is the source character sequence c1 c2 ... ck. 3372 TemplateArgumentListInfo ExplicitArgs; 3373 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3374 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3375 llvm::APSInt Value(CharBits, CharIsUnsigned); 3376 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3377 Value = TokSpelling[I]; 3378 TemplateArgument Arg(Context, Value, Context.CharTy); 3379 TemplateArgumentLocInfo ArgInfo; 3380 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3381 } 3382 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3383 &ExplicitArgs); 3384 } 3385 case LOLR_StringTemplate: 3386 llvm_unreachable("unexpected literal operator lookup result"); 3387 } 3388 } 3389 3390 Expr *Res; 3391 3392 if (Literal.isFloatingLiteral()) { 3393 QualType Ty; 3394 if (Literal.isHalf){ 3395 if (getOpenCLOptions().cl_khr_fp16) 3396 Ty = Context.HalfTy; 3397 else { 3398 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3399 return ExprError(); 3400 } 3401 } else if (Literal.isFloat) 3402 Ty = Context.FloatTy; 3403 else if (Literal.isLong) 3404 Ty = Context.LongDoubleTy; 3405 else if (Literal.isFloat128) 3406 Ty = Context.Float128Ty; 3407 else 3408 Ty = Context.DoubleTy; 3409 3410 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3411 3412 if (Ty == Context.DoubleTy) { 3413 if (getLangOpts().SinglePrecisionConstants) { 3414 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3415 } else if (getLangOpts().OpenCL && 3416 !((getLangOpts().OpenCLVersion >= 120) || 3417 getOpenCLOptions().cl_khr_fp64)) { 3418 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3419 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3420 } 3421 } 3422 } else if (!Literal.isIntegerLiteral()) { 3423 return ExprError(); 3424 } else { 3425 QualType Ty; 3426 3427 // 'long long' is a C99 or C++11 feature. 3428 if (!getLangOpts().C99 && Literal.isLongLong) { 3429 if (getLangOpts().CPlusPlus) 3430 Diag(Tok.getLocation(), 3431 getLangOpts().CPlusPlus11 ? 3432 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3433 else 3434 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3435 } 3436 3437 // Get the value in the widest-possible width. 3438 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3439 llvm::APInt ResultVal(MaxWidth, 0); 3440 3441 if (Literal.GetIntegerValue(ResultVal)) { 3442 // If this value didn't fit into uintmax_t, error and force to ull. 3443 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3444 << /* Unsigned */ 1; 3445 Ty = Context.UnsignedLongLongTy; 3446 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3447 "long long is not intmax_t?"); 3448 } else { 3449 // If this value fits into a ULL, try to figure out what else it fits into 3450 // according to the rules of C99 6.4.4.1p5. 3451 3452 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3453 // be an unsigned int. 3454 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3455 3456 // Check from smallest to largest, picking the smallest type we can. 3457 unsigned Width = 0; 3458 3459 // Microsoft specific integer suffixes are explicitly sized. 3460 if (Literal.MicrosoftInteger) { 3461 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3462 Width = 8; 3463 Ty = Context.CharTy; 3464 } else { 3465 Width = Literal.MicrosoftInteger; 3466 Ty = Context.getIntTypeForBitwidth(Width, 3467 /*Signed=*/!Literal.isUnsigned); 3468 } 3469 } 3470 3471 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3472 // Are int/unsigned possibilities? 3473 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3474 3475 // Does it fit in a unsigned int? 3476 if (ResultVal.isIntN(IntSize)) { 3477 // Does it fit in a signed int? 3478 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3479 Ty = Context.IntTy; 3480 else if (AllowUnsigned) 3481 Ty = Context.UnsignedIntTy; 3482 Width = IntSize; 3483 } 3484 } 3485 3486 // Are long/unsigned long possibilities? 3487 if (Ty.isNull() && !Literal.isLongLong) { 3488 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3489 3490 // Does it fit in a unsigned long? 3491 if (ResultVal.isIntN(LongSize)) { 3492 // Does it fit in a signed long? 3493 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3494 Ty = Context.LongTy; 3495 else if (AllowUnsigned) 3496 Ty = Context.UnsignedLongTy; 3497 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3498 // is compatible. 3499 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3500 const unsigned LongLongSize = 3501 Context.getTargetInfo().getLongLongWidth(); 3502 Diag(Tok.getLocation(), 3503 getLangOpts().CPlusPlus 3504 ? Literal.isLong 3505 ? diag::warn_old_implicitly_unsigned_long_cxx 3506 : /*C++98 UB*/ diag:: 3507 ext_old_implicitly_unsigned_long_cxx 3508 : diag::warn_old_implicitly_unsigned_long) 3509 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3510 : /*will be ill-formed*/ 1); 3511 Ty = Context.UnsignedLongTy; 3512 } 3513 Width = LongSize; 3514 } 3515 } 3516 3517 // Check long long if needed. 3518 if (Ty.isNull()) { 3519 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3520 3521 // Does it fit in a unsigned long long? 3522 if (ResultVal.isIntN(LongLongSize)) { 3523 // Does it fit in a signed long long? 3524 // To be compatible with MSVC, hex integer literals ending with the 3525 // LL or i64 suffix are always signed in Microsoft mode. 3526 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3527 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3528 Ty = Context.LongLongTy; 3529 else if (AllowUnsigned) 3530 Ty = Context.UnsignedLongLongTy; 3531 Width = LongLongSize; 3532 } 3533 } 3534 3535 // If we still couldn't decide a type, we probably have something that 3536 // does not fit in a signed long long, but has no U suffix. 3537 if (Ty.isNull()) { 3538 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3539 Ty = Context.UnsignedLongLongTy; 3540 Width = Context.getTargetInfo().getLongLongWidth(); 3541 } 3542 3543 if (ResultVal.getBitWidth() != Width) 3544 ResultVal = ResultVal.trunc(Width); 3545 } 3546 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3547 } 3548 3549 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3550 if (Literal.isImaginary) 3551 Res = new (Context) ImaginaryLiteral(Res, 3552 Context.getComplexType(Res->getType())); 3553 3554 return Res; 3555 } 3556 3557 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3558 assert(E && "ActOnParenExpr() missing expr"); 3559 return new (Context) ParenExpr(L, R, E); 3560 } 3561 3562 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3563 SourceLocation Loc, 3564 SourceRange ArgRange) { 3565 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3566 // scalar or vector data type argument..." 3567 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3568 // type (C99 6.2.5p18) or void. 3569 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3570 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3571 << T << ArgRange; 3572 return true; 3573 } 3574 3575 assert((T->isVoidType() || !T->isIncompleteType()) && 3576 "Scalar types should always be complete"); 3577 return false; 3578 } 3579 3580 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3581 SourceLocation Loc, 3582 SourceRange ArgRange, 3583 UnaryExprOrTypeTrait TraitKind) { 3584 // Invalid types must be hard errors for SFINAE in C++. 3585 if (S.LangOpts.CPlusPlus) 3586 return true; 3587 3588 // C99 6.5.3.4p1: 3589 if (T->isFunctionType() && 3590 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3591 // sizeof(function)/alignof(function) is allowed as an extension. 3592 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3593 << TraitKind << ArgRange; 3594 return false; 3595 } 3596 3597 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3598 // this is an error (OpenCL v1.1 s6.3.k) 3599 if (T->isVoidType()) { 3600 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3601 : diag::ext_sizeof_alignof_void_type; 3602 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3603 return false; 3604 } 3605 3606 return true; 3607 } 3608 3609 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3610 SourceLocation Loc, 3611 SourceRange ArgRange, 3612 UnaryExprOrTypeTrait TraitKind) { 3613 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3614 // runtime doesn't allow it. 3615 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3616 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3617 << T << (TraitKind == UETT_SizeOf) 3618 << ArgRange; 3619 return true; 3620 } 3621 3622 return false; 3623 } 3624 3625 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3626 /// pointer type is equal to T) and emit a warning if it is. 3627 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3628 Expr *E) { 3629 // Don't warn if the operation changed the type. 3630 if (T != E->getType()) 3631 return; 3632 3633 // Now look for array decays. 3634 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3635 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3636 return; 3637 3638 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3639 << ICE->getType() 3640 << ICE->getSubExpr()->getType(); 3641 } 3642 3643 /// \brief Check the constraints on expression operands to unary type expression 3644 /// and type traits. 3645 /// 3646 /// Completes any types necessary and validates the constraints on the operand 3647 /// expression. The logic mostly mirrors the type-based overload, but may modify 3648 /// the expression as it completes the type for that expression through template 3649 /// instantiation, etc. 3650 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3651 UnaryExprOrTypeTrait ExprKind) { 3652 QualType ExprTy = E->getType(); 3653 assert(!ExprTy->isReferenceType()); 3654 3655 if (ExprKind == UETT_VecStep) 3656 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3657 E->getSourceRange()); 3658 3659 // Whitelist some types as extensions 3660 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3661 E->getSourceRange(), ExprKind)) 3662 return false; 3663 3664 // 'alignof' applied to an expression only requires the base element type of 3665 // the expression to be complete. 'sizeof' requires the expression's type to 3666 // be complete (and will attempt to complete it if it's an array of unknown 3667 // bound). 3668 if (ExprKind == UETT_AlignOf) { 3669 if (RequireCompleteType(E->getExprLoc(), 3670 Context.getBaseElementType(E->getType()), 3671 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3672 E->getSourceRange())) 3673 return true; 3674 } else { 3675 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3676 ExprKind, E->getSourceRange())) 3677 return true; 3678 } 3679 3680 // Completing the expression's type may have changed it. 3681 ExprTy = E->getType(); 3682 assert(!ExprTy->isReferenceType()); 3683 3684 if (ExprTy->isFunctionType()) { 3685 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3686 << ExprKind << E->getSourceRange(); 3687 return true; 3688 } 3689 3690 // The operand for sizeof and alignof is in an unevaluated expression context, 3691 // so side effects could result in unintended consequences. 3692 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3693 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3694 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3695 3696 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3697 E->getSourceRange(), ExprKind)) 3698 return true; 3699 3700 if (ExprKind == UETT_SizeOf) { 3701 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3702 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3703 QualType OType = PVD->getOriginalType(); 3704 QualType Type = PVD->getType(); 3705 if (Type->isPointerType() && OType->isArrayType()) { 3706 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3707 << Type << OType; 3708 Diag(PVD->getLocation(), diag::note_declared_at); 3709 } 3710 } 3711 } 3712 3713 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3714 // decays into a pointer and returns an unintended result. This is most 3715 // likely a typo for "sizeof(array) op x". 3716 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3717 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3718 BO->getLHS()); 3719 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3720 BO->getRHS()); 3721 } 3722 } 3723 3724 return false; 3725 } 3726 3727 /// \brief Check the constraints on operands to unary expression and type 3728 /// traits. 3729 /// 3730 /// This will complete any types necessary, and validate the various constraints 3731 /// on those operands. 3732 /// 3733 /// The UsualUnaryConversions() function is *not* called by this routine. 3734 /// C99 6.3.2.1p[2-4] all state: 3735 /// Except when it is the operand of the sizeof operator ... 3736 /// 3737 /// C++ [expr.sizeof]p4 3738 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3739 /// standard conversions are not applied to the operand of sizeof. 3740 /// 3741 /// This policy is followed for all of the unary trait expressions. 3742 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3743 SourceLocation OpLoc, 3744 SourceRange ExprRange, 3745 UnaryExprOrTypeTrait ExprKind) { 3746 if (ExprType->isDependentType()) 3747 return false; 3748 3749 // C++ [expr.sizeof]p2: 3750 // When applied to a reference or a reference type, the result 3751 // is the size of the referenced type. 3752 // C++11 [expr.alignof]p3: 3753 // When alignof is applied to a reference type, the result 3754 // shall be the alignment of the referenced type. 3755 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3756 ExprType = Ref->getPointeeType(); 3757 3758 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3759 // When alignof or _Alignof is applied to an array type, the result 3760 // is the alignment of the element type. 3761 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3762 ExprType = Context.getBaseElementType(ExprType); 3763 3764 if (ExprKind == UETT_VecStep) 3765 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3766 3767 // Whitelist some types as extensions 3768 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3769 ExprKind)) 3770 return false; 3771 3772 if (RequireCompleteType(OpLoc, ExprType, 3773 diag::err_sizeof_alignof_incomplete_type, 3774 ExprKind, ExprRange)) 3775 return true; 3776 3777 if (ExprType->isFunctionType()) { 3778 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3779 << ExprKind << ExprRange; 3780 return true; 3781 } 3782 3783 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3784 ExprKind)) 3785 return true; 3786 3787 return false; 3788 } 3789 3790 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3791 E = E->IgnoreParens(); 3792 3793 // Cannot know anything else if the expression is dependent. 3794 if (E->isTypeDependent()) 3795 return false; 3796 3797 if (E->getObjectKind() == OK_BitField) { 3798 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3799 << 1 << E->getSourceRange(); 3800 return true; 3801 } 3802 3803 ValueDecl *D = nullptr; 3804 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3805 D = DRE->getDecl(); 3806 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3807 D = ME->getMemberDecl(); 3808 } 3809 3810 // If it's a field, require the containing struct to have a 3811 // complete definition so that we can compute the layout. 3812 // 3813 // This can happen in C++11 onwards, either by naming the member 3814 // in a way that is not transformed into a member access expression 3815 // (in an unevaluated operand, for instance), or by naming the member 3816 // in a trailing-return-type. 3817 // 3818 // For the record, since __alignof__ on expressions is a GCC 3819 // extension, GCC seems to permit this but always gives the 3820 // nonsensical answer 0. 3821 // 3822 // We don't really need the layout here --- we could instead just 3823 // directly check for all the appropriate alignment-lowing 3824 // attributes --- but that would require duplicating a lot of 3825 // logic that just isn't worth duplicating for such a marginal 3826 // use-case. 3827 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3828 // Fast path this check, since we at least know the record has a 3829 // definition if we can find a member of it. 3830 if (!FD->getParent()->isCompleteDefinition()) { 3831 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3832 << E->getSourceRange(); 3833 return true; 3834 } 3835 3836 // Otherwise, if it's a field, and the field doesn't have 3837 // reference type, then it must have a complete type (or be a 3838 // flexible array member, which we explicitly want to 3839 // white-list anyway), which makes the following checks trivial. 3840 if (!FD->getType()->isReferenceType()) 3841 return false; 3842 } 3843 3844 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3845 } 3846 3847 bool Sema::CheckVecStepExpr(Expr *E) { 3848 E = E->IgnoreParens(); 3849 3850 // Cannot know anything else if the expression is dependent. 3851 if (E->isTypeDependent()) 3852 return false; 3853 3854 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3855 } 3856 3857 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3858 CapturingScopeInfo *CSI) { 3859 assert(T->isVariablyModifiedType()); 3860 assert(CSI != nullptr); 3861 3862 // We're going to walk down into the type and look for VLA expressions. 3863 do { 3864 const Type *Ty = T.getTypePtr(); 3865 switch (Ty->getTypeClass()) { 3866 #define TYPE(Class, Base) 3867 #define ABSTRACT_TYPE(Class, Base) 3868 #define NON_CANONICAL_TYPE(Class, Base) 3869 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3870 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3871 #include "clang/AST/TypeNodes.def" 3872 T = QualType(); 3873 break; 3874 // These types are never variably-modified. 3875 case Type::Builtin: 3876 case Type::Complex: 3877 case Type::Vector: 3878 case Type::ExtVector: 3879 case Type::Record: 3880 case Type::Enum: 3881 case Type::Elaborated: 3882 case Type::TemplateSpecialization: 3883 case Type::ObjCObject: 3884 case Type::ObjCInterface: 3885 case Type::ObjCObjectPointer: 3886 case Type::ObjCTypeParam: 3887 case Type::Pipe: 3888 llvm_unreachable("type class is never variably-modified!"); 3889 case Type::Adjusted: 3890 T = cast<AdjustedType>(Ty)->getOriginalType(); 3891 break; 3892 case Type::Decayed: 3893 T = cast<DecayedType>(Ty)->getPointeeType(); 3894 break; 3895 case Type::Pointer: 3896 T = cast<PointerType>(Ty)->getPointeeType(); 3897 break; 3898 case Type::BlockPointer: 3899 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3900 break; 3901 case Type::LValueReference: 3902 case Type::RValueReference: 3903 T = cast<ReferenceType>(Ty)->getPointeeType(); 3904 break; 3905 case Type::MemberPointer: 3906 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3907 break; 3908 case Type::ConstantArray: 3909 case Type::IncompleteArray: 3910 // Losing element qualification here is fine. 3911 T = cast<ArrayType>(Ty)->getElementType(); 3912 break; 3913 case Type::VariableArray: { 3914 // Losing element qualification here is fine. 3915 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3916 3917 // Unknown size indication requires no size computation. 3918 // Otherwise, evaluate and record it. 3919 if (auto Size = VAT->getSizeExpr()) { 3920 if (!CSI->isVLATypeCaptured(VAT)) { 3921 RecordDecl *CapRecord = nullptr; 3922 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3923 CapRecord = LSI->Lambda; 3924 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3925 CapRecord = CRSI->TheRecordDecl; 3926 } 3927 if (CapRecord) { 3928 auto ExprLoc = Size->getExprLoc(); 3929 auto SizeType = Context.getSizeType(); 3930 // Build the non-static data member. 3931 auto Field = 3932 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3933 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3934 /*BW*/ nullptr, /*Mutable*/ false, 3935 /*InitStyle*/ ICIS_NoInit); 3936 Field->setImplicit(true); 3937 Field->setAccess(AS_private); 3938 Field->setCapturedVLAType(VAT); 3939 CapRecord->addDecl(Field); 3940 3941 CSI->addVLATypeCapture(ExprLoc, SizeType); 3942 } 3943 } 3944 } 3945 T = VAT->getElementType(); 3946 break; 3947 } 3948 case Type::FunctionProto: 3949 case Type::FunctionNoProto: 3950 T = cast<FunctionType>(Ty)->getReturnType(); 3951 break; 3952 case Type::Paren: 3953 case Type::TypeOf: 3954 case Type::UnaryTransform: 3955 case Type::Attributed: 3956 case Type::SubstTemplateTypeParm: 3957 case Type::PackExpansion: 3958 // Keep walking after single level desugaring. 3959 T = T.getSingleStepDesugaredType(Context); 3960 break; 3961 case Type::Typedef: 3962 T = cast<TypedefType>(Ty)->desugar(); 3963 break; 3964 case Type::Decltype: 3965 T = cast<DecltypeType>(Ty)->desugar(); 3966 break; 3967 case Type::Auto: 3968 T = cast<AutoType>(Ty)->getDeducedType(); 3969 break; 3970 case Type::TypeOfExpr: 3971 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3972 break; 3973 case Type::Atomic: 3974 T = cast<AtomicType>(Ty)->getValueType(); 3975 break; 3976 } 3977 } while (!T.isNull() && T->isVariablyModifiedType()); 3978 } 3979 3980 /// \brief Build a sizeof or alignof expression given a type operand. 3981 ExprResult 3982 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3983 SourceLocation OpLoc, 3984 UnaryExprOrTypeTrait ExprKind, 3985 SourceRange R) { 3986 if (!TInfo) 3987 return ExprError(); 3988 3989 QualType T = TInfo->getType(); 3990 3991 if (!T->isDependentType() && 3992 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3993 return ExprError(); 3994 3995 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3996 if (auto *TT = T->getAs<TypedefType>()) { 3997 for (auto I = FunctionScopes.rbegin(), 3998 E = std::prev(FunctionScopes.rend()); 3999 I != E; ++I) { 4000 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4001 if (CSI == nullptr) 4002 break; 4003 DeclContext *DC = nullptr; 4004 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4005 DC = LSI->CallOperator; 4006 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4007 DC = CRSI->TheCapturedDecl; 4008 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4009 DC = BSI->TheDecl; 4010 if (DC) { 4011 if (DC->containsDecl(TT->getDecl())) 4012 break; 4013 captureVariablyModifiedType(Context, T, CSI); 4014 } 4015 } 4016 } 4017 } 4018 4019 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4020 return new (Context) UnaryExprOrTypeTraitExpr( 4021 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4022 } 4023 4024 /// \brief Build a sizeof or alignof expression given an expression 4025 /// operand. 4026 ExprResult 4027 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4028 UnaryExprOrTypeTrait ExprKind) { 4029 ExprResult PE = CheckPlaceholderExpr(E); 4030 if (PE.isInvalid()) 4031 return ExprError(); 4032 4033 E = PE.get(); 4034 4035 // Verify that the operand is valid. 4036 bool isInvalid = false; 4037 if (E->isTypeDependent()) { 4038 // Delay type-checking for type-dependent expressions. 4039 } else if (ExprKind == UETT_AlignOf) { 4040 isInvalid = CheckAlignOfExpr(*this, E); 4041 } else if (ExprKind == UETT_VecStep) { 4042 isInvalid = CheckVecStepExpr(E); 4043 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4044 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4045 isInvalid = true; 4046 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4047 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4048 isInvalid = true; 4049 } else { 4050 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4051 } 4052 4053 if (isInvalid) 4054 return ExprError(); 4055 4056 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4057 PE = TransformToPotentiallyEvaluated(E); 4058 if (PE.isInvalid()) return ExprError(); 4059 E = PE.get(); 4060 } 4061 4062 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4063 return new (Context) UnaryExprOrTypeTraitExpr( 4064 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4065 } 4066 4067 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4068 /// expr and the same for @c alignof and @c __alignof 4069 /// Note that the ArgRange is invalid if isType is false. 4070 ExprResult 4071 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4072 UnaryExprOrTypeTrait ExprKind, bool IsType, 4073 void *TyOrEx, SourceRange ArgRange) { 4074 // If error parsing type, ignore. 4075 if (!TyOrEx) return ExprError(); 4076 4077 if (IsType) { 4078 TypeSourceInfo *TInfo; 4079 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4080 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4081 } 4082 4083 Expr *ArgEx = (Expr *)TyOrEx; 4084 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4085 return Result; 4086 } 4087 4088 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4089 bool IsReal) { 4090 if (V.get()->isTypeDependent()) 4091 return S.Context.DependentTy; 4092 4093 // _Real and _Imag are only l-values for normal l-values. 4094 if (V.get()->getObjectKind() != OK_Ordinary) { 4095 V = S.DefaultLvalueConversion(V.get()); 4096 if (V.isInvalid()) 4097 return QualType(); 4098 } 4099 4100 // These operators return the element type of a complex type. 4101 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4102 return CT->getElementType(); 4103 4104 // Otherwise they pass through real integer and floating point types here. 4105 if (V.get()->getType()->isArithmeticType()) 4106 return V.get()->getType(); 4107 4108 // Test for placeholders. 4109 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4110 if (PR.isInvalid()) return QualType(); 4111 if (PR.get() != V.get()) { 4112 V = PR; 4113 return CheckRealImagOperand(S, V, Loc, IsReal); 4114 } 4115 4116 // Reject anything else. 4117 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4118 << (IsReal ? "__real" : "__imag"); 4119 return QualType(); 4120 } 4121 4122 4123 4124 ExprResult 4125 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4126 tok::TokenKind Kind, Expr *Input) { 4127 UnaryOperatorKind Opc; 4128 switch (Kind) { 4129 default: llvm_unreachable("Unknown unary op!"); 4130 case tok::plusplus: Opc = UO_PostInc; break; 4131 case tok::minusminus: Opc = UO_PostDec; break; 4132 } 4133 4134 // Since this might is a postfix expression, get rid of ParenListExprs. 4135 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4136 if (Result.isInvalid()) return ExprError(); 4137 Input = Result.get(); 4138 4139 return BuildUnaryOp(S, OpLoc, Opc, Input); 4140 } 4141 4142 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4143 /// 4144 /// \return true on error 4145 static bool checkArithmeticOnObjCPointer(Sema &S, 4146 SourceLocation opLoc, 4147 Expr *op) { 4148 assert(op->getType()->isObjCObjectPointerType()); 4149 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4150 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4151 return false; 4152 4153 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4154 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4155 << op->getSourceRange(); 4156 return true; 4157 } 4158 4159 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4160 auto *BaseNoParens = Base->IgnoreParens(); 4161 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4162 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4163 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4164 } 4165 4166 ExprResult 4167 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4168 Expr *idx, SourceLocation rbLoc) { 4169 if (base && !base->getType().isNull() && 4170 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4171 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4172 /*Length=*/nullptr, rbLoc); 4173 4174 // Since this might be a postfix expression, get rid of ParenListExprs. 4175 if (isa<ParenListExpr>(base)) { 4176 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4177 if (result.isInvalid()) return ExprError(); 4178 base = result.get(); 4179 } 4180 4181 // Handle any non-overload placeholder types in the base and index 4182 // expressions. We can't handle overloads here because the other 4183 // operand might be an overloadable type, in which case the overload 4184 // resolution for the operator overload should get the first crack 4185 // at the overload. 4186 bool IsMSPropertySubscript = false; 4187 if (base->getType()->isNonOverloadPlaceholderType()) { 4188 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4189 if (!IsMSPropertySubscript) { 4190 ExprResult result = CheckPlaceholderExpr(base); 4191 if (result.isInvalid()) 4192 return ExprError(); 4193 base = result.get(); 4194 } 4195 } 4196 if (idx->getType()->isNonOverloadPlaceholderType()) { 4197 ExprResult result = CheckPlaceholderExpr(idx); 4198 if (result.isInvalid()) return ExprError(); 4199 idx = result.get(); 4200 } 4201 4202 // Build an unanalyzed expression if either operand is type-dependent. 4203 if (getLangOpts().CPlusPlus && 4204 (base->isTypeDependent() || idx->isTypeDependent())) { 4205 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4206 VK_LValue, OK_Ordinary, rbLoc); 4207 } 4208 4209 // MSDN, property (C++) 4210 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4211 // This attribute can also be used in the declaration of an empty array in a 4212 // class or structure definition. For example: 4213 // __declspec(property(get=GetX, put=PutX)) int x[]; 4214 // The above statement indicates that x[] can be used with one or more array 4215 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4216 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4217 if (IsMSPropertySubscript) { 4218 // Build MS property subscript expression if base is MS property reference 4219 // or MS property subscript. 4220 return new (Context) MSPropertySubscriptExpr( 4221 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4222 } 4223 4224 // Use C++ overloaded-operator rules if either operand has record 4225 // type. The spec says to do this if either type is *overloadable*, 4226 // but enum types can't declare subscript operators or conversion 4227 // operators, so there's nothing interesting for overload resolution 4228 // to do if there aren't any record types involved. 4229 // 4230 // ObjC pointers have their own subscripting logic that is not tied 4231 // to overload resolution and so should not take this path. 4232 if (getLangOpts().CPlusPlus && 4233 (base->getType()->isRecordType() || 4234 (!base->getType()->isObjCObjectPointerType() && 4235 idx->getType()->isRecordType()))) { 4236 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4237 } 4238 4239 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4240 } 4241 4242 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4243 Expr *LowerBound, 4244 SourceLocation ColonLoc, Expr *Length, 4245 SourceLocation RBLoc) { 4246 if (Base->getType()->isPlaceholderType() && 4247 !Base->getType()->isSpecificPlaceholderType( 4248 BuiltinType::OMPArraySection)) { 4249 ExprResult Result = CheckPlaceholderExpr(Base); 4250 if (Result.isInvalid()) 4251 return ExprError(); 4252 Base = Result.get(); 4253 } 4254 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4255 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4256 if (Result.isInvalid()) 4257 return ExprError(); 4258 Result = DefaultLvalueConversion(Result.get()); 4259 if (Result.isInvalid()) 4260 return ExprError(); 4261 LowerBound = Result.get(); 4262 } 4263 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4264 ExprResult Result = CheckPlaceholderExpr(Length); 4265 if (Result.isInvalid()) 4266 return ExprError(); 4267 Result = DefaultLvalueConversion(Result.get()); 4268 if (Result.isInvalid()) 4269 return ExprError(); 4270 Length = Result.get(); 4271 } 4272 4273 // Build an unanalyzed expression if either operand is type-dependent. 4274 if (Base->isTypeDependent() || 4275 (LowerBound && 4276 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4277 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4278 return new (Context) 4279 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4280 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4281 } 4282 4283 // Perform default conversions. 4284 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4285 QualType ResultTy; 4286 if (OriginalTy->isAnyPointerType()) { 4287 ResultTy = OriginalTy->getPointeeType(); 4288 } else if (OriginalTy->isArrayType()) { 4289 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4290 } else { 4291 return ExprError( 4292 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4293 << Base->getSourceRange()); 4294 } 4295 // C99 6.5.2.1p1 4296 if (LowerBound) { 4297 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4298 LowerBound); 4299 if (Res.isInvalid()) 4300 return ExprError(Diag(LowerBound->getExprLoc(), 4301 diag::err_omp_typecheck_section_not_integer) 4302 << 0 << LowerBound->getSourceRange()); 4303 LowerBound = Res.get(); 4304 4305 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4306 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4307 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4308 << 0 << LowerBound->getSourceRange(); 4309 } 4310 if (Length) { 4311 auto Res = 4312 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4313 if (Res.isInvalid()) 4314 return ExprError(Diag(Length->getExprLoc(), 4315 diag::err_omp_typecheck_section_not_integer) 4316 << 1 << Length->getSourceRange()); 4317 Length = Res.get(); 4318 4319 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4320 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4321 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4322 << 1 << Length->getSourceRange(); 4323 } 4324 4325 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4326 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4327 // type. Note that functions are not objects, and that (in C99 parlance) 4328 // incomplete types are not object types. 4329 if (ResultTy->isFunctionType()) { 4330 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4331 << ResultTy << Base->getSourceRange(); 4332 return ExprError(); 4333 } 4334 4335 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4336 diag::err_omp_section_incomplete_type, Base)) 4337 return ExprError(); 4338 4339 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4340 llvm::APSInt LowerBoundValue; 4341 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4342 // OpenMP 4.5, [2.4 Array Sections] 4343 // The array section must be a subset of the original array. 4344 if (LowerBoundValue.isNegative()) { 4345 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4346 << LowerBound->getSourceRange(); 4347 return ExprError(); 4348 } 4349 } 4350 } 4351 4352 if (Length) { 4353 llvm::APSInt LengthValue; 4354 if (Length->EvaluateAsInt(LengthValue, Context)) { 4355 // OpenMP 4.5, [2.4 Array Sections] 4356 // The length must evaluate to non-negative integers. 4357 if (LengthValue.isNegative()) { 4358 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4359 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4360 << Length->getSourceRange(); 4361 return ExprError(); 4362 } 4363 } 4364 } else if (ColonLoc.isValid() && 4365 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4366 !OriginalTy->isVariableArrayType()))) { 4367 // OpenMP 4.5, [2.4 Array Sections] 4368 // When the size of the array dimension is not known, the length must be 4369 // specified explicitly. 4370 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4371 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4372 return ExprError(); 4373 } 4374 4375 if (!Base->getType()->isSpecificPlaceholderType( 4376 BuiltinType::OMPArraySection)) { 4377 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4378 if (Result.isInvalid()) 4379 return ExprError(); 4380 Base = Result.get(); 4381 } 4382 return new (Context) 4383 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4384 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4385 } 4386 4387 ExprResult 4388 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4389 Expr *Idx, SourceLocation RLoc) { 4390 Expr *LHSExp = Base; 4391 Expr *RHSExp = Idx; 4392 4393 // Perform default conversions. 4394 if (!LHSExp->getType()->getAs<VectorType>()) { 4395 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4396 if (Result.isInvalid()) 4397 return ExprError(); 4398 LHSExp = Result.get(); 4399 } 4400 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4401 if (Result.isInvalid()) 4402 return ExprError(); 4403 RHSExp = Result.get(); 4404 4405 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4406 ExprValueKind VK = VK_LValue; 4407 ExprObjectKind OK = OK_Ordinary; 4408 4409 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4410 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4411 // in the subscript position. As a result, we need to derive the array base 4412 // and index from the expression types. 4413 Expr *BaseExpr, *IndexExpr; 4414 QualType ResultType; 4415 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4416 BaseExpr = LHSExp; 4417 IndexExpr = RHSExp; 4418 ResultType = Context.DependentTy; 4419 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4420 BaseExpr = LHSExp; 4421 IndexExpr = RHSExp; 4422 ResultType = PTy->getPointeeType(); 4423 } else if (const ObjCObjectPointerType *PTy = 4424 LHSTy->getAs<ObjCObjectPointerType>()) { 4425 BaseExpr = LHSExp; 4426 IndexExpr = RHSExp; 4427 4428 // Use custom logic if this should be the pseudo-object subscript 4429 // expression. 4430 if (!LangOpts.isSubscriptPointerArithmetic()) 4431 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4432 nullptr); 4433 4434 ResultType = PTy->getPointeeType(); 4435 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4436 // Handle the uncommon case of "123[Ptr]". 4437 BaseExpr = RHSExp; 4438 IndexExpr = LHSExp; 4439 ResultType = PTy->getPointeeType(); 4440 } else if (const ObjCObjectPointerType *PTy = 4441 RHSTy->getAs<ObjCObjectPointerType>()) { 4442 // Handle the uncommon case of "123[Ptr]". 4443 BaseExpr = RHSExp; 4444 IndexExpr = LHSExp; 4445 ResultType = PTy->getPointeeType(); 4446 if (!LangOpts.isSubscriptPointerArithmetic()) { 4447 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4448 << ResultType << BaseExpr->getSourceRange(); 4449 return ExprError(); 4450 } 4451 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4452 BaseExpr = LHSExp; // vectors: V[123] 4453 IndexExpr = RHSExp; 4454 VK = LHSExp->getValueKind(); 4455 if (VK != VK_RValue) 4456 OK = OK_VectorComponent; 4457 4458 // FIXME: need to deal with const... 4459 ResultType = VTy->getElementType(); 4460 } else if (LHSTy->isArrayType()) { 4461 // If we see an array that wasn't promoted by 4462 // DefaultFunctionArrayLvalueConversion, it must be an array that 4463 // wasn't promoted because of the C90 rule that doesn't 4464 // allow promoting non-lvalue arrays. Warn, then 4465 // force the promotion here. 4466 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4467 LHSExp->getSourceRange(); 4468 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4469 CK_ArrayToPointerDecay).get(); 4470 LHSTy = LHSExp->getType(); 4471 4472 BaseExpr = LHSExp; 4473 IndexExpr = RHSExp; 4474 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4475 } else if (RHSTy->isArrayType()) { 4476 // Same as previous, except for 123[f().a] case 4477 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4478 RHSExp->getSourceRange(); 4479 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4480 CK_ArrayToPointerDecay).get(); 4481 RHSTy = RHSExp->getType(); 4482 4483 BaseExpr = RHSExp; 4484 IndexExpr = LHSExp; 4485 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4486 } else { 4487 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4488 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4489 } 4490 // C99 6.5.2.1p1 4491 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4492 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4493 << IndexExpr->getSourceRange()); 4494 4495 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4496 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4497 && !IndexExpr->isTypeDependent()) 4498 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4499 4500 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4501 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4502 // type. Note that Functions are not objects, and that (in C99 parlance) 4503 // incomplete types are not object types. 4504 if (ResultType->isFunctionType()) { 4505 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4506 << ResultType << BaseExpr->getSourceRange(); 4507 return ExprError(); 4508 } 4509 4510 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4511 // GNU extension: subscripting on pointer to void 4512 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4513 << BaseExpr->getSourceRange(); 4514 4515 // C forbids expressions of unqualified void type from being l-values. 4516 // See IsCForbiddenLValueType. 4517 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4518 } else if (!ResultType->isDependentType() && 4519 RequireCompleteType(LLoc, ResultType, 4520 diag::err_subscript_incomplete_type, BaseExpr)) 4521 return ExprError(); 4522 4523 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4524 !ResultType.isCForbiddenLValueType()); 4525 4526 return new (Context) 4527 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4528 } 4529 4530 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4531 FunctionDecl *FD, 4532 ParmVarDecl *Param) { 4533 if (Param->hasUnparsedDefaultArg()) { 4534 Diag(CallLoc, 4535 diag::err_use_of_default_argument_to_function_declared_later) << 4536 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4537 Diag(UnparsedDefaultArgLocs[Param], 4538 diag::note_default_argument_declared_here); 4539 return ExprError(); 4540 } 4541 4542 if (Param->hasUninstantiatedDefaultArg()) { 4543 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4544 4545 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4546 Param); 4547 4548 // Instantiate the expression. 4549 MultiLevelTemplateArgumentList MutiLevelArgList 4550 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4551 4552 InstantiatingTemplate Inst(*this, CallLoc, Param, 4553 MutiLevelArgList.getInnermost()); 4554 if (Inst.isInvalid()) 4555 return ExprError(); 4556 if (Inst.isAlreadyInstantiating()) { 4557 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4558 Param->setInvalidDecl(); 4559 return ExprError(); 4560 } 4561 4562 ExprResult Result; 4563 { 4564 // C++ [dcl.fct.default]p5: 4565 // The names in the [default argument] expression are bound, and 4566 // the semantic constraints are checked, at the point where the 4567 // default argument expression appears. 4568 ContextRAII SavedContext(*this, FD); 4569 LocalInstantiationScope Local(*this); 4570 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4571 /*DirectInit*/false); 4572 } 4573 if (Result.isInvalid()) 4574 return ExprError(); 4575 4576 // Check the expression as an initializer for the parameter. 4577 InitializedEntity Entity 4578 = InitializedEntity::InitializeParameter(Context, Param); 4579 InitializationKind Kind 4580 = InitializationKind::CreateCopy(Param->getLocation(), 4581 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4582 Expr *ResultE = Result.getAs<Expr>(); 4583 4584 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4585 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4586 if (Result.isInvalid()) 4587 return ExprError(); 4588 4589 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4590 Param->getOuterLocStart()); 4591 if (Result.isInvalid()) 4592 return ExprError(); 4593 4594 // Remember the instantiated default argument. 4595 Param->setDefaultArg(Result.getAs<Expr>()); 4596 if (ASTMutationListener *L = getASTMutationListener()) { 4597 L->DefaultArgumentInstantiated(Param); 4598 } 4599 } 4600 4601 // If the default argument expression is not set yet, we are building it now. 4602 if (!Param->hasInit()) { 4603 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4604 Param->setInvalidDecl(); 4605 return ExprError(); 4606 } 4607 4608 // If the default expression creates temporaries, we need to 4609 // push them to the current stack of expression temporaries so they'll 4610 // be properly destroyed. 4611 // FIXME: We should really be rebuilding the default argument with new 4612 // bound temporaries; see the comment in PR5810. 4613 // We don't need to do that with block decls, though, because 4614 // blocks in default argument expression can never capture anything. 4615 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4616 // Set the "needs cleanups" bit regardless of whether there are 4617 // any explicit objects. 4618 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4619 4620 // Append all the objects to the cleanup list. Right now, this 4621 // should always be a no-op, because blocks in default argument 4622 // expressions should never be able to capture anything. 4623 assert(!Init->getNumObjects() && 4624 "default argument expression has capturing blocks?"); 4625 } 4626 4627 // We already type-checked the argument, so we know it works. 4628 // Just mark all of the declarations in this potentially-evaluated expression 4629 // as being "referenced". 4630 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4631 /*SkipLocalVariables=*/true); 4632 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4633 } 4634 4635 4636 Sema::VariadicCallType 4637 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4638 Expr *Fn) { 4639 if (Proto && Proto->isVariadic()) { 4640 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4641 return VariadicConstructor; 4642 else if (Fn && Fn->getType()->isBlockPointerType()) 4643 return VariadicBlock; 4644 else if (FDecl) { 4645 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4646 if (Method->isInstance()) 4647 return VariadicMethod; 4648 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4649 return VariadicMethod; 4650 return VariadicFunction; 4651 } 4652 return VariadicDoesNotApply; 4653 } 4654 4655 namespace { 4656 class FunctionCallCCC : public FunctionCallFilterCCC { 4657 public: 4658 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4659 unsigned NumArgs, MemberExpr *ME) 4660 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4661 FunctionName(FuncName) {} 4662 4663 bool ValidateCandidate(const TypoCorrection &candidate) override { 4664 if (!candidate.getCorrectionSpecifier() || 4665 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4666 return false; 4667 } 4668 4669 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4670 } 4671 4672 private: 4673 const IdentifierInfo *const FunctionName; 4674 }; 4675 } 4676 4677 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4678 FunctionDecl *FDecl, 4679 ArrayRef<Expr *> Args) { 4680 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4681 DeclarationName FuncName = FDecl->getDeclName(); 4682 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4683 4684 if (TypoCorrection Corrected = S.CorrectTypo( 4685 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4686 S.getScopeForContext(S.CurContext), nullptr, 4687 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4688 Args.size(), ME), 4689 Sema::CTK_ErrorRecovery)) { 4690 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4691 if (Corrected.isOverloaded()) { 4692 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4693 OverloadCandidateSet::iterator Best; 4694 for (NamedDecl *CD : Corrected) { 4695 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4696 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4697 OCS); 4698 } 4699 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4700 case OR_Success: 4701 ND = Best->FoundDecl; 4702 Corrected.setCorrectionDecl(ND); 4703 break; 4704 default: 4705 break; 4706 } 4707 } 4708 ND = ND->getUnderlyingDecl(); 4709 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4710 return Corrected; 4711 } 4712 } 4713 return TypoCorrection(); 4714 } 4715 4716 /// ConvertArgumentsForCall - Converts the arguments specified in 4717 /// Args/NumArgs to the parameter types of the function FDecl with 4718 /// function prototype Proto. Call is the call expression itself, and 4719 /// Fn is the function expression. For a C++ member function, this 4720 /// routine does not attempt to convert the object argument. Returns 4721 /// true if the call is ill-formed. 4722 bool 4723 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4724 FunctionDecl *FDecl, 4725 const FunctionProtoType *Proto, 4726 ArrayRef<Expr *> Args, 4727 SourceLocation RParenLoc, 4728 bool IsExecConfig) { 4729 // Bail out early if calling a builtin with custom typechecking. 4730 if (FDecl) 4731 if (unsigned ID = FDecl->getBuiltinID()) 4732 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4733 return false; 4734 4735 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4736 // assignment, to the types of the corresponding parameter, ... 4737 unsigned NumParams = Proto->getNumParams(); 4738 bool Invalid = false; 4739 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4740 unsigned FnKind = Fn->getType()->isBlockPointerType() 4741 ? 1 /* block */ 4742 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4743 : 0 /* function */); 4744 4745 // If too few arguments are available (and we don't have default 4746 // arguments for the remaining parameters), don't make the call. 4747 if (Args.size() < NumParams) { 4748 if (Args.size() < MinArgs) { 4749 TypoCorrection TC; 4750 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4751 unsigned diag_id = 4752 MinArgs == NumParams && !Proto->isVariadic() 4753 ? diag::err_typecheck_call_too_few_args_suggest 4754 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4755 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4756 << static_cast<unsigned>(Args.size()) 4757 << TC.getCorrectionRange()); 4758 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4759 Diag(RParenLoc, 4760 MinArgs == NumParams && !Proto->isVariadic() 4761 ? diag::err_typecheck_call_too_few_args_one 4762 : diag::err_typecheck_call_too_few_args_at_least_one) 4763 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4764 else 4765 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4766 ? diag::err_typecheck_call_too_few_args 4767 : diag::err_typecheck_call_too_few_args_at_least) 4768 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4769 << Fn->getSourceRange(); 4770 4771 // Emit the location of the prototype. 4772 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4773 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4774 << FDecl; 4775 4776 return true; 4777 } 4778 Call->setNumArgs(Context, NumParams); 4779 } 4780 4781 // If too many are passed and not variadic, error on the extras and drop 4782 // them. 4783 if (Args.size() > NumParams) { 4784 if (!Proto->isVariadic()) { 4785 TypoCorrection TC; 4786 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4787 unsigned diag_id = 4788 MinArgs == NumParams && !Proto->isVariadic() 4789 ? diag::err_typecheck_call_too_many_args_suggest 4790 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4791 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4792 << static_cast<unsigned>(Args.size()) 4793 << TC.getCorrectionRange()); 4794 } else if (NumParams == 1 && FDecl && 4795 FDecl->getParamDecl(0)->getDeclName()) 4796 Diag(Args[NumParams]->getLocStart(), 4797 MinArgs == NumParams 4798 ? diag::err_typecheck_call_too_many_args_one 4799 : diag::err_typecheck_call_too_many_args_at_most_one) 4800 << FnKind << FDecl->getParamDecl(0) 4801 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4802 << SourceRange(Args[NumParams]->getLocStart(), 4803 Args.back()->getLocEnd()); 4804 else 4805 Diag(Args[NumParams]->getLocStart(), 4806 MinArgs == NumParams 4807 ? diag::err_typecheck_call_too_many_args 4808 : diag::err_typecheck_call_too_many_args_at_most) 4809 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4810 << Fn->getSourceRange() 4811 << SourceRange(Args[NumParams]->getLocStart(), 4812 Args.back()->getLocEnd()); 4813 4814 // Emit the location of the prototype. 4815 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4816 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4817 << FDecl; 4818 4819 // This deletes the extra arguments. 4820 Call->setNumArgs(Context, NumParams); 4821 return true; 4822 } 4823 } 4824 SmallVector<Expr *, 8> AllArgs; 4825 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4826 4827 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4828 Proto, 0, Args, AllArgs, CallType); 4829 if (Invalid) 4830 return true; 4831 unsigned TotalNumArgs = AllArgs.size(); 4832 for (unsigned i = 0; i < TotalNumArgs; ++i) 4833 Call->setArg(i, AllArgs[i]); 4834 4835 return false; 4836 } 4837 4838 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4839 const FunctionProtoType *Proto, 4840 unsigned FirstParam, ArrayRef<Expr *> Args, 4841 SmallVectorImpl<Expr *> &AllArgs, 4842 VariadicCallType CallType, bool AllowExplicit, 4843 bool IsListInitialization) { 4844 unsigned NumParams = Proto->getNumParams(); 4845 bool Invalid = false; 4846 size_t ArgIx = 0; 4847 // Continue to check argument types (even if we have too few/many args). 4848 for (unsigned i = FirstParam; i < NumParams; i++) { 4849 QualType ProtoArgType = Proto->getParamType(i); 4850 4851 Expr *Arg; 4852 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4853 if (ArgIx < Args.size()) { 4854 Arg = Args[ArgIx++]; 4855 4856 if (RequireCompleteType(Arg->getLocStart(), 4857 ProtoArgType, 4858 diag::err_call_incomplete_argument, Arg)) 4859 return true; 4860 4861 // Strip the unbridged-cast placeholder expression off, if applicable. 4862 bool CFAudited = false; 4863 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4864 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4865 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4866 Arg = stripARCUnbridgedCast(Arg); 4867 else if (getLangOpts().ObjCAutoRefCount && 4868 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4869 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4870 CFAudited = true; 4871 4872 InitializedEntity Entity = 4873 Param ? InitializedEntity::InitializeParameter(Context, Param, 4874 ProtoArgType) 4875 : InitializedEntity::InitializeParameter( 4876 Context, ProtoArgType, Proto->isParamConsumed(i)); 4877 4878 // Remember that parameter belongs to a CF audited API. 4879 if (CFAudited) 4880 Entity.setParameterCFAudited(); 4881 4882 ExprResult ArgE = PerformCopyInitialization( 4883 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4884 if (ArgE.isInvalid()) 4885 return true; 4886 4887 Arg = ArgE.getAs<Expr>(); 4888 } else { 4889 assert(Param && "can't use default arguments without a known callee"); 4890 4891 ExprResult ArgExpr = 4892 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4893 if (ArgExpr.isInvalid()) 4894 return true; 4895 4896 Arg = ArgExpr.getAs<Expr>(); 4897 } 4898 4899 // Check for array bounds violations for each argument to the call. This 4900 // check only triggers warnings when the argument isn't a more complex Expr 4901 // with its own checking, such as a BinaryOperator. 4902 CheckArrayAccess(Arg); 4903 4904 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4905 CheckStaticArrayArgument(CallLoc, Param, Arg); 4906 4907 AllArgs.push_back(Arg); 4908 } 4909 4910 // If this is a variadic call, handle args passed through "...". 4911 if (CallType != VariadicDoesNotApply) { 4912 // Assume that extern "C" functions with variadic arguments that 4913 // return __unknown_anytype aren't *really* variadic. 4914 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4915 FDecl->isExternC()) { 4916 for (Expr *A : Args.slice(ArgIx)) { 4917 QualType paramType; // ignored 4918 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4919 Invalid |= arg.isInvalid(); 4920 AllArgs.push_back(arg.get()); 4921 } 4922 4923 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4924 } else { 4925 for (Expr *A : Args.slice(ArgIx)) { 4926 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4927 Invalid |= Arg.isInvalid(); 4928 AllArgs.push_back(Arg.get()); 4929 } 4930 } 4931 4932 // Check for array bounds violations. 4933 for (Expr *A : Args.slice(ArgIx)) 4934 CheckArrayAccess(A); 4935 } 4936 return Invalid; 4937 } 4938 4939 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4940 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4941 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4942 TL = DTL.getOriginalLoc(); 4943 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4944 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4945 << ATL.getLocalSourceRange(); 4946 } 4947 4948 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4949 /// array parameter, check that it is non-null, and that if it is formed by 4950 /// array-to-pointer decay, the underlying array is sufficiently large. 4951 /// 4952 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4953 /// array type derivation, then for each call to the function, the value of the 4954 /// corresponding actual argument shall provide access to the first element of 4955 /// an array with at least as many elements as specified by the size expression. 4956 void 4957 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4958 ParmVarDecl *Param, 4959 const Expr *ArgExpr) { 4960 // Static array parameters are not supported in C++. 4961 if (!Param || getLangOpts().CPlusPlus) 4962 return; 4963 4964 QualType OrigTy = Param->getOriginalType(); 4965 4966 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4967 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4968 return; 4969 4970 if (ArgExpr->isNullPointerConstant(Context, 4971 Expr::NPC_NeverValueDependent)) { 4972 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4973 DiagnoseCalleeStaticArrayParam(*this, Param); 4974 return; 4975 } 4976 4977 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4978 if (!CAT) 4979 return; 4980 4981 const ConstantArrayType *ArgCAT = 4982 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4983 if (!ArgCAT) 4984 return; 4985 4986 if (ArgCAT->getSize().ult(CAT->getSize())) { 4987 Diag(CallLoc, diag::warn_static_array_too_small) 4988 << ArgExpr->getSourceRange() 4989 << (unsigned) ArgCAT->getSize().getZExtValue() 4990 << (unsigned) CAT->getSize().getZExtValue(); 4991 DiagnoseCalleeStaticArrayParam(*this, Param); 4992 } 4993 } 4994 4995 /// Given a function expression of unknown-any type, try to rebuild it 4996 /// to have a function type. 4997 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4998 4999 /// Is the given type a placeholder that we need to lower out 5000 /// immediately during argument processing? 5001 static bool isPlaceholderToRemoveAsArg(QualType type) { 5002 // Placeholders are never sugared. 5003 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5004 if (!placeholder) return false; 5005 5006 switch (placeholder->getKind()) { 5007 // Ignore all the non-placeholder types. 5008 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5009 case BuiltinType::Id: 5010 #include "clang/Basic/OpenCLImageTypes.def" 5011 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5012 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5013 #include "clang/AST/BuiltinTypes.def" 5014 return false; 5015 5016 // We cannot lower out overload sets; they might validly be resolved 5017 // by the call machinery. 5018 case BuiltinType::Overload: 5019 return false; 5020 5021 // Unbridged casts in ARC can be handled in some call positions and 5022 // should be left in place. 5023 case BuiltinType::ARCUnbridgedCast: 5024 return false; 5025 5026 // Pseudo-objects should be converted as soon as possible. 5027 case BuiltinType::PseudoObject: 5028 return true; 5029 5030 // The debugger mode could theoretically but currently does not try 5031 // to resolve unknown-typed arguments based on known parameter types. 5032 case BuiltinType::UnknownAny: 5033 return true; 5034 5035 // These are always invalid as call arguments and should be reported. 5036 case BuiltinType::BoundMember: 5037 case BuiltinType::BuiltinFn: 5038 case BuiltinType::OMPArraySection: 5039 return true; 5040 5041 } 5042 llvm_unreachable("bad builtin type kind"); 5043 } 5044 5045 /// Check an argument list for placeholders that we won't try to 5046 /// handle later. 5047 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5048 // Apply this processing to all the arguments at once instead of 5049 // dying at the first failure. 5050 bool hasInvalid = false; 5051 for (size_t i = 0, e = args.size(); i != e; i++) { 5052 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5053 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5054 if (result.isInvalid()) hasInvalid = true; 5055 else args[i] = result.get(); 5056 } else if (hasInvalid) { 5057 (void)S.CorrectDelayedTyposInExpr(args[i]); 5058 } 5059 } 5060 return hasInvalid; 5061 } 5062 5063 /// If a builtin function has a pointer argument with no explicit address 5064 /// space, then it should be able to accept a pointer to any address 5065 /// space as input. In order to do this, we need to replace the 5066 /// standard builtin declaration with one that uses the same address space 5067 /// as the call. 5068 /// 5069 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5070 /// it does not contain any pointer arguments without 5071 /// an address space qualifer. Otherwise the rewritten 5072 /// FunctionDecl is returned. 5073 /// TODO: Handle pointer return types. 5074 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5075 const FunctionDecl *FDecl, 5076 MultiExprArg ArgExprs) { 5077 5078 QualType DeclType = FDecl->getType(); 5079 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5080 5081 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5082 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5083 return nullptr; 5084 5085 bool NeedsNewDecl = false; 5086 unsigned i = 0; 5087 SmallVector<QualType, 8> OverloadParams; 5088 5089 for (QualType ParamType : FT->param_types()) { 5090 5091 // Convert array arguments to pointer to simplify type lookup. 5092 ExprResult ArgRes = 5093 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5094 if (ArgRes.isInvalid()) 5095 return nullptr; 5096 Expr *Arg = ArgRes.get(); 5097 QualType ArgType = Arg->getType(); 5098 if (!ParamType->isPointerType() || 5099 ParamType.getQualifiers().hasAddressSpace() || 5100 !ArgType->isPointerType() || 5101 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5102 OverloadParams.push_back(ParamType); 5103 continue; 5104 } 5105 5106 NeedsNewDecl = true; 5107 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5108 5109 QualType PointeeType = ParamType->getPointeeType(); 5110 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5111 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5112 } 5113 5114 if (!NeedsNewDecl) 5115 return nullptr; 5116 5117 FunctionProtoType::ExtProtoInfo EPI; 5118 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5119 OverloadParams, EPI); 5120 DeclContext *Parent = Context.getTranslationUnitDecl(); 5121 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5122 FDecl->getLocation(), 5123 FDecl->getLocation(), 5124 FDecl->getIdentifier(), 5125 OverloadTy, 5126 /*TInfo=*/nullptr, 5127 SC_Extern, false, 5128 /*hasPrototype=*/true); 5129 SmallVector<ParmVarDecl*, 16> Params; 5130 FT = cast<FunctionProtoType>(OverloadTy); 5131 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5132 QualType ParamType = FT->getParamType(i); 5133 ParmVarDecl *Parm = 5134 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5135 SourceLocation(), nullptr, ParamType, 5136 /*TInfo=*/nullptr, SC_None, nullptr); 5137 Parm->setScopeInfo(0, i); 5138 Params.push_back(Parm); 5139 } 5140 OverloadDecl->setParams(Params); 5141 return OverloadDecl; 5142 } 5143 5144 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5145 std::size_t NumArgs) { 5146 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5147 /*PartialOverloading=*/false)) 5148 return Callee->isVariadic(); 5149 return Callee->getMinRequiredArguments() <= NumArgs; 5150 } 5151 5152 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5153 /// This provides the location of the left/right parens and a list of comma 5154 /// locations. 5155 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5156 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5157 Expr *ExecConfig, bool IsExecConfig) { 5158 // Since this might be a postfix expression, get rid of ParenListExprs. 5159 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5160 if (Result.isInvalid()) return ExprError(); 5161 Fn = Result.get(); 5162 5163 if (checkArgsForPlaceholders(*this, ArgExprs)) 5164 return ExprError(); 5165 5166 if (getLangOpts().CPlusPlus) { 5167 // If this is a pseudo-destructor expression, build the call immediately. 5168 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5169 if (!ArgExprs.empty()) { 5170 // Pseudo-destructor calls should not have any arguments. 5171 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5172 << FixItHint::CreateRemoval( 5173 SourceRange(ArgExprs.front()->getLocStart(), 5174 ArgExprs.back()->getLocEnd())); 5175 } 5176 5177 return new (Context) 5178 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5179 } 5180 if (Fn->getType() == Context.PseudoObjectTy) { 5181 ExprResult result = CheckPlaceholderExpr(Fn); 5182 if (result.isInvalid()) return ExprError(); 5183 Fn = result.get(); 5184 } 5185 5186 // Determine whether this is a dependent call inside a C++ template, 5187 // in which case we won't do any semantic analysis now. 5188 bool Dependent = false; 5189 if (Fn->isTypeDependent()) 5190 Dependent = true; 5191 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5192 Dependent = true; 5193 5194 if (Dependent) { 5195 if (ExecConfig) { 5196 return new (Context) CUDAKernelCallExpr( 5197 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5198 Context.DependentTy, VK_RValue, RParenLoc); 5199 } else { 5200 return new (Context) CallExpr( 5201 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5202 } 5203 } 5204 5205 // Determine whether this is a call to an object (C++ [over.call.object]). 5206 if (Fn->getType()->isRecordType()) 5207 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5208 RParenLoc); 5209 5210 if (Fn->getType() == Context.UnknownAnyTy) { 5211 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5212 if (result.isInvalid()) return ExprError(); 5213 Fn = result.get(); 5214 } 5215 5216 if (Fn->getType() == Context.BoundMemberTy) { 5217 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5218 RParenLoc); 5219 } 5220 } 5221 5222 // Check for overloaded calls. This can happen even in C due to extensions. 5223 if (Fn->getType() == Context.OverloadTy) { 5224 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5225 5226 // We aren't supposed to apply this logic for if there'Scope an '&' 5227 // involved. 5228 if (!find.HasFormOfMemberPointer) { 5229 OverloadExpr *ovl = find.Expression; 5230 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5231 return BuildOverloadedCallExpr( 5232 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5233 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5234 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5235 RParenLoc); 5236 } 5237 } 5238 5239 // If we're directly calling a function, get the appropriate declaration. 5240 if (Fn->getType() == Context.UnknownAnyTy) { 5241 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5242 if (result.isInvalid()) return ExprError(); 5243 Fn = result.get(); 5244 } 5245 5246 Expr *NakedFn = Fn->IgnoreParens(); 5247 5248 bool CallingNDeclIndirectly = false; 5249 NamedDecl *NDecl = nullptr; 5250 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5251 if (UnOp->getOpcode() == UO_AddrOf) { 5252 CallingNDeclIndirectly = true; 5253 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5254 } 5255 } 5256 5257 if (isa<DeclRefExpr>(NakedFn)) { 5258 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5259 5260 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5261 if (FDecl && FDecl->getBuiltinID()) { 5262 // Rewrite the function decl for this builtin by replacing parameters 5263 // with no explicit address space with the address space of the arguments 5264 // in ArgExprs. 5265 if ((FDecl = 5266 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5267 NDecl = FDecl; 5268 Fn = DeclRefExpr::Create( 5269 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5270 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5271 } 5272 } 5273 } else if (isa<MemberExpr>(NakedFn)) 5274 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5275 5276 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5277 if (CallingNDeclIndirectly && 5278 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5279 Fn->getLocStart())) 5280 return ExprError(); 5281 5282 // CheckEnableIf assumes that the we're passing in a sane number of args for 5283 // FD, but that doesn't always hold true here. This is because, in some 5284 // cases, we'll emit a diag about an ill-formed function call, but then 5285 // we'll continue on as if the function call wasn't ill-formed. So, if the 5286 // number of args looks incorrect, don't do enable_if checks; we should've 5287 // already emitted an error about the bad call. 5288 if (FD->hasAttr<EnableIfAttr>() && 5289 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5290 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5291 Diag(Fn->getLocStart(), 5292 isa<CXXMethodDecl>(FD) 5293 ? diag::err_ovl_no_viable_member_function_in_call 5294 : diag::err_ovl_no_viable_function_in_call) 5295 << FD << FD->getSourceRange(); 5296 Diag(FD->getLocation(), 5297 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5298 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5299 } 5300 } 5301 } 5302 5303 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5304 ExecConfig, IsExecConfig); 5305 } 5306 5307 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5308 /// 5309 /// __builtin_astype( value, dst type ) 5310 /// 5311 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5312 SourceLocation BuiltinLoc, 5313 SourceLocation RParenLoc) { 5314 ExprValueKind VK = VK_RValue; 5315 ExprObjectKind OK = OK_Ordinary; 5316 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5317 QualType SrcTy = E->getType(); 5318 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5319 return ExprError(Diag(BuiltinLoc, 5320 diag::err_invalid_astype_of_different_size) 5321 << DstTy 5322 << SrcTy 5323 << E->getSourceRange()); 5324 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5325 } 5326 5327 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5328 /// provided arguments. 5329 /// 5330 /// __builtin_convertvector( value, dst type ) 5331 /// 5332 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5333 SourceLocation BuiltinLoc, 5334 SourceLocation RParenLoc) { 5335 TypeSourceInfo *TInfo; 5336 GetTypeFromParser(ParsedDestTy, &TInfo); 5337 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5338 } 5339 5340 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5341 /// i.e. an expression not of \p OverloadTy. The expression should 5342 /// unary-convert to an expression of function-pointer or 5343 /// block-pointer type. 5344 /// 5345 /// \param NDecl the declaration being called, if available 5346 ExprResult 5347 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5348 SourceLocation LParenLoc, 5349 ArrayRef<Expr *> Args, 5350 SourceLocation RParenLoc, 5351 Expr *Config, bool IsExecConfig) { 5352 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5353 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5354 5355 // Functions with 'interrupt' attribute cannot be called directly. 5356 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5357 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5358 return ExprError(); 5359 } 5360 5361 // Promote the function operand. 5362 // We special-case function promotion here because we only allow promoting 5363 // builtin functions to function pointers in the callee of a call. 5364 ExprResult Result; 5365 if (BuiltinID && 5366 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5367 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5368 CK_BuiltinFnToFnPtr).get(); 5369 } else { 5370 Result = CallExprUnaryConversions(Fn); 5371 } 5372 if (Result.isInvalid()) 5373 return ExprError(); 5374 Fn = Result.get(); 5375 5376 // Make the call expr early, before semantic checks. This guarantees cleanup 5377 // of arguments and function on error. 5378 CallExpr *TheCall; 5379 if (Config) 5380 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5381 cast<CallExpr>(Config), Args, 5382 Context.BoolTy, VK_RValue, 5383 RParenLoc); 5384 else 5385 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5386 VK_RValue, RParenLoc); 5387 5388 if (!getLangOpts().CPlusPlus) { 5389 // C cannot always handle TypoExpr nodes in builtin calls and direct 5390 // function calls as their argument checking don't necessarily handle 5391 // dependent types properly, so make sure any TypoExprs have been 5392 // dealt with. 5393 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5394 if (!Result.isUsable()) return ExprError(); 5395 TheCall = dyn_cast<CallExpr>(Result.get()); 5396 if (!TheCall) return Result; 5397 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5398 } 5399 5400 // Bail out early if calling a builtin with custom typechecking. 5401 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5402 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5403 5404 retry: 5405 const FunctionType *FuncT; 5406 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5407 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5408 // have type pointer to function". 5409 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5410 if (!FuncT) 5411 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5412 << Fn->getType() << Fn->getSourceRange()); 5413 } else if (const BlockPointerType *BPT = 5414 Fn->getType()->getAs<BlockPointerType>()) { 5415 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5416 } else { 5417 // Handle calls to expressions of unknown-any type. 5418 if (Fn->getType() == Context.UnknownAnyTy) { 5419 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5420 if (rewrite.isInvalid()) return ExprError(); 5421 Fn = rewrite.get(); 5422 TheCall->setCallee(Fn); 5423 goto retry; 5424 } 5425 5426 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5427 << Fn->getType() << Fn->getSourceRange()); 5428 } 5429 5430 if (getLangOpts().CUDA) { 5431 if (Config) { 5432 // CUDA: Kernel calls must be to global functions 5433 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5434 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5435 << FDecl->getName() << Fn->getSourceRange()); 5436 5437 // CUDA: Kernel function must have 'void' return type 5438 if (!FuncT->getReturnType()->isVoidType()) 5439 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5440 << Fn->getType() << Fn->getSourceRange()); 5441 } else { 5442 // CUDA: Calls to global functions must be configured 5443 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5444 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5445 << FDecl->getName() << Fn->getSourceRange()); 5446 } 5447 } 5448 5449 // Check for a valid return type 5450 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5451 FDecl)) 5452 return ExprError(); 5453 5454 // We know the result type of the call, set it. 5455 TheCall->setType(FuncT->getCallResultType(Context)); 5456 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5457 5458 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5459 if (Proto) { 5460 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5461 IsExecConfig)) 5462 return ExprError(); 5463 } else { 5464 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5465 5466 if (FDecl) { 5467 // Check if we have too few/too many template arguments, based 5468 // on our knowledge of the function definition. 5469 const FunctionDecl *Def = nullptr; 5470 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5471 Proto = Def->getType()->getAs<FunctionProtoType>(); 5472 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5473 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5474 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5475 } 5476 5477 // If the function we're calling isn't a function prototype, but we have 5478 // a function prototype from a prior declaratiom, use that prototype. 5479 if (!FDecl->hasPrototype()) 5480 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5481 } 5482 5483 // Promote the arguments (C99 6.5.2.2p6). 5484 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5485 Expr *Arg = Args[i]; 5486 5487 if (Proto && i < Proto->getNumParams()) { 5488 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5489 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5490 ExprResult ArgE = 5491 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5492 if (ArgE.isInvalid()) 5493 return true; 5494 5495 Arg = ArgE.getAs<Expr>(); 5496 5497 } else { 5498 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5499 5500 if (ArgE.isInvalid()) 5501 return true; 5502 5503 Arg = ArgE.getAs<Expr>(); 5504 } 5505 5506 if (RequireCompleteType(Arg->getLocStart(), 5507 Arg->getType(), 5508 diag::err_call_incomplete_argument, Arg)) 5509 return ExprError(); 5510 5511 TheCall->setArg(i, Arg); 5512 } 5513 } 5514 5515 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5516 if (!Method->isStatic()) 5517 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5518 << Fn->getSourceRange()); 5519 5520 // Check for sentinels 5521 if (NDecl) 5522 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5523 5524 // Do special checking on direct calls to functions. 5525 if (FDecl) { 5526 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5527 return ExprError(); 5528 5529 if (BuiltinID) 5530 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5531 } else if (NDecl) { 5532 if (CheckPointerCall(NDecl, TheCall, Proto)) 5533 return ExprError(); 5534 } else { 5535 if (CheckOtherCall(TheCall, Proto)) 5536 return ExprError(); 5537 } 5538 5539 return MaybeBindToTemporary(TheCall); 5540 } 5541 5542 ExprResult 5543 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5544 SourceLocation RParenLoc, Expr *InitExpr) { 5545 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5546 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5547 5548 TypeSourceInfo *TInfo; 5549 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5550 if (!TInfo) 5551 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5552 5553 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5554 } 5555 5556 ExprResult 5557 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5558 SourceLocation RParenLoc, Expr *LiteralExpr) { 5559 QualType literalType = TInfo->getType(); 5560 5561 if (literalType->isArrayType()) { 5562 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5563 diag::err_illegal_decl_array_incomplete_type, 5564 SourceRange(LParenLoc, 5565 LiteralExpr->getSourceRange().getEnd()))) 5566 return ExprError(); 5567 if (literalType->isVariableArrayType()) 5568 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5569 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5570 } else if (!literalType->isDependentType() && 5571 RequireCompleteType(LParenLoc, literalType, 5572 diag::err_typecheck_decl_incomplete_type, 5573 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5574 return ExprError(); 5575 5576 InitializedEntity Entity 5577 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5578 InitializationKind Kind 5579 = InitializationKind::CreateCStyleCast(LParenLoc, 5580 SourceRange(LParenLoc, RParenLoc), 5581 /*InitList=*/true); 5582 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5583 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5584 &literalType); 5585 if (Result.isInvalid()) 5586 return ExprError(); 5587 LiteralExpr = Result.get(); 5588 5589 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5590 if (isFileScope && 5591 !LiteralExpr->isTypeDependent() && 5592 !LiteralExpr->isValueDependent() && 5593 !literalType->isDependentType()) { // 6.5.2.5p3 5594 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5595 return ExprError(); 5596 } 5597 5598 // In C, compound literals are l-values for some reason. 5599 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5600 5601 return MaybeBindToTemporary( 5602 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5603 VK, LiteralExpr, isFileScope)); 5604 } 5605 5606 ExprResult 5607 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5608 SourceLocation RBraceLoc) { 5609 // Immediately handle non-overload placeholders. Overloads can be 5610 // resolved contextually, but everything else here can't. 5611 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5612 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5613 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5614 5615 // Ignore failures; dropping the entire initializer list because 5616 // of one failure would be terrible for indexing/etc. 5617 if (result.isInvalid()) continue; 5618 5619 InitArgList[I] = result.get(); 5620 } 5621 } 5622 5623 // Semantic analysis for initializers is done by ActOnDeclarator() and 5624 // CheckInitializer() - it requires knowledge of the object being intialized. 5625 5626 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5627 RBraceLoc); 5628 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5629 return E; 5630 } 5631 5632 /// Do an explicit extend of the given block pointer if we're in ARC. 5633 void Sema::maybeExtendBlockObject(ExprResult &E) { 5634 assert(E.get()->getType()->isBlockPointerType()); 5635 assert(E.get()->isRValue()); 5636 5637 // Only do this in an r-value context. 5638 if (!getLangOpts().ObjCAutoRefCount) return; 5639 5640 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5641 CK_ARCExtendBlockObject, E.get(), 5642 /*base path*/ nullptr, VK_RValue); 5643 Cleanup.setExprNeedsCleanups(true); 5644 } 5645 5646 /// Prepare a conversion of the given expression to an ObjC object 5647 /// pointer type. 5648 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5649 QualType type = E.get()->getType(); 5650 if (type->isObjCObjectPointerType()) { 5651 return CK_BitCast; 5652 } else if (type->isBlockPointerType()) { 5653 maybeExtendBlockObject(E); 5654 return CK_BlockPointerToObjCPointerCast; 5655 } else { 5656 assert(type->isPointerType()); 5657 return CK_CPointerToObjCPointerCast; 5658 } 5659 } 5660 5661 /// Prepares for a scalar cast, performing all the necessary stages 5662 /// except the final cast and returning the kind required. 5663 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5664 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5665 // Also, callers should have filtered out the invalid cases with 5666 // pointers. Everything else should be possible. 5667 5668 QualType SrcTy = Src.get()->getType(); 5669 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5670 return CK_NoOp; 5671 5672 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5673 case Type::STK_MemberPointer: 5674 llvm_unreachable("member pointer type in C"); 5675 5676 case Type::STK_CPointer: 5677 case Type::STK_BlockPointer: 5678 case Type::STK_ObjCObjectPointer: 5679 switch (DestTy->getScalarTypeKind()) { 5680 case Type::STK_CPointer: { 5681 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5682 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5683 if (SrcAS != DestAS) 5684 return CK_AddressSpaceConversion; 5685 return CK_BitCast; 5686 } 5687 case Type::STK_BlockPointer: 5688 return (SrcKind == Type::STK_BlockPointer 5689 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5690 case Type::STK_ObjCObjectPointer: 5691 if (SrcKind == Type::STK_ObjCObjectPointer) 5692 return CK_BitCast; 5693 if (SrcKind == Type::STK_CPointer) 5694 return CK_CPointerToObjCPointerCast; 5695 maybeExtendBlockObject(Src); 5696 return CK_BlockPointerToObjCPointerCast; 5697 case Type::STK_Bool: 5698 return CK_PointerToBoolean; 5699 case Type::STK_Integral: 5700 return CK_PointerToIntegral; 5701 case Type::STK_Floating: 5702 case Type::STK_FloatingComplex: 5703 case Type::STK_IntegralComplex: 5704 case Type::STK_MemberPointer: 5705 llvm_unreachable("illegal cast from pointer"); 5706 } 5707 llvm_unreachable("Should have returned before this"); 5708 5709 case Type::STK_Bool: // casting from bool is like casting from an integer 5710 case Type::STK_Integral: 5711 switch (DestTy->getScalarTypeKind()) { 5712 case Type::STK_CPointer: 5713 case Type::STK_ObjCObjectPointer: 5714 case Type::STK_BlockPointer: 5715 if (Src.get()->isNullPointerConstant(Context, 5716 Expr::NPC_ValueDependentIsNull)) 5717 return CK_NullToPointer; 5718 return CK_IntegralToPointer; 5719 case Type::STK_Bool: 5720 return CK_IntegralToBoolean; 5721 case Type::STK_Integral: 5722 return CK_IntegralCast; 5723 case Type::STK_Floating: 5724 return CK_IntegralToFloating; 5725 case Type::STK_IntegralComplex: 5726 Src = ImpCastExprToType(Src.get(), 5727 DestTy->castAs<ComplexType>()->getElementType(), 5728 CK_IntegralCast); 5729 return CK_IntegralRealToComplex; 5730 case Type::STK_FloatingComplex: 5731 Src = ImpCastExprToType(Src.get(), 5732 DestTy->castAs<ComplexType>()->getElementType(), 5733 CK_IntegralToFloating); 5734 return CK_FloatingRealToComplex; 5735 case Type::STK_MemberPointer: 5736 llvm_unreachable("member pointer type in C"); 5737 } 5738 llvm_unreachable("Should have returned before this"); 5739 5740 case Type::STK_Floating: 5741 switch (DestTy->getScalarTypeKind()) { 5742 case Type::STK_Floating: 5743 return CK_FloatingCast; 5744 case Type::STK_Bool: 5745 return CK_FloatingToBoolean; 5746 case Type::STK_Integral: 5747 return CK_FloatingToIntegral; 5748 case Type::STK_FloatingComplex: 5749 Src = ImpCastExprToType(Src.get(), 5750 DestTy->castAs<ComplexType>()->getElementType(), 5751 CK_FloatingCast); 5752 return CK_FloatingRealToComplex; 5753 case Type::STK_IntegralComplex: 5754 Src = ImpCastExprToType(Src.get(), 5755 DestTy->castAs<ComplexType>()->getElementType(), 5756 CK_FloatingToIntegral); 5757 return CK_IntegralRealToComplex; 5758 case Type::STK_CPointer: 5759 case Type::STK_ObjCObjectPointer: 5760 case Type::STK_BlockPointer: 5761 llvm_unreachable("valid float->pointer cast?"); 5762 case Type::STK_MemberPointer: 5763 llvm_unreachable("member pointer type in C"); 5764 } 5765 llvm_unreachable("Should have returned before this"); 5766 5767 case Type::STK_FloatingComplex: 5768 switch (DestTy->getScalarTypeKind()) { 5769 case Type::STK_FloatingComplex: 5770 return CK_FloatingComplexCast; 5771 case Type::STK_IntegralComplex: 5772 return CK_FloatingComplexToIntegralComplex; 5773 case Type::STK_Floating: { 5774 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5775 if (Context.hasSameType(ET, DestTy)) 5776 return CK_FloatingComplexToReal; 5777 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5778 return CK_FloatingCast; 5779 } 5780 case Type::STK_Bool: 5781 return CK_FloatingComplexToBoolean; 5782 case Type::STK_Integral: 5783 Src = ImpCastExprToType(Src.get(), 5784 SrcTy->castAs<ComplexType>()->getElementType(), 5785 CK_FloatingComplexToReal); 5786 return CK_FloatingToIntegral; 5787 case Type::STK_CPointer: 5788 case Type::STK_ObjCObjectPointer: 5789 case Type::STK_BlockPointer: 5790 llvm_unreachable("valid complex float->pointer cast?"); 5791 case Type::STK_MemberPointer: 5792 llvm_unreachable("member pointer type in C"); 5793 } 5794 llvm_unreachable("Should have returned before this"); 5795 5796 case Type::STK_IntegralComplex: 5797 switch (DestTy->getScalarTypeKind()) { 5798 case Type::STK_FloatingComplex: 5799 return CK_IntegralComplexToFloatingComplex; 5800 case Type::STK_IntegralComplex: 5801 return CK_IntegralComplexCast; 5802 case Type::STK_Integral: { 5803 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5804 if (Context.hasSameType(ET, DestTy)) 5805 return CK_IntegralComplexToReal; 5806 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5807 return CK_IntegralCast; 5808 } 5809 case Type::STK_Bool: 5810 return CK_IntegralComplexToBoolean; 5811 case Type::STK_Floating: 5812 Src = ImpCastExprToType(Src.get(), 5813 SrcTy->castAs<ComplexType>()->getElementType(), 5814 CK_IntegralComplexToReal); 5815 return CK_IntegralToFloating; 5816 case Type::STK_CPointer: 5817 case Type::STK_ObjCObjectPointer: 5818 case Type::STK_BlockPointer: 5819 llvm_unreachable("valid complex int->pointer cast?"); 5820 case Type::STK_MemberPointer: 5821 llvm_unreachable("member pointer type in C"); 5822 } 5823 llvm_unreachable("Should have returned before this"); 5824 } 5825 5826 llvm_unreachable("Unhandled scalar cast"); 5827 } 5828 5829 static bool breakDownVectorType(QualType type, uint64_t &len, 5830 QualType &eltType) { 5831 // Vectors are simple. 5832 if (const VectorType *vecType = type->getAs<VectorType>()) { 5833 len = vecType->getNumElements(); 5834 eltType = vecType->getElementType(); 5835 assert(eltType->isScalarType()); 5836 return true; 5837 } 5838 5839 // We allow lax conversion to and from non-vector types, but only if 5840 // they're real types (i.e. non-complex, non-pointer scalar types). 5841 if (!type->isRealType()) return false; 5842 5843 len = 1; 5844 eltType = type; 5845 return true; 5846 } 5847 5848 /// Are the two types lax-compatible vector types? That is, given 5849 /// that one of them is a vector, do they have equal storage sizes, 5850 /// where the storage size is the number of elements times the element 5851 /// size? 5852 /// 5853 /// This will also return false if either of the types is neither a 5854 /// vector nor a real type. 5855 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5856 assert(destTy->isVectorType() || srcTy->isVectorType()); 5857 5858 // Disallow lax conversions between scalars and ExtVectors (these 5859 // conversions are allowed for other vector types because common headers 5860 // depend on them). Most scalar OP ExtVector cases are handled by the 5861 // splat path anyway, which does what we want (convert, not bitcast). 5862 // What this rules out for ExtVectors is crazy things like char4*float. 5863 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5864 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5865 5866 uint64_t srcLen, destLen; 5867 QualType srcEltTy, destEltTy; 5868 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5869 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5870 5871 // ASTContext::getTypeSize will return the size rounded up to a 5872 // power of 2, so instead of using that, we need to use the raw 5873 // element size multiplied by the element count. 5874 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5875 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5876 5877 return (srcLen * srcEltSize == destLen * destEltSize); 5878 } 5879 5880 /// Is this a legal conversion between two types, one of which is 5881 /// known to be a vector type? 5882 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5883 assert(destTy->isVectorType() || srcTy->isVectorType()); 5884 5885 if (!Context.getLangOpts().LaxVectorConversions) 5886 return false; 5887 return areLaxCompatibleVectorTypes(srcTy, destTy); 5888 } 5889 5890 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5891 CastKind &Kind) { 5892 assert(VectorTy->isVectorType() && "Not a vector type!"); 5893 5894 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5895 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5896 return Diag(R.getBegin(), 5897 Ty->isVectorType() ? 5898 diag::err_invalid_conversion_between_vectors : 5899 diag::err_invalid_conversion_between_vector_and_integer) 5900 << VectorTy << Ty << R; 5901 } else 5902 return Diag(R.getBegin(), 5903 diag::err_invalid_conversion_between_vector_and_scalar) 5904 << VectorTy << Ty << R; 5905 5906 Kind = CK_BitCast; 5907 return false; 5908 } 5909 5910 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5911 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5912 5913 if (DestElemTy == SplattedExpr->getType()) 5914 return SplattedExpr; 5915 5916 assert(DestElemTy->isFloatingType() || 5917 DestElemTy->isIntegralOrEnumerationType()); 5918 5919 CastKind CK; 5920 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5921 // OpenCL requires that we convert `true` boolean expressions to -1, but 5922 // only when splatting vectors. 5923 if (DestElemTy->isFloatingType()) { 5924 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5925 // in two steps: boolean to signed integral, then to floating. 5926 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5927 CK_BooleanToSignedIntegral); 5928 SplattedExpr = CastExprRes.get(); 5929 CK = CK_IntegralToFloating; 5930 } else { 5931 CK = CK_BooleanToSignedIntegral; 5932 } 5933 } else { 5934 ExprResult CastExprRes = SplattedExpr; 5935 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5936 if (CastExprRes.isInvalid()) 5937 return ExprError(); 5938 SplattedExpr = CastExprRes.get(); 5939 } 5940 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5941 } 5942 5943 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5944 Expr *CastExpr, CastKind &Kind) { 5945 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5946 5947 QualType SrcTy = CastExpr->getType(); 5948 5949 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5950 // an ExtVectorType. 5951 // In OpenCL, casts between vectors of different types are not allowed. 5952 // (See OpenCL 6.2). 5953 if (SrcTy->isVectorType()) { 5954 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5955 || (getLangOpts().OpenCL && 5956 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5957 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5958 << DestTy << SrcTy << R; 5959 return ExprError(); 5960 } 5961 Kind = CK_BitCast; 5962 return CastExpr; 5963 } 5964 5965 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5966 // conversion will take place first from scalar to elt type, and then 5967 // splat from elt type to vector. 5968 if (SrcTy->isPointerType()) 5969 return Diag(R.getBegin(), 5970 diag::err_invalid_conversion_between_vector_and_scalar) 5971 << DestTy << SrcTy << R; 5972 5973 Kind = CK_VectorSplat; 5974 return prepareVectorSplat(DestTy, CastExpr); 5975 } 5976 5977 ExprResult 5978 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5979 Declarator &D, ParsedType &Ty, 5980 SourceLocation RParenLoc, Expr *CastExpr) { 5981 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5982 "ActOnCastExpr(): missing type or expr"); 5983 5984 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5985 if (D.isInvalidType()) 5986 return ExprError(); 5987 5988 if (getLangOpts().CPlusPlus) { 5989 // Check that there are no default arguments (C++ only). 5990 CheckExtraCXXDefaultArguments(D); 5991 } else { 5992 // Make sure any TypoExprs have been dealt with. 5993 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5994 if (!Res.isUsable()) 5995 return ExprError(); 5996 CastExpr = Res.get(); 5997 } 5998 5999 checkUnusedDeclAttributes(D); 6000 6001 QualType castType = castTInfo->getType(); 6002 Ty = CreateParsedType(castType, castTInfo); 6003 6004 bool isVectorLiteral = false; 6005 6006 // Check for an altivec or OpenCL literal, 6007 // i.e. all the elements are integer constants. 6008 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6009 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6010 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6011 && castType->isVectorType() && (PE || PLE)) { 6012 if (PLE && PLE->getNumExprs() == 0) { 6013 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6014 return ExprError(); 6015 } 6016 if (PE || PLE->getNumExprs() == 1) { 6017 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6018 if (!E->getType()->isVectorType()) 6019 isVectorLiteral = true; 6020 } 6021 else 6022 isVectorLiteral = true; 6023 } 6024 6025 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6026 // then handle it as such. 6027 if (isVectorLiteral) 6028 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6029 6030 // If the Expr being casted is a ParenListExpr, handle it specially. 6031 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6032 // sequence of BinOp comma operators. 6033 if (isa<ParenListExpr>(CastExpr)) { 6034 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6035 if (Result.isInvalid()) return ExprError(); 6036 CastExpr = Result.get(); 6037 } 6038 6039 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6040 !getSourceManager().isInSystemMacro(LParenLoc)) 6041 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6042 6043 CheckTollFreeBridgeCast(castType, CastExpr); 6044 6045 CheckObjCBridgeRelatedCast(castType, CastExpr); 6046 6047 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6048 6049 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6050 } 6051 6052 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6053 SourceLocation RParenLoc, Expr *E, 6054 TypeSourceInfo *TInfo) { 6055 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6056 "Expected paren or paren list expression"); 6057 6058 Expr **exprs; 6059 unsigned numExprs; 6060 Expr *subExpr; 6061 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6062 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6063 LiteralLParenLoc = PE->getLParenLoc(); 6064 LiteralRParenLoc = PE->getRParenLoc(); 6065 exprs = PE->getExprs(); 6066 numExprs = PE->getNumExprs(); 6067 } else { // isa<ParenExpr> by assertion at function entrance 6068 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6069 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6070 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6071 exprs = &subExpr; 6072 numExprs = 1; 6073 } 6074 6075 QualType Ty = TInfo->getType(); 6076 assert(Ty->isVectorType() && "Expected vector type"); 6077 6078 SmallVector<Expr *, 8> initExprs; 6079 const VectorType *VTy = Ty->getAs<VectorType>(); 6080 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6081 6082 // '(...)' form of vector initialization in AltiVec: the number of 6083 // initializers must be one or must match the size of the vector. 6084 // If a single value is specified in the initializer then it will be 6085 // replicated to all the components of the vector 6086 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6087 // The number of initializers must be one or must match the size of the 6088 // vector. If a single value is specified in the initializer then it will 6089 // be replicated to all the components of the vector 6090 if (numExprs == 1) { 6091 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6092 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6093 if (Literal.isInvalid()) 6094 return ExprError(); 6095 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6096 PrepareScalarCast(Literal, ElemTy)); 6097 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6098 } 6099 else if (numExprs < numElems) { 6100 Diag(E->getExprLoc(), 6101 diag::err_incorrect_number_of_vector_initializers); 6102 return ExprError(); 6103 } 6104 else 6105 initExprs.append(exprs, exprs + numExprs); 6106 } 6107 else { 6108 // For OpenCL, when the number of initializers is a single value, 6109 // it will be replicated to all components of the vector. 6110 if (getLangOpts().OpenCL && 6111 VTy->getVectorKind() == VectorType::GenericVector && 6112 numExprs == 1) { 6113 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6114 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6115 if (Literal.isInvalid()) 6116 return ExprError(); 6117 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6118 PrepareScalarCast(Literal, ElemTy)); 6119 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6120 } 6121 6122 initExprs.append(exprs, exprs + numExprs); 6123 } 6124 // FIXME: This means that pretty-printing the final AST will produce curly 6125 // braces instead of the original commas. 6126 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6127 initExprs, LiteralRParenLoc); 6128 initE->setType(Ty); 6129 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6130 } 6131 6132 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6133 /// the ParenListExpr into a sequence of comma binary operators. 6134 ExprResult 6135 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6136 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6137 if (!E) 6138 return OrigExpr; 6139 6140 ExprResult Result(E->getExpr(0)); 6141 6142 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6143 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6144 E->getExpr(i)); 6145 6146 if (Result.isInvalid()) return ExprError(); 6147 6148 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6149 } 6150 6151 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6152 SourceLocation R, 6153 MultiExprArg Val) { 6154 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6155 return expr; 6156 } 6157 6158 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6159 /// constant and the other is not a pointer. Returns true if a diagnostic is 6160 /// emitted. 6161 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6162 SourceLocation QuestionLoc) { 6163 Expr *NullExpr = LHSExpr; 6164 Expr *NonPointerExpr = RHSExpr; 6165 Expr::NullPointerConstantKind NullKind = 6166 NullExpr->isNullPointerConstant(Context, 6167 Expr::NPC_ValueDependentIsNotNull); 6168 6169 if (NullKind == Expr::NPCK_NotNull) { 6170 NullExpr = RHSExpr; 6171 NonPointerExpr = LHSExpr; 6172 NullKind = 6173 NullExpr->isNullPointerConstant(Context, 6174 Expr::NPC_ValueDependentIsNotNull); 6175 } 6176 6177 if (NullKind == Expr::NPCK_NotNull) 6178 return false; 6179 6180 if (NullKind == Expr::NPCK_ZeroExpression) 6181 return false; 6182 6183 if (NullKind == Expr::NPCK_ZeroLiteral) { 6184 // In this case, check to make sure that we got here from a "NULL" 6185 // string in the source code. 6186 NullExpr = NullExpr->IgnoreParenImpCasts(); 6187 SourceLocation loc = NullExpr->getExprLoc(); 6188 if (!findMacroSpelling(loc, "NULL")) 6189 return false; 6190 } 6191 6192 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6193 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6194 << NonPointerExpr->getType() << DiagType 6195 << NonPointerExpr->getSourceRange(); 6196 return true; 6197 } 6198 6199 /// \brief Return false if the condition expression is valid, true otherwise. 6200 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6201 QualType CondTy = Cond->getType(); 6202 6203 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6204 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6205 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6206 << CondTy << Cond->getSourceRange(); 6207 return true; 6208 } 6209 6210 // C99 6.5.15p2 6211 if (CondTy->isScalarType()) return false; 6212 6213 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6214 << CondTy << Cond->getSourceRange(); 6215 return true; 6216 } 6217 6218 /// \brief Handle when one or both operands are void type. 6219 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6220 ExprResult &RHS) { 6221 Expr *LHSExpr = LHS.get(); 6222 Expr *RHSExpr = RHS.get(); 6223 6224 if (!LHSExpr->getType()->isVoidType()) 6225 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6226 << RHSExpr->getSourceRange(); 6227 if (!RHSExpr->getType()->isVoidType()) 6228 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6229 << LHSExpr->getSourceRange(); 6230 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6231 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6232 return S.Context.VoidTy; 6233 } 6234 6235 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6236 /// true otherwise. 6237 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6238 QualType PointerTy) { 6239 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6240 !NullExpr.get()->isNullPointerConstant(S.Context, 6241 Expr::NPC_ValueDependentIsNull)) 6242 return true; 6243 6244 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6245 return false; 6246 } 6247 6248 /// \brief Checks compatibility between two pointers and return the resulting 6249 /// type. 6250 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6251 ExprResult &RHS, 6252 SourceLocation Loc) { 6253 QualType LHSTy = LHS.get()->getType(); 6254 QualType RHSTy = RHS.get()->getType(); 6255 6256 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6257 // Two identical pointers types are always compatible. 6258 return LHSTy; 6259 } 6260 6261 QualType lhptee, rhptee; 6262 6263 // Get the pointee types. 6264 bool IsBlockPointer = false; 6265 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6266 lhptee = LHSBTy->getPointeeType(); 6267 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6268 IsBlockPointer = true; 6269 } else { 6270 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6271 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6272 } 6273 6274 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6275 // differently qualified versions of compatible types, the result type is 6276 // a pointer to an appropriately qualified version of the composite 6277 // type. 6278 6279 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6280 // clause doesn't make sense for our extensions. E.g. address space 2 should 6281 // be incompatible with address space 3: they may live on different devices or 6282 // anything. 6283 Qualifiers lhQual = lhptee.getQualifiers(); 6284 Qualifiers rhQual = rhptee.getQualifiers(); 6285 6286 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6287 lhQual.removeCVRQualifiers(); 6288 rhQual.removeCVRQualifiers(); 6289 6290 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6291 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6292 6293 // For OpenCL: 6294 // 1. If LHS and RHS types match exactly and: 6295 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6296 // (b) AS overlap => generate addrspacecast 6297 // (c) AS don't overlap => give an error 6298 // 2. if LHS and RHS types don't match: 6299 // (a) AS match => use standard C rules, generate bitcast 6300 // (b) AS overlap => generate addrspacecast instead of bitcast 6301 // (c) AS don't overlap => give an error 6302 6303 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6304 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6305 6306 // OpenCL cases 1c, 2a, 2b, and 2c. 6307 if (CompositeTy.isNull()) { 6308 // In this situation, we assume void* type. No especially good 6309 // reason, but this is what gcc does, and we do have to pick 6310 // to get a consistent AST. 6311 QualType incompatTy; 6312 if (S.getLangOpts().OpenCL) { 6313 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6314 // spaces is disallowed. 6315 unsigned ResultAddrSpace; 6316 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6317 // Cases 2a and 2b. 6318 ResultAddrSpace = lhQual.getAddressSpace(); 6319 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6320 // Cases 2a and 2b. 6321 ResultAddrSpace = rhQual.getAddressSpace(); 6322 } else { 6323 // Cases 1c and 2c. 6324 S.Diag(Loc, 6325 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6326 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6327 << RHS.get()->getSourceRange(); 6328 return QualType(); 6329 } 6330 6331 // Continue handling cases 2a and 2b. 6332 incompatTy = S.Context.getPointerType( 6333 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6334 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6335 (lhQual.getAddressSpace() != ResultAddrSpace) 6336 ? CK_AddressSpaceConversion /* 2b */ 6337 : CK_BitCast /* 2a */); 6338 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6339 (rhQual.getAddressSpace() != ResultAddrSpace) 6340 ? CK_AddressSpaceConversion /* 2b */ 6341 : CK_BitCast /* 2a */); 6342 } else { 6343 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6344 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6345 << RHS.get()->getSourceRange(); 6346 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6347 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6348 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6349 } 6350 return incompatTy; 6351 } 6352 6353 // The pointer types are compatible. 6354 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6355 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6356 if (IsBlockPointer) 6357 ResultTy = S.Context.getBlockPointerType(ResultTy); 6358 else { 6359 // Cases 1a and 1b for OpenCL. 6360 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6361 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6362 ? CK_BitCast /* 1a */ 6363 : CK_AddressSpaceConversion /* 1b */; 6364 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6365 ? CK_BitCast /* 1a */ 6366 : CK_AddressSpaceConversion /* 1b */; 6367 ResultTy = S.Context.getPointerType(ResultTy); 6368 } 6369 6370 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6371 // if the target type does not change. 6372 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6373 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6374 return ResultTy; 6375 } 6376 6377 /// \brief Return the resulting type when the operands are both block pointers. 6378 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6379 ExprResult &LHS, 6380 ExprResult &RHS, 6381 SourceLocation Loc) { 6382 QualType LHSTy = LHS.get()->getType(); 6383 QualType RHSTy = RHS.get()->getType(); 6384 6385 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6386 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6387 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6388 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6389 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6390 return destType; 6391 } 6392 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6393 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6394 << RHS.get()->getSourceRange(); 6395 return QualType(); 6396 } 6397 6398 // We have 2 block pointer types. 6399 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6400 } 6401 6402 /// \brief Return the resulting type when the operands are both pointers. 6403 static QualType 6404 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6405 ExprResult &RHS, 6406 SourceLocation Loc) { 6407 // get the pointer types 6408 QualType LHSTy = LHS.get()->getType(); 6409 QualType RHSTy = RHS.get()->getType(); 6410 6411 // get the "pointed to" types 6412 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6413 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6414 6415 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6416 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6417 // Figure out necessary qualifiers (C99 6.5.15p6) 6418 QualType destPointee 6419 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6420 QualType destType = S.Context.getPointerType(destPointee); 6421 // Add qualifiers if necessary. 6422 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6423 // Promote to void*. 6424 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6425 return destType; 6426 } 6427 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6428 QualType destPointee 6429 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6430 QualType destType = S.Context.getPointerType(destPointee); 6431 // Add qualifiers if necessary. 6432 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6433 // Promote to void*. 6434 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6435 return destType; 6436 } 6437 6438 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6439 } 6440 6441 /// \brief Return false if the first expression is not an integer and the second 6442 /// expression is not a pointer, true otherwise. 6443 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6444 Expr* PointerExpr, SourceLocation Loc, 6445 bool IsIntFirstExpr) { 6446 if (!PointerExpr->getType()->isPointerType() || 6447 !Int.get()->getType()->isIntegerType()) 6448 return false; 6449 6450 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6451 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6452 6453 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6454 << Expr1->getType() << Expr2->getType() 6455 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6456 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6457 CK_IntegralToPointer); 6458 return true; 6459 } 6460 6461 /// \brief Simple conversion between integer and floating point types. 6462 /// 6463 /// Used when handling the OpenCL conditional operator where the 6464 /// condition is a vector while the other operands are scalar. 6465 /// 6466 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6467 /// types are either integer or floating type. Between the two 6468 /// operands, the type with the higher rank is defined as the "result 6469 /// type". The other operand needs to be promoted to the same type. No 6470 /// other type promotion is allowed. We cannot use 6471 /// UsualArithmeticConversions() for this purpose, since it always 6472 /// promotes promotable types. 6473 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6474 ExprResult &RHS, 6475 SourceLocation QuestionLoc) { 6476 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6477 if (LHS.isInvalid()) 6478 return QualType(); 6479 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6480 if (RHS.isInvalid()) 6481 return QualType(); 6482 6483 // For conversion purposes, we ignore any qualifiers. 6484 // For example, "const float" and "float" are equivalent. 6485 QualType LHSType = 6486 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6487 QualType RHSType = 6488 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6489 6490 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6491 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6492 << LHSType << LHS.get()->getSourceRange(); 6493 return QualType(); 6494 } 6495 6496 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6497 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6498 << RHSType << RHS.get()->getSourceRange(); 6499 return QualType(); 6500 } 6501 6502 // If both types are identical, no conversion is needed. 6503 if (LHSType == RHSType) 6504 return LHSType; 6505 6506 // Now handle "real" floating types (i.e. float, double, long double). 6507 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6508 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6509 /*IsCompAssign = */ false); 6510 6511 // Finally, we have two differing integer types. 6512 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6513 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6514 } 6515 6516 /// \brief Convert scalar operands to a vector that matches the 6517 /// condition in length. 6518 /// 6519 /// Used when handling the OpenCL conditional operator where the 6520 /// condition is a vector while the other operands are scalar. 6521 /// 6522 /// We first compute the "result type" for the scalar operands 6523 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6524 /// into a vector of that type where the length matches the condition 6525 /// vector type. s6.11.6 requires that the element types of the result 6526 /// and the condition must have the same number of bits. 6527 static QualType 6528 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6529 QualType CondTy, SourceLocation QuestionLoc) { 6530 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6531 if (ResTy.isNull()) return QualType(); 6532 6533 const VectorType *CV = CondTy->getAs<VectorType>(); 6534 assert(CV); 6535 6536 // Determine the vector result type 6537 unsigned NumElements = CV->getNumElements(); 6538 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6539 6540 // Ensure that all types have the same number of bits 6541 if (S.Context.getTypeSize(CV->getElementType()) 6542 != S.Context.getTypeSize(ResTy)) { 6543 // Since VectorTy is created internally, it does not pretty print 6544 // with an OpenCL name. Instead, we just print a description. 6545 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6546 SmallString<64> Str; 6547 llvm::raw_svector_ostream OS(Str); 6548 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6549 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6550 << CondTy << OS.str(); 6551 return QualType(); 6552 } 6553 6554 // Convert operands to the vector result type 6555 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6556 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6557 6558 return VectorTy; 6559 } 6560 6561 /// \brief Return false if this is a valid OpenCL condition vector 6562 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6563 SourceLocation QuestionLoc) { 6564 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6565 // integral type. 6566 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6567 assert(CondTy); 6568 QualType EleTy = CondTy->getElementType(); 6569 if (EleTy->isIntegerType()) return false; 6570 6571 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6572 << Cond->getType() << Cond->getSourceRange(); 6573 return true; 6574 } 6575 6576 /// \brief Return false if the vector condition type and the vector 6577 /// result type are compatible. 6578 /// 6579 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6580 /// number of elements, and their element types have the same number 6581 /// of bits. 6582 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6583 SourceLocation QuestionLoc) { 6584 const VectorType *CV = CondTy->getAs<VectorType>(); 6585 const VectorType *RV = VecResTy->getAs<VectorType>(); 6586 assert(CV && RV); 6587 6588 if (CV->getNumElements() != RV->getNumElements()) { 6589 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6590 << CondTy << VecResTy; 6591 return true; 6592 } 6593 6594 QualType CVE = CV->getElementType(); 6595 QualType RVE = RV->getElementType(); 6596 6597 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6598 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6599 << CondTy << VecResTy; 6600 return true; 6601 } 6602 6603 return false; 6604 } 6605 6606 /// \brief Return the resulting type for the conditional operator in 6607 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6608 /// s6.3.i) when the condition is a vector type. 6609 static QualType 6610 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6611 ExprResult &LHS, ExprResult &RHS, 6612 SourceLocation QuestionLoc) { 6613 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6614 if (Cond.isInvalid()) 6615 return QualType(); 6616 QualType CondTy = Cond.get()->getType(); 6617 6618 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6619 return QualType(); 6620 6621 // If either operand is a vector then find the vector type of the 6622 // result as specified in OpenCL v1.1 s6.3.i. 6623 if (LHS.get()->getType()->isVectorType() || 6624 RHS.get()->getType()->isVectorType()) { 6625 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6626 /*isCompAssign*/false, 6627 /*AllowBothBool*/true, 6628 /*AllowBoolConversions*/false); 6629 if (VecResTy.isNull()) return QualType(); 6630 // The result type must match the condition type as specified in 6631 // OpenCL v1.1 s6.11.6. 6632 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6633 return QualType(); 6634 return VecResTy; 6635 } 6636 6637 // Both operands are scalar. 6638 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6639 } 6640 6641 /// \brief Return true if the Expr is block type 6642 static bool checkBlockType(Sema &S, const Expr *E) { 6643 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6644 QualType Ty = CE->getCallee()->getType(); 6645 if (Ty->isBlockPointerType()) { 6646 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6647 return true; 6648 } 6649 } 6650 return false; 6651 } 6652 6653 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6654 /// In that case, LHS = cond. 6655 /// C99 6.5.15 6656 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6657 ExprResult &RHS, ExprValueKind &VK, 6658 ExprObjectKind &OK, 6659 SourceLocation QuestionLoc) { 6660 6661 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6662 if (!LHSResult.isUsable()) return QualType(); 6663 LHS = LHSResult; 6664 6665 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6666 if (!RHSResult.isUsable()) return QualType(); 6667 RHS = RHSResult; 6668 6669 // C++ is sufficiently different to merit its own checker. 6670 if (getLangOpts().CPlusPlus) 6671 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6672 6673 VK = VK_RValue; 6674 OK = OK_Ordinary; 6675 6676 // The OpenCL operator with a vector condition is sufficiently 6677 // different to merit its own checker. 6678 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6679 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6680 6681 // First, check the condition. 6682 Cond = UsualUnaryConversions(Cond.get()); 6683 if (Cond.isInvalid()) 6684 return QualType(); 6685 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6686 return QualType(); 6687 6688 // Now check the two expressions. 6689 if (LHS.get()->getType()->isVectorType() || 6690 RHS.get()->getType()->isVectorType()) 6691 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6692 /*AllowBothBool*/true, 6693 /*AllowBoolConversions*/false); 6694 6695 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6696 if (LHS.isInvalid() || RHS.isInvalid()) 6697 return QualType(); 6698 6699 QualType LHSTy = LHS.get()->getType(); 6700 QualType RHSTy = RHS.get()->getType(); 6701 6702 // Diagnose attempts to convert between __float128 and long double where 6703 // such conversions currently can't be handled. 6704 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6705 Diag(QuestionLoc, 6706 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6707 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6708 return QualType(); 6709 } 6710 6711 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6712 // selection operator (?:). 6713 if (getLangOpts().OpenCL && 6714 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6715 return QualType(); 6716 } 6717 6718 // If both operands have arithmetic type, do the usual arithmetic conversions 6719 // to find a common type: C99 6.5.15p3,5. 6720 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6721 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6722 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6723 6724 return ResTy; 6725 } 6726 6727 // If both operands are the same structure or union type, the result is that 6728 // type. 6729 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6730 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6731 if (LHSRT->getDecl() == RHSRT->getDecl()) 6732 // "If both the operands have structure or union type, the result has 6733 // that type." This implies that CV qualifiers are dropped. 6734 return LHSTy.getUnqualifiedType(); 6735 // FIXME: Type of conditional expression must be complete in C mode. 6736 } 6737 6738 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6739 // The following || allows only one side to be void (a GCC-ism). 6740 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6741 return checkConditionalVoidType(*this, LHS, RHS); 6742 } 6743 6744 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6745 // the type of the other operand." 6746 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6747 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6748 6749 // All objective-c pointer type analysis is done here. 6750 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6751 QuestionLoc); 6752 if (LHS.isInvalid() || RHS.isInvalid()) 6753 return QualType(); 6754 if (!compositeType.isNull()) 6755 return compositeType; 6756 6757 6758 // Handle block pointer types. 6759 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6760 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6761 QuestionLoc); 6762 6763 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6764 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6765 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6766 QuestionLoc); 6767 6768 // GCC compatibility: soften pointer/integer mismatch. Note that 6769 // null pointers have been filtered out by this point. 6770 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6771 /*isIntFirstExpr=*/true)) 6772 return RHSTy; 6773 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6774 /*isIntFirstExpr=*/false)) 6775 return LHSTy; 6776 6777 // Emit a better diagnostic if one of the expressions is a null pointer 6778 // constant and the other is not a pointer type. In this case, the user most 6779 // likely forgot to take the address of the other expression. 6780 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6781 return QualType(); 6782 6783 // Otherwise, the operands are not compatible. 6784 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6785 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6786 << RHS.get()->getSourceRange(); 6787 return QualType(); 6788 } 6789 6790 /// FindCompositeObjCPointerType - Helper method to find composite type of 6791 /// two objective-c pointer types of the two input expressions. 6792 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6793 SourceLocation QuestionLoc) { 6794 QualType LHSTy = LHS.get()->getType(); 6795 QualType RHSTy = RHS.get()->getType(); 6796 6797 // Handle things like Class and struct objc_class*. Here we case the result 6798 // to the pseudo-builtin, because that will be implicitly cast back to the 6799 // redefinition type if an attempt is made to access its fields. 6800 if (LHSTy->isObjCClassType() && 6801 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6802 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6803 return LHSTy; 6804 } 6805 if (RHSTy->isObjCClassType() && 6806 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6807 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6808 return RHSTy; 6809 } 6810 // And the same for struct objc_object* / id 6811 if (LHSTy->isObjCIdType() && 6812 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6813 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6814 return LHSTy; 6815 } 6816 if (RHSTy->isObjCIdType() && 6817 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6818 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6819 return RHSTy; 6820 } 6821 // And the same for struct objc_selector* / SEL 6822 if (Context.isObjCSelType(LHSTy) && 6823 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6824 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6825 return LHSTy; 6826 } 6827 if (Context.isObjCSelType(RHSTy) && 6828 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6829 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6830 return RHSTy; 6831 } 6832 // Check constraints for Objective-C object pointers types. 6833 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6834 6835 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6836 // Two identical object pointer types are always compatible. 6837 return LHSTy; 6838 } 6839 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6840 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6841 QualType compositeType = LHSTy; 6842 6843 // If both operands are interfaces and either operand can be 6844 // assigned to the other, use that type as the composite 6845 // type. This allows 6846 // xxx ? (A*) a : (B*) b 6847 // where B is a subclass of A. 6848 // 6849 // Additionally, as for assignment, if either type is 'id' 6850 // allow silent coercion. Finally, if the types are 6851 // incompatible then make sure to use 'id' as the composite 6852 // type so the result is acceptable for sending messages to. 6853 6854 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6855 // It could return the composite type. 6856 if (!(compositeType = 6857 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6858 // Nothing more to do. 6859 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6860 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6861 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6862 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6863 } else if ((LHSTy->isObjCQualifiedIdType() || 6864 RHSTy->isObjCQualifiedIdType()) && 6865 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6866 // Need to handle "id<xx>" explicitly. 6867 // GCC allows qualified id and any Objective-C type to devolve to 6868 // id. Currently localizing to here until clear this should be 6869 // part of ObjCQualifiedIdTypesAreCompatible. 6870 compositeType = Context.getObjCIdType(); 6871 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6872 compositeType = Context.getObjCIdType(); 6873 } else { 6874 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6875 << LHSTy << RHSTy 6876 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6877 QualType incompatTy = Context.getObjCIdType(); 6878 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6879 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6880 return incompatTy; 6881 } 6882 // The object pointer types are compatible. 6883 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6884 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6885 return compositeType; 6886 } 6887 // Check Objective-C object pointer types and 'void *' 6888 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6889 if (getLangOpts().ObjCAutoRefCount) { 6890 // ARC forbids the implicit conversion of object pointers to 'void *', 6891 // so these types are not compatible. 6892 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6893 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6894 LHS = RHS = true; 6895 return QualType(); 6896 } 6897 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6898 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6899 QualType destPointee 6900 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6901 QualType destType = Context.getPointerType(destPointee); 6902 // Add qualifiers if necessary. 6903 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6904 // Promote to void*. 6905 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6906 return destType; 6907 } 6908 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6909 if (getLangOpts().ObjCAutoRefCount) { 6910 // ARC forbids the implicit conversion of object pointers to 'void *', 6911 // so these types are not compatible. 6912 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6913 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6914 LHS = RHS = true; 6915 return QualType(); 6916 } 6917 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6918 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6919 QualType destPointee 6920 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6921 QualType destType = Context.getPointerType(destPointee); 6922 // Add qualifiers if necessary. 6923 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6924 // Promote to void*. 6925 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6926 return destType; 6927 } 6928 return QualType(); 6929 } 6930 6931 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6932 /// ParenRange in parentheses. 6933 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6934 const PartialDiagnostic &Note, 6935 SourceRange ParenRange) { 6936 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6937 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6938 EndLoc.isValid()) { 6939 Self.Diag(Loc, Note) 6940 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6941 << FixItHint::CreateInsertion(EndLoc, ")"); 6942 } else { 6943 // We can't display the parentheses, so just show the bare note. 6944 Self.Diag(Loc, Note) << ParenRange; 6945 } 6946 } 6947 6948 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6949 return BinaryOperator::isAdditiveOp(Opc) || 6950 BinaryOperator::isMultiplicativeOp(Opc) || 6951 BinaryOperator::isShiftOp(Opc); 6952 } 6953 6954 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6955 /// expression, either using a built-in or overloaded operator, 6956 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6957 /// expression. 6958 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6959 Expr **RHSExprs) { 6960 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6961 E = E->IgnoreImpCasts(); 6962 E = E->IgnoreConversionOperator(); 6963 E = E->IgnoreImpCasts(); 6964 6965 // Built-in binary operator. 6966 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6967 if (IsArithmeticOp(OP->getOpcode())) { 6968 *Opcode = OP->getOpcode(); 6969 *RHSExprs = OP->getRHS(); 6970 return true; 6971 } 6972 } 6973 6974 // Overloaded operator. 6975 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6976 if (Call->getNumArgs() != 2) 6977 return false; 6978 6979 // Make sure this is really a binary operator that is safe to pass into 6980 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6981 OverloadedOperatorKind OO = Call->getOperator(); 6982 if (OO < OO_Plus || OO > OO_Arrow || 6983 OO == OO_PlusPlus || OO == OO_MinusMinus) 6984 return false; 6985 6986 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6987 if (IsArithmeticOp(OpKind)) { 6988 *Opcode = OpKind; 6989 *RHSExprs = Call->getArg(1); 6990 return true; 6991 } 6992 } 6993 6994 return false; 6995 } 6996 6997 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6998 /// or is a logical expression such as (x==y) which has int type, but is 6999 /// commonly interpreted as boolean. 7000 static bool ExprLooksBoolean(Expr *E) { 7001 E = E->IgnoreParenImpCasts(); 7002 7003 if (E->getType()->isBooleanType()) 7004 return true; 7005 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7006 return OP->isComparisonOp() || OP->isLogicalOp(); 7007 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7008 return OP->getOpcode() == UO_LNot; 7009 if (E->getType()->isPointerType()) 7010 return true; 7011 7012 return false; 7013 } 7014 7015 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7016 /// and binary operator are mixed in a way that suggests the programmer assumed 7017 /// the conditional operator has higher precedence, for example: 7018 /// "int x = a + someBinaryCondition ? 1 : 2". 7019 static void DiagnoseConditionalPrecedence(Sema &Self, 7020 SourceLocation OpLoc, 7021 Expr *Condition, 7022 Expr *LHSExpr, 7023 Expr *RHSExpr) { 7024 BinaryOperatorKind CondOpcode; 7025 Expr *CondRHS; 7026 7027 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7028 return; 7029 if (!ExprLooksBoolean(CondRHS)) 7030 return; 7031 7032 // The condition is an arithmetic binary expression, with a right- 7033 // hand side that looks boolean, so warn. 7034 7035 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7036 << Condition->getSourceRange() 7037 << BinaryOperator::getOpcodeStr(CondOpcode); 7038 7039 SuggestParentheses(Self, OpLoc, 7040 Self.PDiag(diag::note_precedence_silence) 7041 << BinaryOperator::getOpcodeStr(CondOpcode), 7042 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7043 7044 SuggestParentheses(Self, OpLoc, 7045 Self.PDiag(diag::note_precedence_conditional_first), 7046 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7047 } 7048 7049 /// Compute the nullability of a conditional expression. 7050 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7051 QualType LHSTy, QualType RHSTy, 7052 ASTContext &Ctx) { 7053 if (!ResTy->isAnyPointerType()) 7054 return ResTy; 7055 7056 auto GetNullability = [&Ctx](QualType Ty) { 7057 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7058 if (Kind) 7059 return *Kind; 7060 return NullabilityKind::Unspecified; 7061 }; 7062 7063 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7064 NullabilityKind MergedKind; 7065 7066 // Compute nullability of a binary conditional expression. 7067 if (IsBin) { 7068 if (LHSKind == NullabilityKind::NonNull) 7069 MergedKind = NullabilityKind::NonNull; 7070 else 7071 MergedKind = RHSKind; 7072 // Compute nullability of a normal conditional expression. 7073 } else { 7074 if (LHSKind == NullabilityKind::Nullable || 7075 RHSKind == NullabilityKind::Nullable) 7076 MergedKind = NullabilityKind::Nullable; 7077 else if (LHSKind == NullabilityKind::NonNull) 7078 MergedKind = RHSKind; 7079 else if (RHSKind == NullabilityKind::NonNull) 7080 MergedKind = LHSKind; 7081 else 7082 MergedKind = NullabilityKind::Unspecified; 7083 } 7084 7085 // Return if ResTy already has the correct nullability. 7086 if (GetNullability(ResTy) == MergedKind) 7087 return ResTy; 7088 7089 // Strip all nullability from ResTy. 7090 while (ResTy->getNullability(Ctx)) 7091 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7092 7093 // Create a new AttributedType with the new nullability kind. 7094 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7095 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7096 } 7097 7098 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7099 /// in the case of a the GNU conditional expr extension. 7100 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7101 SourceLocation ColonLoc, 7102 Expr *CondExpr, Expr *LHSExpr, 7103 Expr *RHSExpr) { 7104 if (!getLangOpts().CPlusPlus) { 7105 // C cannot handle TypoExpr nodes in the condition because it 7106 // doesn't handle dependent types properly, so make sure any TypoExprs have 7107 // been dealt with before checking the operands. 7108 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7109 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7110 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7111 7112 if (!CondResult.isUsable()) 7113 return ExprError(); 7114 7115 if (LHSExpr) { 7116 if (!LHSResult.isUsable()) 7117 return ExprError(); 7118 } 7119 7120 if (!RHSResult.isUsable()) 7121 return ExprError(); 7122 7123 CondExpr = CondResult.get(); 7124 LHSExpr = LHSResult.get(); 7125 RHSExpr = RHSResult.get(); 7126 } 7127 7128 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7129 // was the condition. 7130 OpaqueValueExpr *opaqueValue = nullptr; 7131 Expr *commonExpr = nullptr; 7132 if (!LHSExpr) { 7133 commonExpr = CondExpr; 7134 // Lower out placeholder types first. This is important so that we don't 7135 // try to capture a placeholder. This happens in few cases in C++; such 7136 // as Objective-C++'s dictionary subscripting syntax. 7137 if (commonExpr->hasPlaceholderType()) { 7138 ExprResult result = CheckPlaceholderExpr(commonExpr); 7139 if (!result.isUsable()) return ExprError(); 7140 commonExpr = result.get(); 7141 } 7142 // We usually want to apply unary conversions *before* saving, except 7143 // in the special case of a C++ l-value conditional. 7144 if (!(getLangOpts().CPlusPlus 7145 && !commonExpr->isTypeDependent() 7146 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7147 && commonExpr->isGLValue() 7148 && commonExpr->isOrdinaryOrBitFieldObject() 7149 && RHSExpr->isOrdinaryOrBitFieldObject() 7150 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7151 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7152 if (commonRes.isInvalid()) 7153 return ExprError(); 7154 commonExpr = commonRes.get(); 7155 } 7156 7157 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7158 commonExpr->getType(), 7159 commonExpr->getValueKind(), 7160 commonExpr->getObjectKind(), 7161 commonExpr); 7162 LHSExpr = CondExpr = opaqueValue; 7163 } 7164 7165 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7166 ExprValueKind VK = VK_RValue; 7167 ExprObjectKind OK = OK_Ordinary; 7168 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7169 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7170 VK, OK, QuestionLoc); 7171 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7172 RHS.isInvalid()) 7173 return ExprError(); 7174 7175 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7176 RHS.get()); 7177 7178 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7179 7180 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7181 Context); 7182 7183 if (!commonExpr) 7184 return new (Context) 7185 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7186 RHS.get(), result, VK, OK); 7187 7188 return new (Context) BinaryConditionalOperator( 7189 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7190 ColonLoc, result, VK, OK); 7191 } 7192 7193 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7194 // being closely modeled after the C99 spec:-). The odd characteristic of this 7195 // routine is it effectively iqnores the qualifiers on the top level pointee. 7196 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7197 // FIXME: add a couple examples in this comment. 7198 static Sema::AssignConvertType 7199 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7200 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7201 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7202 7203 // get the "pointed to" type (ignoring qualifiers at the top level) 7204 const Type *lhptee, *rhptee; 7205 Qualifiers lhq, rhq; 7206 std::tie(lhptee, lhq) = 7207 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7208 std::tie(rhptee, rhq) = 7209 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7210 7211 Sema::AssignConvertType ConvTy = Sema::Compatible; 7212 7213 // C99 6.5.16.1p1: This following citation is common to constraints 7214 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7215 // qualifiers of the type *pointed to* by the right; 7216 7217 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7218 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7219 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7220 // Ignore lifetime for further calculation. 7221 lhq.removeObjCLifetime(); 7222 rhq.removeObjCLifetime(); 7223 } 7224 7225 if (!lhq.compatiblyIncludes(rhq)) { 7226 // Treat address-space mismatches as fatal. TODO: address subspaces 7227 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7228 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7229 7230 // It's okay to add or remove GC or lifetime qualifiers when converting to 7231 // and from void*. 7232 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7233 .compatiblyIncludes( 7234 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7235 && (lhptee->isVoidType() || rhptee->isVoidType())) 7236 ; // keep old 7237 7238 // Treat lifetime mismatches as fatal. 7239 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7240 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7241 7242 // For GCC/MS compatibility, other qualifier mismatches are treated 7243 // as still compatible in C. 7244 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7245 } 7246 7247 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7248 // incomplete type and the other is a pointer to a qualified or unqualified 7249 // version of void... 7250 if (lhptee->isVoidType()) { 7251 if (rhptee->isIncompleteOrObjectType()) 7252 return ConvTy; 7253 7254 // As an extension, we allow cast to/from void* to function pointer. 7255 assert(rhptee->isFunctionType()); 7256 return Sema::FunctionVoidPointer; 7257 } 7258 7259 if (rhptee->isVoidType()) { 7260 if (lhptee->isIncompleteOrObjectType()) 7261 return ConvTy; 7262 7263 // As an extension, we allow cast to/from void* to function pointer. 7264 assert(lhptee->isFunctionType()); 7265 return Sema::FunctionVoidPointer; 7266 } 7267 7268 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7269 // unqualified versions of compatible types, ... 7270 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7271 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7272 // Check if the pointee types are compatible ignoring the sign. 7273 // We explicitly check for char so that we catch "char" vs 7274 // "unsigned char" on systems where "char" is unsigned. 7275 if (lhptee->isCharType()) 7276 ltrans = S.Context.UnsignedCharTy; 7277 else if (lhptee->hasSignedIntegerRepresentation()) 7278 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7279 7280 if (rhptee->isCharType()) 7281 rtrans = S.Context.UnsignedCharTy; 7282 else if (rhptee->hasSignedIntegerRepresentation()) 7283 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7284 7285 if (ltrans == rtrans) { 7286 // Types are compatible ignoring the sign. Qualifier incompatibility 7287 // takes priority over sign incompatibility because the sign 7288 // warning can be disabled. 7289 if (ConvTy != Sema::Compatible) 7290 return ConvTy; 7291 7292 return Sema::IncompatiblePointerSign; 7293 } 7294 7295 // If we are a multi-level pointer, it's possible that our issue is simply 7296 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7297 // the eventual target type is the same and the pointers have the same 7298 // level of indirection, this must be the issue. 7299 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7300 do { 7301 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7302 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7303 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7304 7305 if (lhptee == rhptee) 7306 return Sema::IncompatibleNestedPointerQualifiers; 7307 } 7308 7309 // General pointer incompatibility takes priority over qualifiers. 7310 return Sema::IncompatiblePointer; 7311 } 7312 if (!S.getLangOpts().CPlusPlus && 7313 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7314 return Sema::IncompatiblePointer; 7315 return ConvTy; 7316 } 7317 7318 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7319 /// block pointer types are compatible or whether a block and normal pointer 7320 /// are compatible. It is more restrict than comparing two function pointer 7321 // types. 7322 static Sema::AssignConvertType 7323 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7324 QualType RHSType) { 7325 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7326 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7327 7328 QualType lhptee, rhptee; 7329 7330 // get the "pointed to" type (ignoring qualifiers at the top level) 7331 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7332 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7333 7334 // In C++, the types have to match exactly. 7335 if (S.getLangOpts().CPlusPlus) 7336 return Sema::IncompatibleBlockPointer; 7337 7338 Sema::AssignConvertType ConvTy = Sema::Compatible; 7339 7340 // For blocks we enforce that qualifiers are identical. 7341 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7342 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7343 7344 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7345 return Sema::IncompatibleBlockPointer; 7346 7347 return ConvTy; 7348 } 7349 7350 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7351 /// for assignment compatibility. 7352 static Sema::AssignConvertType 7353 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7354 QualType RHSType) { 7355 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7356 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7357 7358 if (LHSType->isObjCBuiltinType()) { 7359 // Class is not compatible with ObjC object pointers. 7360 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7361 !RHSType->isObjCQualifiedClassType()) 7362 return Sema::IncompatiblePointer; 7363 return Sema::Compatible; 7364 } 7365 if (RHSType->isObjCBuiltinType()) { 7366 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7367 !LHSType->isObjCQualifiedClassType()) 7368 return Sema::IncompatiblePointer; 7369 return Sema::Compatible; 7370 } 7371 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7372 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7373 7374 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7375 // make an exception for id<P> 7376 !LHSType->isObjCQualifiedIdType()) 7377 return Sema::CompatiblePointerDiscardsQualifiers; 7378 7379 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7380 return Sema::Compatible; 7381 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7382 return Sema::IncompatibleObjCQualifiedId; 7383 return Sema::IncompatiblePointer; 7384 } 7385 7386 Sema::AssignConvertType 7387 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7388 QualType LHSType, QualType RHSType) { 7389 // Fake up an opaque expression. We don't actually care about what 7390 // cast operations are required, so if CheckAssignmentConstraints 7391 // adds casts to this they'll be wasted, but fortunately that doesn't 7392 // usually happen on valid code. 7393 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7394 ExprResult RHSPtr = &RHSExpr; 7395 CastKind K = CK_Invalid; 7396 7397 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7398 } 7399 7400 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7401 /// has code to accommodate several GCC extensions when type checking 7402 /// pointers. Here are some objectionable examples that GCC considers warnings: 7403 /// 7404 /// int a, *pint; 7405 /// short *pshort; 7406 /// struct foo *pfoo; 7407 /// 7408 /// pint = pshort; // warning: assignment from incompatible pointer type 7409 /// a = pint; // warning: assignment makes integer from pointer without a cast 7410 /// pint = a; // warning: assignment makes pointer from integer without a cast 7411 /// pint = pfoo; // warning: assignment from incompatible pointer type 7412 /// 7413 /// As a result, the code for dealing with pointers is more complex than the 7414 /// C99 spec dictates. 7415 /// 7416 /// Sets 'Kind' for any result kind except Incompatible. 7417 Sema::AssignConvertType 7418 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7419 CastKind &Kind, bool ConvertRHS) { 7420 QualType RHSType = RHS.get()->getType(); 7421 QualType OrigLHSType = LHSType; 7422 7423 // Get canonical types. We're not formatting these types, just comparing 7424 // them. 7425 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7426 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7427 7428 // Common case: no conversion required. 7429 if (LHSType == RHSType) { 7430 Kind = CK_NoOp; 7431 return Compatible; 7432 } 7433 7434 // If we have an atomic type, try a non-atomic assignment, then just add an 7435 // atomic qualification step. 7436 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7437 Sema::AssignConvertType result = 7438 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7439 if (result != Compatible) 7440 return result; 7441 if (Kind != CK_NoOp && ConvertRHS) 7442 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7443 Kind = CK_NonAtomicToAtomic; 7444 return Compatible; 7445 } 7446 7447 // If the left-hand side is a reference type, then we are in a 7448 // (rare!) case where we've allowed the use of references in C, 7449 // e.g., as a parameter type in a built-in function. In this case, 7450 // just make sure that the type referenced is compatible with the 7451 // right-hand side type. The caller is responsible for adjusting 7452 // LHSType so that the resulting expression does not have reference 7453 // type. 7454 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7455 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7456 Kind = CK_LValueBitCast; 7457 return Compatible; 7458 } 7459 return Incompatible; 7460 } 7461 7462 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7463 // to the same ExtVector type. 7464 if (LHSType->isExtVectorType()) { 7465 if (RHSType->isExtVectorType()) 7466 return Incompatible; 7467 if (RHSType->isArithmeticType()) { 7468 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7469 if (ConvertRHS) 7470 RHS = prepareVectorSplat(LHSType, RHS.get()); 7471 Kind = CK_VectorSplat; 7472 return Compatible; 7473 } 7474 } 7475 7476 // Conversions to or from vector type. 7477 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7478 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7479 // Allow assignments of an AltiVec vector type to an equivalent GCC 7480 // vector type and vice versa 7481 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7482 Kind = CK_BitCast; 7483 return Compatible; 7484 } 7485 7486 // If we are allowing lax vector conversions, and LHS and RHS are both 7487 // vectors, the total size only needs to be the same. This is a bitcast; 7488 // no bits are changed but the result type is different. 7489 if (isLaxVectorConversion(RHSType, LHSType)) { 7490 Kind = CK_BitCast; 7491 return IncompatibleVectors; 7492 } 7493 } 7494 7495 // When the RHS comes from another lax conversion (e.g. binops between 7496 // scalars and vectors) the result is canonicalized as a vector. When the 7497 // LHS is also a vector, the lax is allowed by the condition above. Handle 7498 // the case where LHS is a scalar. 7499 if (LHSType->isScalarType()) { 7500 const VectorType *VecType = RHSType->getAs<VectorType>(); 7501 if (VecType && VecType->getNumElements() == 1 && 7502 isLaxVectorConversion(RHSType, LHSType)) { 7503 ExprResult *VecExpr = &RHS; 7504 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7505 Kind = CK_BitCast; 7506 return Compatible; 7507 } 7508 } 7509 7510 return Incompatible; 7511 } 7512 7513 // Diagnose attempts to convert between __float128 and long double where 7514 // such conversions currently can't be handled. 7515 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7516 return Incompatible; 7517 7518 // Arithmetic conversions. 7519 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7520 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7521 if (ConvertRHS) 7522 Kind = PrepareScalarCast(RHS, LHSType); 7523 return Compatible; 7524 } 7525 7526 // Conversions to normal pointers. 7527 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7528 // U* -> T* 7529 if (isa<PointerType>(RHSType)) { 7530 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7531 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7532 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7533 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7534 } 7535 7536 // int -> T* 7537 if (RHSType->isIntegerType()) { 7538 Kind = CK_IntegralToPointer; // FIXME: null? 7539 return IntToPointer; 7540 } 7541 7542 // C pointers are not compatible with ObjC object pointers, 7543 // with two exceptions: 7544 if (isa<ObjCObjectPointerType>(RHSType)) { 7545 // - conversions to void* 7546 if (LHSPointer->getPointeeType()->isVoidType()) { 7547 Kind = CK_BitCast; 7548 return Compatible; 7549 } 7550 7551 // - conversions from 'Class' to the redefinition type 7552 if (RHSType->isObjCClassType() && 7553 Context.hasSameType(LHSType, 7554 Context.getObjCClassRedefinitionType())) { 7555 Kind = CK_BitCast; 7556 return Compatible; 7557 } 7558 7559 Kind = CK_BitCast; 7560 return IncompatiblePointer; 7561 } 7562 7563 // U^ -> void* 7564 if (RHSType->getAs<BlockPointerType>()) { 7565 if (LHSPointer->getPointeeType()->isVoidType()) { 7566 Kind = CK_BitCast; 7567 return Compatible; 7568 } 7569 } 7570 7571 return Incompatible; 7572 } 7573 7574 // Conversions to block pointers. 7575 if (isa<BlockPointerType>(LHSType)) { 7576 // U^ -> T^ 7577 if (RHSType->isBlockPointerType()) { 7578 Kind = CK_BitCast; 7579 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7580 } 7581 7582 // int or null -> T^ 7583 if (RHSType->isIntegerType()) { 7584 Kind = CK_IntegralToPointer; // FIXME: null 7585 return IntToBlockPointer; 7586 } 7587 7588 // id -> T^ 7589 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7590 Kind = CK_AnyPointerToBlockPointerCast; 7591 return Compatible; 7592 } 7593 7594 // void* -> T^ 7595 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7596 if (RHSPT->getPointeeType()->isVoidType()) { 7597 Kind = CK_AnyPointerToBlockPointerCast; 7598 return Compatible; 7599 } 7600 7601 return Incompatible; 7602 } 7603 7604 // Conversions to Objective-C pointers. 7605 if (isa<ObjCObjectPointerType>(LHSType)) { 7606 // A* -> B* 7607 if (RHSType->isObjCObjectPointerType()) { 7608 Kind = CK_BitCast; 7609 Sema::AssignConvertType result = 7610 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7611 if (getLangOpts().ObjCAutoRefCount && 7612 result == Compatible && 7613 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7614 result = IncompatibleObjCWeakRef; 7615 return result; 7616 } 7617 7618 // int or null -> A* 7619 if (RHSType->isIntegerType()) { 7620 Kind = CK_IntegralToPointer; // FIXME: null 7621 return IntToPointer; 7622 } 7623 7624 // In general, C pointers are not compatible with ObjC object pointers, 7625 // with two exceptions: 7626 if (isa<PointerType>(RHSType)) { 7627 Kind = CK_CPointerToObjCPointerCast; 7628 7629 // - conversions from 'void*' 7630 if (RHSType->isVoidPointerType()) { 7631 return Compatible; 7632 } 7633 7634 // - conversions to 'Class' from its redefinition type 7635 if (LHSType->isObjCClassType() && 7636 Context.hasSameType(RHSType, 7637 Context.getObjCClassRedefinitionType())) { 7638 return Compatible; 7639 } 7640 7641 return IncompatiblePointer; 7642 } 7643 7644 // Only under strict condition T^ is compatible with an Objective-C pointer. 7645 if (RHSType->isBlockPointerType() && 7646 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7647 if (ConvertRHS) 7648 maybeExtendBlockObject(RHS); 7649 Kind = CK_BlockPointerToObjCPointerCast; 7650 return Compatible; 7651 } 7652 7653 return Incompatible; 7654 } 7655 7656 // Conversions from pointers that are not covered by the above. 7657 if (isa<PointerType>(RHSType)) { 7658 // T* -> _Bool 7659 if (LHSType == Context.BoolTy) { 7660 Kind = CK_PointerToBoolean; 7661 return Compatible; 7662 } 7663 7664 // T* -> int 7665 if (LHSType->isIntegerType()) { 7666 Kind = CK_PointerToIntegral; 7667 return PointerToInt; 7668 } 7669 7670 return Incompatible; 7671 } 7672 7673 // Conversions from Objective-C pointers that are not covered by the above. 7674 if (isa<ObjCObjectPointerType>(RHSType)) { 7675 // T* -> _Bool 7676 if (LHSType == Context.BoolTy) { 7677 Kind = CK_PointerToBoolean; 7678 return Compatible; 7679 } 7680 7681 // T* -> int 7682 if (LHSType->isIntegerType()) { 7683 Kind = CK_PointerToIntegral; 7684 return PointerToInt; 7685 } 7686 7687 return Incompatible; 7688 } 7689 7690 // struct A -> struct B 7691 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7692 if (Context.typesAreCompatible(LHSType, RHSType)) { 7693 Kind = CK_NoOp; 7694 return Compatible; 7695 } 7696 } 7697 7698 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7699 Kind = CK_IntToOCLSampler; 7700 return Compatible; 7701 } 7702 7703 return Incompatible; 7704 } 7705 7706 /// \brief Constructs a transparent union from an expression that is 7707 /// used to initialize the transparent union. 7708 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7709 ExprResult &EResult, QualType UnionType, 7710 FieldDecl *Field) { 7711 // Build an initializer list that designates the appropriate member 7712 // of the transparent union. 7713 Expr *E = EResult.get(); 7714 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7715 E, SourceLocation()); 7716 Initializer->setType(UnionType); 7717 Initializer->setInitializedFieldInUnion(Field); 7718 7719 // Build a compound literal constructing a value of the transparent 7720 // union type from this initializer list. 7721 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7722 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7723 VK_RValue, Initializer, false); 7724 } 7725 7726 Sema::AssignConvertType 7727 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7728 ExprResult &RHS) { 7729 QualType RHSType = RHS.get()->getType(); 7730 7731 // If the ArgType is a Union type, we want to handle a potential 7732 // transparent_union GCC extension. 7733 const RecordType *UT = ArgType->getAsUnionType(); 7734 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7735 return Incompatible; 7736 7737 // The field to initialize within the transparent union. 7738 RecordDecl *UD = UT->getDecl(); 7739 FieldDecl *InitField = nullptr; 7740 // It's compatible if the expression matches any of the fields. 7741 for (auto *it : UD->fields()) { 7742 if (it->getType()->isPointerType()) { 7743 // If the transparent union contains a pointer type, we allow: 7744 // 1) void pointer 7745 // 2) null pointer constant 7746 if (RHSType->isPointerType()) 7747 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7748 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7749 InitField = it; 7750 break; 7751 } 7752 7753 if (RHS.get()->isNullPointerConstant(Context, 7754 Expr::NPC_ValueDependentIsNull)) { 7755 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7756 CK_NullToPointer); 7757 InitField = it; 7758 break; 7759 } 7760 } 7761 7762 CastKind Kind = CK_Invalid; 7763 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7764 == Compatible) { 7765 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7766 InitField = it; 7767 break; 7768 } 7769 } 7770 7771 if (!InitField) 7772 return Incompatible; 7773 7774 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7775 return Compatible; 7776 } 7777 7778 Sema::AssignConvertType 7779 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7780 bool Diagnose, 7781 bool DiagnoseCFAudited, 7782 bool ConvertRHS) { 7783 // We need to be able to tell the caller whether we diagnosed a problem, if 7784 // they ask us to issue diagnostics. 7785 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7786 7787 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7788 // we can't avoid *all* modifications at the moment, so we need some somewhere 7789 // to put the updated value. 7790 ExprResult LocalRHS = CallerRHS; 7791 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7792 7793 if (getLangOpts().CPlusPlus) { 7794 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7795 // C++ 5.17p3: If the left operand is not of class type, the 7796 // expression is implicitly converted (C++ 4) to the 7797 // cv-unqualified type of the left operand. 7798 QualType RHSType = RHS.get()->getType(); 7799 if (Diagnose) { 7800 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7801 AA_Assigning); 7802 } else { 7803 ImplicitConversionSequence ICS = 7804 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7805 /*SuppressUserConversions=*/false, 7806 /*AllowExplicit=*/false, 7807 /*InOverloadResolution=*/false, 7808 /*CStyle=*/false, 7809 /*AllowObjCWritebackConversion=*/false); 7810 if (ICS.isFailure()) 7811 return Incompatible; 7812 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7813 ICS, AA_Assigning); 7814 } 7815 if (RHS.isInvalid()) 7816 return Incompatible; 7817 Sema::AssignConvertType result = Compatible; 7818 if (getLangOpts().ObjCAutoRefCount && 7819 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7820 result = IncompatibleObjCWeakRef; 7821 return result; 7822 } 7823 7824 // FIXME: Currently, we fall through and treat C++ classes like C 7825 // structures. 7826 // FIXME: We also fall through for atomics; not sure what should 7827 // happen there, though. 7828 } else if (RHS.get()->getType() == Context.OverloadTy) { 7829 // As a set of extensions to C, we support overloading on functions. These 7830 // functions need to be resolved here. 7831 DeclAccessPair DAP; 7832 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7833 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7834 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7835 else 7836 return Incompatible; 7837 } 7838 7839 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7840 // a null pointer constant. 7841 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7842 LHSType->isBlockPointerType()) && 7843 RHS.get()->isNullPointerConstant(Context, 7844 Expr::NPC_ValueDependentIsNull)) { 7845 if (Diagnose || ConvertRHS) { 7846 CastKind Kind; 7847 CXXCastPath Path; 7848 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7849 /*IgnoreBaseAccess=*/false, Diagnose); 7850 if (ConvertRHS) 7851 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7852 } 7853 return Compatible; 7854 } 7855 7856 // This check seems unnatural, however it is necessary to ensure the proper 7857 // conversion of functions/arrays. If the conversion were done for all 7858 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7859 // expressions that suppress this implicit conversion (&, sizeof). 7860 // 7861 // Suppress this for references: C++ 8.5.3p5. 7862 if (!LHSType->isReferenceType()) { 7863 // FIXME: We potentially allocate here even if ConvertRHS is false. 7864 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7865 if (RHS.isInvalid()) 7866 return Incompatible; 7867 } 7868 7869 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7870 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7871 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7872 if (PDecl && !PDecl->hasDefinition()) { 7873 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7874 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7875 } 7876 } 7877 7878 CastKind Kind = CK_Invalid; 7879 Sema::AssignConvertType result = 7880 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7881 7882 // C99 6.5.16.1p2: The value of the right operand is converted to the 7883 // type of the assignment expression. 7884 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7885 // so that we can use references in built-in functions even in C. 7886 // The getNonReferenceType() call makes sure that the resulting expression 7887 // does not have reference type. 7888 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7889 QualType Ty = LHSType.getNonLValueExprType(Context); 7890 Expr *E = RHS.get(); 7891 7892 // Check for various Objective-C errors. If we are not reporting 7893 // diagnostics and just checking for errors, e.g., during overload 7894 // resolution, return Incompatible to indicate the failure. 7895 if (getLangOpts().ObjCAutoRefCount && 7896 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7897 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7898 if (!Diagnose) 7899 return Incompatible; 7900 } 7901 if (getLangOpts().ObjC1 && 7902 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7903 E->getType(), E, Diagnose) || 7904 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7905 if (!Diagnose) 7906 return Incompatible; 7907 // Replace the expression with a corrected version and continue so we 7908 // can find further errors. 7909 RHS = E; 7910 return Compatible; 7911 } 7912 7913 if (ConvertRHS) 7914 RHS = ImpCastExprToType(E, Ty, Kind); 7915 } 7916 return result; 7917 } 7918 7919 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7920 ExprResult &RHS) { 7921 Diag(Loc, diag::err_typecheck_invalid_operands) 7922 << LHS.get()->getType() << RHS.get()->getType() 7923 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7924 return QualType(); 7925 } 7926 7927 /// Try to convert a value of non-vector type to a vector type by converting 7928 /// the type to the element type of the vector and then performing a splat. 7929 /// If the language is OpenCL, we only use conversions that promote scalar 7930 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7931 /// for float->int. 7932 /// 7933 /// \param scalar - if non-null, actually perform the conversions 7934 /// \return true if the operation fails (but without diagnosing the failure) 7935 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7936 QualType scalarTy, 7937 QualType vectorEltTy, 7938 QualType vectorTy) { 7939 // The conversion to apply to the scalar before splatting it, 7940 // if necessary. 7941 CastKind scalarCast = CK_Invalid; 7942 7943 if (vectorEltTy->isIntegralType(S.Context)) { 7944 if (!scalarTy->isIntegralType(S.Context)) 7945 return true; 7946 if (S.getLangOpts().OpenCL && 7947 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7948 return true; 7949 scalarCast = CK_IntegralCast; 7950 } else if (vectorEltTy->isRealFloatingType()) { 7951 if (scalarTy->isRealFloatingType()) { 7952 if (S.getLangOpts().OpenCL && 7953 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7954 return true; 7955 scalarCast = CK_FloatingCast; 7956 } 7957 else if (scalarTy->isIntegralType(S.Context)) 7958 scalarCast = CK_IntegralToFloating; 7959 else 7960 return true; 7961 } else { 7962 return true; 7963 } 7964 7965 // Adjust scalar if desired. 7966 if (scalar) { 7967 if (scalarCast != CK_Invalid) 7968 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7969 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7970 } 7971 return false; 7972 } 7973 7974 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7975 SourceLocation Loc, bool IsCompAssign, 7976 bool AllowBothBool, 7977 bool AllowBoolConversions) { 7978 if (!IsCompAssign) { 7979 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7980 if (LHS.isInvalid()) 7981 return QualType(); 7982 } 7983 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7984 if (RHS.isInvalid()) 7985 return QualType(); 7986 7987 // For conversion purposes, we ignore any qualifiers. 7988 // For example, "const float" and "float" are equivalent. 7989 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7990 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7991 7992 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7993 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7994 assert(LHSVecType || RHSVecType); 7995 7996 // AltiVec-style "vector bool op vector bool" combinations are allowed 7997 // for some operators but not others. 7998 if (!AllowBothBool && 7999 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8000 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8001 return InvalidOperands(Loc, LHS, RHS); 8002 8003 // If the vector types are identical, return. 8004 if (Context.hasSameType(LHSType, RHSType)) 8005 return LHSType; 8006 8007 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8008 if (LHSVecType && RHSVecType && 8009 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8010 if (isa<ExtVectorType>(LHSVecType)) { 8011 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8012 return LHSType; 8013 } 8014 8015 if (!IsCompAssign) 8016 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8017 return RHSType; 8018 } 8019 8020 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8021 // can be mixed, with the result being the non-bool type. The non-bool 8022 // operand must have integer element type. 8023 if (AllowBoolConversions && LHSVecType && RHSVecType && 8024 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8025 (Context.getTypeSize(LHSVecType->getElementType()) == 8026 Context.getTypeSize(RHSVecType->getElementType()))) { 8027 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8028 LHSVecType->getElementType()->isIntegerType() && 8029 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8030 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8031 return LHSType; 8032 } 8033 if (!IsCompAssign && 8034 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8035 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8036 RHSVecType->getElementType()->isIntegerType()) { 8037 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8038 return RHSType; 8039 } 8040 } 8041 8042 // If there's an ext-vector type and a scalar, try to convert the scalar to 8043 // the vector element type and splat. 8044 // FIXME: this should also work for regular vector types as supported in GCC. 8045 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8046 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8047 LHSVecType->getElementType(), LHSType)) 8048 return LHSType; 8049 } 8050 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8051 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8052 LHSType, RHSVecType->getElementType(), 8053 RHSType)) 8054 return RHSType; 8055 } 8056 8057 // FIXME: The code below also handles convertion between vectors and 8058 // non-scalars, we should break this down into fine grained specific checks 8059 // and emit proper diagnostics. 8060 QualType VecType = LHSVecType ? LHSType : RHSType; 8061 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8062 QualType OtherType = LHSVecType ? RHSType : LHSType; 8063 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8064 if (isLaxVectorConversion(OtherType, VecType)) { 8065 // If we're allowing lax vector conversions, only the total (data) size 8066 // needs to be the same. For non compound assignment, if one of the types is 8067 // scalar, the result is always the vector type. 8068 if (!IsCompAssign) { 8069 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8070 return VecType; 8071 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8072 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8073 // type. Note that this is already done by non-compound assignments in 8074 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8075 // <1 x T> -> T. The result is also a vector type. 8076 } else if (OtherType->isExtVectorType() || 8077 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8078 ExprResult *RHSExpr = &RHS; 8079 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8080 return VecType; 8081 } 8082 } 8083 8084 // Okay, the expression is invalid. 8085 8086 // If there's a non-vector, non-real operand, diagnose that. 8087 if ((!RHSVecType && !RHSType->isRealType()) || 8088 (!LHSVecType && !LHSType->isRealType())) { 8089 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8090 << LHSType << RHSType 8091 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8092 return QualType(); 8093 } 8094 8095 // OpenCL V1.1 6.2.6.p1: 8096 // If the operands are of more than one vector type, then an error shall 8097 // occur. Implicit conversions between vector types are not permitted, per 8098 // section 6.2.1. 8099 if (getLangOpts().OpenCL && 8100 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8101 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8102 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8103 << RHSType; 8104 return QualType(); 8105 } 8106 8107 // Otherwise, use the generic diagnostic. 8108 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8109 << LHSType << RHSType 8110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8111 return QualType(); 8112 } 8113 8114 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8115 // expression. These are mainly cases where the null pointer is used as an 8116 // integer instead of a pointer. 8117 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8118 SourceLocation Loc, bool IsCompare) { 8119 // The canonical way to check for a GNU null is with isNullPointerConstant, 8120 // but we use a bit of a hack here for speed; this is a relatively 8121 // hot path, and isNullPointerConstant is slow. 8122 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8123 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8124 8125 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8126 8127 // Avoid analyzing cases where the result will either be invalid (and 8128 // diagnosed as such) or entirely valid and not something to warn about. 8129 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8130 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8131 return; 8132 8133 // Comparison operations would not make sense with a null pointer no matter 8134 // what the other expression is. 8135 if (!IsCompare) { 8136 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8137 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8138 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8139 return; 8140 } 8141 8142 // The rest of the operations only make sense with a null pointer 8143 // if the other expression is a pointer. 8144 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8145 NonNullType->canDecayToPointerType()) 8146 return; 8147 8148 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8149 << LHSNull /* LHS is NULL */ << NonNullType 8150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8151 } 8152 8153 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8154 ExprResult &RHS, 8155 SourceLocation Loc, bool IsDiv) { 8156 // Check for division/remainder by zero. 8157 llvm::APSInt RHSValue; 8158 if (!RHS.get()->isValueDependent() && 8159 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8160 S.DiagRuntimeBehavior(Loc, RHS.get(), 8161 S.PDiag(diag::warn_remainder_division_by_zero) 8162 << IsDiv << RHS.get()->getSourceRange()); 8163 } 8164 8165 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8166 SourceLocation Loc, 8167 bool IsCompAssign, bool IsDiv) { 8168 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8169 8170 if (LHS.get()->getType()->isVectorType() || 8171 RHS.get()->getType()->isVectorType()) 8172 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8173 /*AllowBothBool*/getLangOpts().AltiVec, 8174 /*AllowBoolConversions*/false); 8175 8176 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8177 if (LHS.isInvalid() || RHS.isInvalid()) 8178 return QualType(); 8179 8180 8181 if (compType.isNull() || !compType->isArithmeticType()) 8182 return InvalidOperands(Loc, LHS, RHS); 8183 if (IsDiv) 8184 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8185 return compType; 8186 } 8187 8188 QualType Sema::CheckRemainderOperands( 8189 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8190 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8191 8192 if (LHS.get()->getType()->isVectorType() || 8193 RHS.get()->getType()->isVectorType()) { 8194 if (LHS.get()->getType()->hasIntegerRepresentation() && 8195 RHS.get()->getType()->hasIntegerRepresentation()) 8196 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8197 /*AllowBothBool*/getLangOpts().AltiVec, 8198 /*AllowBoolConversions*/false); 8199 return InvalidOperands(Loc, LHS, RHS); 8200 } 8201 8202 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8203 if (LHS.isInvalid() || RHS.isInvalid()) 8204 return QualType(); 8205 8206 if (compType.isNull() || !compType->isIntegerType()) 8207 return InvalidOperands(Loc, LHS, RHS); 8208 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8209 return compType; 8210 } 8211 8212 /// \brief Diagnose invalid arithmetic on two void pointers. 8213 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8214 Expr *LHSExpr, Expr *RHSExpr) { 8215 S.Diag(Loc, S.getLangOpts().CPlusPlus 8216 ? diag::err_typecheck_pointer_arith_void_type 8217 : diag::ext_gnu_void_ptr) 8218 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8219 << RHSExpr->getSourceRange(); 8220 } 8221 8222 /// \brief Diagnose invalid arithmetic on a void pointer. 8223 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8224 Expr *Pointer) { 8225 S.Diag(Loc, S.getLangOpts().CPlusPlus 8226 ? diag::err_typecheck_pointer_arith_void_type 8227 : diag::ext_gnu_void_ptr) 8228 << 0 /* one pointer */ << Pointer->getSourceRange(); 8229 } 8230 8231 /// \brief Diagnose invalid arithmetic on two function pointers. 8232 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8233 Expr *LHS, Expr *RHS) { 8234 assert(LHS->getType()->isAnyPointerType()); 8235 assert(RHS->getType()->isAnyPointerType()); 8236 S.Diag(Loc, S.getLangOpts().CPlusPlus 8237 ? diag::err_typecheck_pointer_arith_function_type 8238 : diag::ext_gnu_ptr_func_arith) 8239 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8240 // We only show the second type if it differs from the first. 8241 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8242 RHS->getType()) 8243 << RHS->getType()->getPointeeType() 8244 << LHS->getSourceRange() << RHS->getSourceRange(); 8245 } 8246 8247 /// \brief Diagnose invalid arithmetic on a function pointer. 8248 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8249 Expr *Pointer) { 8250 assert(Pointer->getType()->isAnyPointerType()); 8251 S.Diag(Loc, S.getLangOpts().CPlusPlus 8252 ? diag::err_typecheck_pointer_arith_function_type 8253 : diag::ext_gnu_ptr_func_arith) 8254 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8255 << 0 /* one pointer, so only one type */ 8256 << Pointer->getSourceRange(); 8257 } 8258 8259 /// \brief Emit error if Operand is incomplete pointer type 8260 /// 8261 /// \returns True if pointer has incomplete type 8262 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8263 Expr *Operand) { 8264 QualType ResType = Operand->getType(); 8265 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8266 ResType = ResAtomicType->getValueType(); 8267 8268 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8269 QualType PointeeTy = ResType->getPointeeType(); 8270 return S.RequireCompleteType(Loc, PointeeTy, 8271 diag::err_typecheck_arithmetic_incomplete_type, 8272 PointeeTy, Operand->getSourceRange()); 8273 } 8274 8275 /// \brief Check the validity of an arithmetic pointer operand. 8276 /// 8277 /// If the operand has pointer type, this code will check for pointer types 8278 /// which are invalid in arithmetic operations. These will be diagnosed 8279 /// appropriately, including whether or not the use is supported as an 8280 /// extension. 8281 /// 8282 /// \returns True when the operand is valid to use (even if as an extension). 8283 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8284 Expr *Operand) { 8285 QualType ResType = Operand->getType(); 8286 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8287 ResType = ResAtomicType->getValueType(); 8288 8289 if (!ResType->isAnyPointerType()) return true; 8290 8291 QualType PointeeTy = ResType->getPointeeType(); 8292 if (PointeeTy->isVoidType()) { 8293 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8294 return !S.getLangOpts().CPlusPlus; 8295 } 8296 if (PointeeTy->isFunctionType()) { 8297 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8298 return !S.getLangOpts().CPlusPlus; 8299 } 8300 8301 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8302 8303 return true; 8304 } 8305 8306 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8307 /// operands. 8308 /// 8309 /// This routine will diagnose any invalid arithmetic on pointer operands much 8310 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8311 /// for emitting a single diagnostic even for operations where both LHS and RHS 8312 /// are (potentially problematic) pointers. 8313 /// 8314 /// \returns True when the operand is valid to use (even if as an extension). 8315 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8316 Expr *LHSExpr, Expr *RHSExpr) { 8317 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8318 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8319 if (!isLHSPointer && !isRHSPointer) return true; 8320 8321 QualType LHSPointeeTy, RHSPointeeTy; 8322 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8323 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8324 8325 // if both are pointers check if operation is valid wrt address spaces 8326 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8327 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8328 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8329 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8330 S.Diag(Loc, 8331 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8332 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8333 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8334 return false; 8335 } 8336 } 8337 8338 // Check for arithmetic on pointers to incomplete types. 8339 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8340 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8341 if (isLHSVoidPtr || isRHSVoidPtr) { 8342 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8343 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8344 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8345 8346 return !S.getLangOpts().CPlusPlus; 8347 } 8348 8349 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8350 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8351 if (isLHSFuncPtr || isRHSFuncPtr) { 8352 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8353 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8354 RHSExpr); 8355 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8356 8357 return !S.getLangOpts().CPlusPlus; 8358 } 8359 8360 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8361 return false; 8362 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8363 return false; 8364 8365 return true; 8366 } 8367 8368 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8369 /// literal. 8370 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8371 Expr *LHSExpr, Expr *RHSExpr) { 8372 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8373 Expr* IndexExpr = RHSExpr; 8374 if (!StrExpr) { 8375 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8376 IndexExpr = LHSExpr; 8377 } 8378 8379 bool IsStringPlusInt = StrExpr && 8380 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8381 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8382 return; 8383 8384 llvm::APSInt index; 8385 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8386 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8387 if (index.isNonNegative() && 8388 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8389 index.isUnsigned())) 8390 return; 8391 } 8392 8393 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8394 Self.Diag(OpLoc, diag::warn_string_plus_int) 8395 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8396 8397 // Only print a fixit for "str" + int, not for int + "str". 8398 if (IndexExpr == RHSExpr) { 8399 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8400 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8401 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8402 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8403 << FixItHint::CreateInsertion(EndLoc, "]"); 8404 } else 8405 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8406 } 8407 8408 /// \brief Emit a warning when adding a char literal to a string. 8409 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8410 Expr *LHSExpr, Expr *RHSExpr) { 8411 const Expr *StringRefExpr = LHSExpr; 8412 const CharacterLiteral *CharExpr = 8413 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8414 8415 if (!CharExpr) { 8416 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8417 StringRefExpr = RHSExpr; 8418 } 8419 8420 if (!CharExpr || !StringRefExpr) 8421 return; 8422 8423 const QualType StringType = StringRefExpr->getType(); 8424 8425 // Return if not a PointerType. 8426 if (!StringType->isAnyPointerType()) 8427 return; 8428 8429 // Return if not a CharacterType. 8430 if (!StringType->getPointeeType()->isAnyCharacterType()) 8431 return; 8432 8433 ASTContext &Ctx = Self.getASTContext(); 8434 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8435 8436 const QualType CharType = CharExpr->getType(); 8437 if (!CharType->isAnyCharacterType() && 8438 CharType->isIntegerType() && 8439 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8440 Self.Diag(OpLoc, diag::warn_string_plus_char) 8441 << DiagRange << Ctx.CharTy; 8442 } else { 8443 Self.Diag(OpLoc, diag::warn_string_plus_char) 8444 << DiagRange << CharExpr->getType(); 8445 } 8446 8447 // Only print a fixit for str + char, not for char + str. 8448 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8449 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8450 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8451 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8452 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8453 << FixItHint::CreateInsertion(EndLoc, "]"); 8454 } else { 8455 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8456 } 8457 } 8458 8459 /// \brief Emit error when two pointers are incompatible. 8460 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8461 Expr *LHSExpr, Expr *RHSExpr) { 8462 assert(LHSExpr->getType()->isAnyPointerType()); 8463 assert(RHSExpr->getType()->isAnyPointerType()); 8464 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8465 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8466 << RHSExpr->getSourceRange(); 8467 } 8468 8469 // C99 6.5.6 8470 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8471 SourceLocation Loc, BinaryOperatorKind Opc, 8472 QualType* CompLHSTy) { 8473 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8474 8475 if (LHS.get()->getType()->isVectorType() || 8476 RHS.get()->getType()->isVectorType()) { 8477 QualType compType = CheckVectorOperands( 8478 LHS, RHS, Loc, CompLHSTy, 8479 /*AllowBothBool*/getLangOpts().AltiVec, 8480 /*AllowBoolConversions*/getLangOpts().ZVector); 8481 if (CompLHSTy) *CompLHSTy = compType; 8482 return compType; 8483 } 8484 8485 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8486 if (LHS.isInvalid() || RHS.isInvalid()) 8487 return QualType(); 8488 8489 // Diagnose "string literal" '+' int and string '+' "char literal". 8490 if (Opc == BO_Add) { 8491 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8492 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8493 } 8494 8495 // handle the common case first (both operands are arithmetic). 8496 if (!compType.isNull() && compType->isArithmeticType()) { 8497 if (CompLHSTy) *CompLHSTy = compType; 8498 return compType; 8499 } 8500 8501 // Type-checking. Ultimately the pointer's going to be in PExp; 8502 // note that we bias towards the LHS being the pointer. 8503 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8504 8505 bool isObjCPointer; 8506 if (PExp->getType()->isPointerType()) { 8507 isObjCPointer = false; 8508 } else if (PExp->getType()->isObjCObjectPointerType()) { 8509 isObjCPointer = true; 8510 } else { 8511 std::swap(PExp, IExp); 8512 if (PExp->getType()->isPointerType()) { 8513 isObjCPointer = false; 8514 } else if (PExp->getType()->isObjCObjectPointerType()) { 8515 isObjCPointer = true; 8516 } else { 8517 return InvalidOperands(Loc, LHS, RHS); 8518 } 8519 } 8520 assert(PExp->getType()->isAnyPointerType()); 8521 8522 if (!IExp->getType()->isIntegerType()) 8523 return InvalidOperands(Loc, LHS, RHS); 8524 8525 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8526 return QualType(); 8527 8528 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8529 return QualType(); 8530 8531 // Check array bounds for pointer arithemtic 8532 CheckArrayAccess(PExp, IExp); 8533 8534 if (CompLHSTy) { 8535 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8536 if (LHSTy.isNull()) { 8537 LHSTy = LHS.get()->getType(); 8538 if (LHSTy->isPromotableIntegerType()) 8539 LHSTy = Context.getPromotedIntegerType(LHSTy); 8540 } 8541 *CompLHSTy = LHSTy; 8542 } 8543 8544 return PExp->getType(); 8545 } 8546 8547 // C99 6.5.6 8548 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8549 SourceLocation Loc, 8550 QualType* CompLHSTy) { 8551 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8552 8553 if (LHS.get()->getType()->isVectorType() || 8554 RHS.get()->getType()->isVectorType()) { 8555 QualType compType = CheckVectorOperands( 8556 LHS, RHS, Loc, CompLHSTy, 8557 /*AllowBothBool*/getLangOpts().AltiVec, 8558 /*AllowBoolConversions*/getLangOpts().ZVector); 8559 if (CompLHSTy) *CompLHSTy = compType; 8560 return compType; 8561 } 8562 8563 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8564 if (LHS.isInvalid() || RHS.isInvalid()) 8565 return QualType(); 8566 8567 // Enforce type constraints: C99 6.5.6p3. 8568 8569 // Handle the common case first (both operands are arithmetic). 8570 if (!compType.isNull() && compType->isArithmeticType()) { 8571 if (CompLHSTy) *CompLHSTy = compType; 8572 return compType; 8573 } 8574 8575 // Either ptr - int or ptr - ptr. 8576 if (LHS.get()->getType()->isAnyPointerType()) { 8577 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8578 8579 // Diagnose bad cases where we step over interface counts. 8580 if (LHS.get()->getType()->isObjCObjectPointerType() && 8581 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8582 return QualType(); 8583 8584 // The result type of a pointer-int computation is the pointer type. 8585 if (RHS.get()->getType()->isIntegerType()) { 8586 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8587 return QualType(); 8588 8589 // Check array bounds for pointer arithemtic 8590 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8591 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8592 8593 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8594 return LHS.get()->getType(); 8595 } 8596 8597 // Handle pointer-pointer subtractions. 8598 if (const PointerType *RHSPTy 8599 = RHS.get()->getType()->getAs<PointerType>()) { 8600 QualType rpointee = RHSPTy->getPointeeType(); 8601 8602 if (getLangOpts().CPlusPlus) { 8603 // Pointee types must be the same: C++ [expr.add] 8604 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8605 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8606 } 8607 } else { 8608 // Pointee types must be compatible C99 6.5.6p3 8609 if (!Context.typesAreCompatible( 8610 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8611 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8612 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8613 return QualType(); 8614 } 8615 } 8616 8617 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8618 LHS.get(), RHS.get())) 8619 return QualType(); 8620 8621 // The pointee type may have zero size. As an extension, a structure or 8622 // union may have zero size or an array may have zero length. In this 8623 // case subtraction does not make sense. 8624 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8625 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8626 if (ElementSize.isZero()) { 8627 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8628 << rpointee.getUnqualifiedType() 8629 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8630 } 8631 } 8632 8633 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8634 return Context.getPointerDiffType(); 8635 } 8636 } 8637 8638 return InvalidOperands(Loc, LHS, RHS); 8639 } 8640 8641 static bool isScopedEnumerationType(QualType T) { 8642 if (const EnumType *ET = T->getAs<EnumType>()) 8643 return ET->getDecl()->isScoped(); 8644 return false; 8645 } 8646 8647 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8648 SourceLocation Loc, BinaryOperatorKind Opc, 8649 QualType LHSType) { 8650 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8651 // so skip remaining warnings as we don't want to modify values within Sema. 8652 if (S.getLangOpts().OpenCL) 8653 return; 8654 8655 llvm::APSInt Right; 8656 // Check right/shifter operand 8657 if (RHS.get()->isValueDependent() || 8658 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8659 return; 8660 8661 if (Right.isNegative()) { 8662 S.DiagRuntimeBehavior(Loc, RHS.get(), 8663 S.PDiag(diag::warn_shift_negative) 8664 << RHS.get()->getSourceRange()); 8665 return; 8666 } 8667 llvm::APInt LeftBits(Right.getBitWidth(), 8668 S.Context.getTypeSize(LHS.get()->getType())); 8669 if (Right.uge(LeftBits)) { 8670 S.DiagRuntimeBehavior(Loc, RHS.get(), 8671 S.PDiag(diag::warn_shift_gt_typewidth) 8672 << RHS.get()->getSourceRange()); 8673 return; 8674 } 8675 if (Opc != BO_Shl) 8676 return; 8677 8678 // When left shifting an ICE which is signed, we can check for overflow which 8679 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8680 // integers have defined behavior modulo one more than the maximum value 8681 // representable in the result type, so never warn for those. 8682 llvm::APSInt Left; 8683 if (LHS.get()->isValueDependent() || 8684 LHSType->hasUnsignedIntegerRepresentation() || 8685 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8686 return; 8687 8688 // If LHS does not have a signed type and non-negative value 8689 // then, the behavior is undefined. Warn about it. 8690 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8691 S.DiagRuntimeBehavior(Loc, LHS.get(), 8692 S.PDiag(diag::warn_shift_lhs_negative) 8693 << LHS.get()->getSourceRange()); 8694 return; 8695 } 8696 8697 llvm::APInt ResultBits = 8698 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8699 if (LeftBits.uge(ResultBits)) 8700 return; 8701 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8702 Result = Result.shl(Right); 8703 8704 // Print the bit representation of the signed integer as an unsigned 8705 // hexadecimal number. 8706 SmallString<40> HexResult; 8707 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8708 8709 // If we are only missing a sign bit, this is less likely to result in actual 8710 // bugs -- if the result is cast back to an unsigned type, it will have the 8711 // expected value. Thus we place this behind a different warning that can be 8712 // turned off separately if needed. 8713 if (LeftBits == ResultBits - 1) { 8714 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8715 << HexResult << LHSType 8716 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8717 return; 8718 } 8719 8720 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8721 << HexResult.str() << Result.getMinSignedBits() << LHSType 8722 << Left.getBitWidth() << LHS.get()->getSourceRange() 8723 << RHS.get()->getSourceRange(); 8724 } 8725 8726 /// \brief Return the resulting type when a vector is shifted 8727 /// by a scalar or vector shift amount. 8728 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8729 SourceLocation Loc, bool IsCompAssign) { 8730 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8731 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8732 !LHS.get()->getType()->isVectorType()) { 8733 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8734 << RHS.get()->getType() << LHS.get()->getType() 8735 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8736 return QualType(); 8737 } 8738 8739 if (!IsCompAssign) { 8740 LHS = S.UsualUnaryConversions(LHS.get()); 8741 if (LHS.isInvalid()) return QualType(); 8742 } 8743 8744 RHS = S.UsualUnaryConversions(RHS.get()); 8745 if (RHS.isInvalid()) return QualType(); 8746 8747 QualType LHSType = LHS.get()->getType(); 8748 // Note that LHS might be a scalar because the routine calls not only in 8749 // OpenCL case. 8750 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8751 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8752 8753 // Note that RHS might not be a vector. 8754 QualType RHSType = RHS.get()->getType(); 8755 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8756 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8757 8758 // The operands need to be integers. 8759 if (!LHSEleType->isIntegerType()) { 8760 S.Diag(Loc, diag::err_typecheck_expect_int) 8761 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8762 return QualType(); 8763 } 8764 8765 if (!RHSEleType->isIntegerType()) { 8766 S.Diag(Loc, diag::err_typecheck_expect_int) 8767 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8768 return QualType(); 8769 } 8770 8771 if (!LHSVecTy) { 8772 assert(RHSVecTy); 8773 if (IsCompAssign) 8774 return RHSType; 8775 if (LHSEleType != RHSEleType) { 8776 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8777 LHSEleType = RHSEleType; 8778 } 8779 QualType VecTy = 8780 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8781 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8782 LHSType = VecTy; 8783 } else if (RHSVecTy) { 8784 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8785 // are applied component-wise. So if RHS is a vector, then ensure 8786 // that the number of elements is the same as LHS... 8787 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8788 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8789 << LHS.get()->getType() << RHS.get()->getType() 8790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8791 return QualType(); 8792 } 8793 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8794 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8795 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8796 if (LHSBT != RHSBT && 8797 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8798 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8799 << LHS.get()->getType() << RHS.get()->getType() 8800 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8801 } 8802 } 8803 } else { 8804 // ...else expand RHS to match the number of elements in LHS. 8805 QualType VecTy = 8806 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8807 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8808 } 8809 8810 return LHSType; 8811 } 8812 8813 // C99 6.5.7 8814 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8815 SourceLocation Loc, BinaryOperatorKind Opc, 8816 bool IsCompAssign) { 8817 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8818 8819 // Vector shifts promote their scalar inputs to vector type. 8820 if (LHS.get()->getType()->isVectorType() || 8821 RHS.get()->getType()->isVectorType()) { 8822 if (LangOpts.ZVector) { 8823 // The shift operators for the z vector extensions work basically 8824 // like general shifts, except that neither the LHS nor the RHS is 8825 // allowed to be a "vector bool". 8826 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8827 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8828 return InvalidOperands(Loc, LHS, RHS); 8829 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8830 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8831 return InvalidOperands(Loc, LHS, RHS); 8832 } 8833 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8834 } 8835 8836 // Shifts don't perform usual arithmetic conversions, they just do integer 8837 // promotions on each operand. C99 6.5.7p3 8838 8839 // For the LHS, do usual unary conversions, but then reset them away 8840 // if this is a compound assignment. 8841 ExprResult OldLHS = LHS; 8842 LHS = UsualUnaryConversions(LHS.get()); 8843 if (LHS.isInvalid()) 8844 return QualType(); 8845 QualType LHSType = LHS.get()->getType(); 8846 if (IsCompAssign) LHS = OldLHS; 8847 8848 // The RHS is simpler. 8849 RHS = UsualUnaryConversions(RHS.get()); 8850 if (RHS.isInvalid()) 8851 return QualType(); 8852 QualType RHSType = RHS.get()->getType(); 8853 8854 // C99 6.5.7p2: Each of the operands shall have integer type. 8855 if (!LHSType->hasIntegerRepresentation() || 8856 !RHSType->hasIntegerRepresentation()) 8857 return InvalidOperands(Loc, LHS, RHS); 8858 8859 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8860 // hasIntegerRepresentation() above instead of this. 8861 if (isScopedEnumerationType(LHSType) || 8862 isScopedEnumerationType(RHSType)) { 8863 return InvalidOperands(Loc, LHS, RHS); 8864 } 8865 // Sanity-check shift operands 8866 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8867 8868 // "The type of the result is that of the promoted left operand." 8869 return LHSType; 8870 } 8871 8872 static bool IsWithinTemplateSpecialization(Decl *D) { 8873 if (DeclContext *DC = D->getDeclContext()) { 8874 if (isa<ClassTemplateSpecializationDecl>(DC)) 8875 return true; 8876 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8877 return FD->isFunctionTemplateSpecialization(); 8878 } 8879 return false; 8880 } 8881 8882 /// If two different enums are compared, raise a warning. 8883 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8884 Expr *RHS) { 8885 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8886 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8887 8888 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8889 if (!LHSEnumType) 8890 return; 8891 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8892 if (!RHSEnumType) 8893 return; 8894 8895 // Ignore anonymous enums. 8896 if (!LHSEnumType->getDecl()->getIdentifier()) 8897 return; 8898 if (!RHSEnumType->getDecl()->getIdentifier()) 8899 return; 8900 8901 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8902 return; 8903 8904 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8905 << LHSStrippedType << RHSStrippedType 8906 << LHS->getSourceRange() << RHS->getSourceRange(); 8907 } 8908 8909 /// \brief Diagnose bad pointer comparisons. 8910 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8911 ExprResult &LHS, ExprResult &RHS, 8912 bool IsError) { 8913 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8914 : diag::ext_typecheck_comparison_of_distinct_pointers) 8915 << LHS.get()->getType() << RHS.get()->getType() 8916 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8917 } 8918 8919 /// \brief Returns false if the pointers are converted to a composite type, 8920 /// true otherwise. 8921 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8922 ExprResult &LHS, ExprResult &RHS) { 8923 // C++ [expr.rel]p2: 8924 // [...] Pointer conversions (4.10) and qualification 8925 // conversions (4.4) are performed on pointer operands (or on 8926 // a pointer operand and a null pointer constant) to bring 8927 // them to their composite pointer type. [...] 8928 // 8929 // C++ [expr.eq]p1 uses the same notion for (in)equality 8930 // comparisons of pointers. 8931 8932 QualType LHSType = LHS.get()->getType(); 8933 QualType RHSType = RHS.get()->getType(); 8934 assert(LHSType->isPointerType() || RHSType->isPointerType() || 8935 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 8936 8937 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 8938 if (T.isNull()) { 8939 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 8940 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 8941 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8942 else 8943 S.InvalidOperands(Loc, LHS, RHS); 8944 return true; 8945 } 8946 8947 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8948 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8949 return false; 8950 } 8951 8952 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8953 ExprResult &LHS, 8954 ExprResult &RHS, 8955 bool IsError) { 8956 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8957 : diag::ext_typecheck_comparison_of_fptr_to_void) 8958 << LHS.get()->getType() << RHS.get()->getType() 8959 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8960 } 8961 8962 static bool isObjCObjectLiteral(ExprResult &E) { 8963 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8964 case Stmt::ObjCArrayLiteralClass: 8965 case Stmt::ObjCDictionaryLiteralClass: 8966 case Stmt::ObjCStringLiteralClass: 8967 case Stmt::ObjCBoxedExprClass: 8968 return true; 8969 default: 8970 // Note that ObjCBoolLiteral is NOT an object literal! 8971 return false; 8972 } 8973 } 8974 8975 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8976 const ObjCObjectPointerType *Type = 8977 LHS->getType()->getAs<ObjCObjectPointerType>(); 8978 8979 // If this is not actually an Objective-C object, bail out. 8980 if (!Type) 8981 return false; 8982 8983 // Get the LHS object's interface type. 8984 QualType InterfaceType = Type->getPointeeType(); 8985 8986 // If the RHS isn't an Objective-C object, bail out. 8987 if (!RHS->getType()->isObjCObjectPointerType()) 8988 return false; 8989 8990 // Try to find the -isEqual: method. 8991 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8992 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8993 InterfaceType, 8994 /*instance=*/true); 8995 if (!Method) { 8996 if (Type->isObjCIdType()) { 8997 // For 'id', just check the global pool. 8998 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8999 /*receiverId=*/true); 9000 } else { 9001 // Check protocols. 9002 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9003 /*instance=*/true); 9004 } 9005 } 9006 9007 if (!Method) 9008 return false; 9009 9010 QualType T = Method->parameters()[0]->getType(); 9011 if (!T->isObjCObjectPointerType()) 9012 return false; 9013 9014 QualType R = Method->getReturnType(); 9015 if (!R->isScalarType()) 9016 return false; 9017 9018 return true; 9019 } 9020 9021 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9022 FromE = FromE->IgnoreParenImpCasts(); 9023 switch (FromE->getStmtClass()) { 9024 default: 9025 break; 9026 case Stmt::ObjCStringLiteralClass: 9027 // "string literal" 9028 return LK_String; 9029 case Stmt::ObjCArrayLiteralClass: 9030 // "array literal" 9031 return LK_Array; 9032 case Stmt::ObjCDictionaryLiteralClass: 9033 // "dictionary literal" 9034 return LK_Dictionary; 9035 case Stmt::BlockExprClass: 9036 return LK_Block; 9037 case Stmt::ObjCBoxedExprClass: { 9038 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9039 switch (Inner->getStmtClass()) { 9040 case Stmt::IntegerLiteralClass: 9041 case Stmt::FloatingLiteralClass: 9042 case Stmt::CharacterLiteralClass: 9043 case Stmt::ObjCBoolLiteralExprClass: 9044 case Stmt::CXXBoolLiteralExprClass: 9045 // "numeric literal" 9046 return LK_Numeric; 9047 case Stmt::ImplicitCastExprClass: { 9048 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9049 // Boolean literals can be represented by implicit casts. 9050 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9051 return LK_Numeric; 9052 break; 9053 } 9054 default: 9055 break; 9056 } 9057 return LK_Boxed; 9058 } 9059 } 9060 return LK_None; 9061 } 9062 9063 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9064 ExprResult &LHS, ExprResult &RHS, 9065 BinaryOperator::Opcode Opc){ 9066 Expr *Literal; 9067 Expr *Other; 9068 if (isObjCObjectLiteral(LHS)) { 9069 Literal = LHS.get(); 9070 Other = RHS.get(); 9071 } else { 9072 Literal = RHS.get(); 9073 Other = LHS.get(); 9074 } 9075 9076 // Don't warn on comparisons against nil. 9077 Other = Other->IgnoreParenCasts(); 9078 if (Other->isNullPointerConstant(S.getASTContext(), 9079 Expr::NPC_ValueDependentIsNotNull)) 9080 return; 9081 9082 // This should be kept in sync with warn_objc_literal_comparison. 9083 // LK_String should always be after the other literals, since it has its own 9084 // warning flag. 9085 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9086 assert(LiteralKind != Sema::LK_Block); 9087 if (LiteralKind == Sema::LK_None) { 9088 llvm_unreachable("Unknown Objective-C object literal kind"); 9089 } 9090 9091 if (LiteralKind == Sema::LK_String) 9092 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9093 << Literal->getSourceRange(); 9094 else 9095 S.Diag(Loc, diag::warn_objc_literal_comparison) 9096 << LiteralKind << Literal->getSourceRange(); 9097 9098 if (BinaryOperator::isEqualityOp(Opc) && 9099 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9100 SourceLocation Start = LHS.get()->getLocStart(); 9101 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9102 CharSourceRange OpRange = 9103 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9104 9105 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9106 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9107 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9108 << FixItHint::CreateInsertion(End, "]"); 9109 } 9110 } 9111 9112 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9113 ExprResult &RHS, 9114 SourceLocation Loc, 9115 BinaryOperatorKind Opc) { 9116 // Check that left hand side is !something. 9117 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9118 if (!UO || UO->getOpcode() != UO_LNot) return; 9119 9120 // Only check if the right hand side is non-bool arithmetic type. 9121 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9122 9123 // Make sure that the something in !something is not bool. 9124 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9125 if (SubExpr->isKnownToHaveBooleanValue()) return; 9126 9127 // Emit warning. 9128 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9129 << Loc; 9130 9131 // First note suggest !(x < y) 9132 SourceLocation FirstOpen = SubExpr->getLocStart(); 9133 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9134 FirstClose = S.getLocForEndOfToken(FirstClose); 9135 if (FirstClose.isInvalid()) 9136 FirstOpen = SourceLocation(); 9137 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9138 << FixItHint::CreateInsertion(FirstOpen, "(") 9139 << FixItHint::CreateInsertion(FirstClose, ")"); 9140 9141 // Second note suggests (!x) < y 9142 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9143 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9144 SecondClose = S.getLocForEndOfToken(SecondClose); 9145 if (SecondClose.isInvalid()) 9146 SecondOpen = SourceLocation(); 9147 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9148 << FixItHint::CreateInsertion(SecondOpen, "(") 9149 << FixItHint::CreateInsertion(SecondClose, ")"); 9150 } 9151 9152 // Get the decl for a simple expression: a reference to a variable, 9153 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9154 static ValueDecl *getCompareDecl(Expr *E) { 9155 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9156 return DR->getDecl(); 9157 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9158 if (Ivar->isFreeIvar()) 9159 return Ivar->getDecl(); 9160 } 9161 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9162 if (Mem->isImplicitAccess()) 9163 return Mem->getMemberDecl(); 9164 } 9165 return nullptr; 9166 } 9167 9168 // C99 6.5.8, C++ [expr.rel] 9169 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9170 SourceLocation Loc, BinaryOperatorKind Opc, 9171 bool IsRelational) { 9172 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9173 9174 // Handle vector comparisons separately. 9175 if (LHS.get()->getType()->isVectorType() || 9176 RHS.get()->getType()->isVectorType()) 9177 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9178 9179 QualType LHSType = LHS.get()->getType(); 9180 QualType RHSType = RHS.get()->getType(); 9181 9182 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9183 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9184 9185 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9186 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9187 9188 if (!LHSType->hasFloatingRepresentation() && 9189 !(LHSType->isBlockPointerType() && IsRelational) && 9190 !LHS.get()->getLocStart().isMacroID() && 9191 !RHS.get()->getLocStart().isMacroID() && 9192 ActiveTemplateInstantiations.empty()) { 9193 // For non-floating point types, check for self-comparisons of the form 9194 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9195 // often indicate logic errors in the program. 9196 // 9197 // NOTE: Don't warn about comparison expressions resulting from macro 9198 // expansion. Also don't warn about comparisons which are only self 9199 // comparisons within a template specialization. The warnings should catch 9200 // obvious cases in the definition of the template anyways. The idea is to 9201 // warn when the typed comparison operator will always evaluate to the same 9202 // result. 9203 ValueDecl *DL = getCompareDecl(LHSStripped); 9204 ValueDecl *DR = getCompareDecl(RHSStripped); 9205 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9206 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9207 << 0 // self- 9208 << (Opc == BO_EQ 9209 || Opc == BO_LE 9210 || Opc == BO_GE)); 9211 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9212 !DL->getType()->isReferenceType() && 9213 !DR->getType()->isReferenceType()) { 9214 // what is it always going to eval to? 9215 char always_evals_to; 9216 switch(Opc) { 9217 case BO_EQ: // e.g. array1 == array2 9218 always_evals_to = 0; // false 9219 break; 9220 case BO_NE: // e.g. array1 != array2 9221 always_evals_to = 1; // true 9222 break; 9223 default: 9224 // best we can say is 'a constant' 9225 always_evals_to = 2; // e.g. array1 <= array2 9226 break; 9227 } 9228 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9229 << 1 // array 9230 << always_evals_to); 9231 } 9232 9233 if (isa<CastExpr>(LHSStripped)) 9234 LHSStripped = LHSStripped->IgnoreParenCasts(); 9235 if (isa<CastExpr>(RHSStripped)) 9236 RHSStripped = RHSStripped->IgnoreParenCasts(); 9237 9238 // Warn about comparisons against a string constant (unless the other 9239 // operand is null), the user probably wants strcmp. 9240 Expr *literalString = nullptr; 9241 Expr *literalStringStripped = nullptr; 9242 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9243 !RHSStripped->isNullPointerConstant(Context, 9244 Expr::NPC_ValueDependentIsNull)) { 9245 literalString = LHS.get(); 9246 literalStringStripped = LHSStripped; 9247 } else if ((isa<StringLiteral>(RHSStripped) || 9248 isa<ObjCEncodeExpr>(RHSStripped)) && 9249 !LHSStripped->isNullPointerConstant(Context, 9250 Expr::NPC_ValueDependentIsNull)) { 9251 literalString = RHS.get(); 9252 literalStringStripped = RHSStripped; 9253 } 9254 9255 if (literalString) { 9256 DiagRuntimeBehavior(Loc, nullptr, 9257 PDiag(diag::warn_stringcompare) 9258 << isa<ObjCEncodeExpr>(literalStringStripped) 9259 << literalString->getSourceRange()); 9260 } 9261 } 9262 9263 // C99 6.5.8p3 / C99 6.5.9p4 9264 UsualArithmeticConversions(LHS, RHS); 9265 if (LHS.isInvalid() || RHS.isInvalid()) 9266 return QualType(); 9267 9268 LHSType = LHS.get()->getType(); 9269 RHSType = RHS.get()->getType(); 9270 9271 // The result of comparisons is 'bool' in C++, 'int' in C. 9272 QualType ResultTy = Context.getLogicalOperationType(); 9273 9274 if (IsRelational) { 9275 if (LHSType->isRealType() && RHSType->isRealType()) 9276 return ResultTy; 9277 } else { 9278 // Check for comparisons of floating point operands using != and ==. 9279 if (LHSType->hasFloatingRepresentation()) 9280 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9281 9282 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9283 return ResultTy; 9284 } 9285 9286 const Expr::NullPointerConstantKind LHSNullKind = 9287 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9288 const Expr::NullPointerConstantKind RHSNullKind = 9289 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9290 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9291 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9292 9293 if (!IsRelational && LHSIsNull != RHSIsNull) { 9294 bool IsEquality = Opc == BO_EQ; 9295 if (RHSIsNull) 9296 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9297 RHS.get()->getSourceRange()); 9298 else 9299 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9300 LHS.get()->getSourceRange()); 9301 } 9302 9303 if ((LHSType->isIntegerType() && !LHSIsNull) || 9304 (RHSType->isIntegerType() && !RHSIsNull)) { 9305 // Skip normal pointer conversion checks in this case; we have better 9306 // diagnostics for this below. 9307 } else if (getLangOpts().CPlusPlus) { 9308 // Equality comparison of a function pointer to a void pointer is invalid, 9309 // but we allow it as an extension. 9310 // FIXME: If we really want to allow this, should it be part of composite 9311 // pointer type computation so it works in conditionals too? 9312 if (!IsRelational && 9313 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9314 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9315 // This is a gcc extension compatibility comparison. 9316 // In a SFINAE context, we treat this as a hard error to maintain 9317 // conformance with the C++ standard. 9318 diagnoseFunctionPointerToVoidComparison( 9319 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9320 9321 if (isSFINAEContext()) 9322 return QualType(); 9323 9324 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9325 return ResultTy; 9326 } 9327 9328 // C++ [expr.eq]p2: 9329 // If at least one operand is a pointer [...] bring them to their 9330 // composite pointer type. 9331 // C++ [expr.rel]p2: 9332 // If both operands are pointers, [...] bring them to their composite 9333 // pointer type. 9334 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9335 (IsRelational ? 2 : 1)) { 9336 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9337 return QualType(); 9338 else 9339 return ResultTy; 9340 } 9341 } else if (LHSType->isPointerType() && 9342 RHSType->isPointerType()) { // C99 6.5.8p2 9343 // All of the following pointer-related warnings are GCC extensions, except 9344 // when handling null pointer constants. 9345 QualType LCanPointeeTy = 9346 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9347 QualType RCanPointeeTy = 9348 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9349 9350 // C99 6.5.9p2 and C99 6.5.8p2 9351 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9352 RCanPointeeTy.getUnqualifiedType())) { 9353 // Valid unless a relational comparison of function pointers 9354 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9355 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9356 << LHSType << RHSType << LHS.get()->getSourceRange() 9357 << RHS.get()->getSourceRange(); 9358 } 9359 } else if (!IsRelational && 9360 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9361 // Valid unless comparison between non-null pointer and function pointer 9362 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9363 && !LHSIsNull && !RHSIsNull) 9364 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9365 /*isError*/false); 9366 } else { 9367 // Invalid 9368 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9369 } 9370 if (LCanPointeeTy != RCanPointeeTy) { 9371 // Treat NULL constant as a special case in OpenCL. 9372 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9373 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9374 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9375 Diag(Loc, 9376 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9377 << LHSType << RHSType << 0 /* comparison */ 9378 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9379 } 9380 } 9381 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9382 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9383 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9384 : CK_BitCast; 9385 if (LHSIsNull && !RHSIsNull) 9386 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9387 else 9388 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9389 } 9390 return ResultTy; 9391 } 9392 9393 if (getLangOpts().CPlusPlus) { 9394 // C++ [expr.eq]p4: 9395 // Two operands of type std::nullptr_t or one operand of type 9396 // std::nullptr_t and the other a null pointer constant compare equal. 9397 if (!IsRelational && LHSIsNull && RHSIsNull) { 9398 if (LHSType->isNullPtrType()) { 9399 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9400 return ResultTy; 9401 } 9402 if (RHSType->isNullPtrType()) { 9403 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9404 return ResultTy; 9405 } 9406 } 9407 9408 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9409 // These aren't covered by the composite pointer type rules. 9410 if (!IsRelational && RHSType->isNullPtrType() && 9411 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9412 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9413 return ResultTy; 9414 } 9415 if (!IsRelational && LHSType->isNullPtrType() && 9416 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9417 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9418 return ResultTy; 9419 } 9420 9421 if (IsRelational && 9422 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9423 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9424 // HACK: Relational comparison of nullptr_t against a pointer type is 9425 // invalid per DR583, but we allow it within std::less<> and friends, 9426 // since otherwise common uses of it break. 9427 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9428 // friends to have std::nullptr_t overload candidates. 9429 DeclContext *DC = CurContext; 9430 if (isa<FunctionDecl>(DC)) 9431 DC = DC->getParent(); 9432 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9433 if (CTSD->isInStdNamespace() && 9434 llvm::StringSwitch<bool>(CTSD->getName()) 9435 .Cases("less", "less_equal", "greater", "greater_equal", true) 9436 .Default(false)) { 9437 if (RHSType->isNullPtrType()) 9438 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9439 else 9440 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9441 return ResultTy; 9442 } 9443 } 9444 } 9445 9446 // C++ [expr.eq]p2: 9447 // If at least one operand is a pointer to member, [...] bring them to 9448 // their composite pointer type. 9449 if (!IsRelational && 9450 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9451 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9452 return QualType(); 9453 else 9454 return ResultTy; 9455 } 9456 9457 // Handle scoped enumeration types specifically, since they don't promote 9458 // to integers. 9459 if (LHS.get()->getType()->isEnumeralType() && 9460 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9461 RHS.get()->getType())) 9462 return ResultTy; 9463 } 9464 9465 // Handle block pointer types. 9466 if (!IsRelational && LHSType->isBlockPointerType() && 9467 RHSType->isBlockPointerType()) { 9468 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9469 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9470 9471 if (!LHSIsNull && !RHSIsNull && 9472 !Context.typesAreCompatible(lpointee, rpointee)) { 9473 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9474 << LHSType << RHSType << LHS.get()->getSourceRange() 9475 << RHS.get()->getSourceRange(); 9476 } 9477 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9478 return ResultTy; 9479 } 9480 9481 // Allow block pointers to be compared with null pointer constants. 9482 if (!IsRelational 9483 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9484 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9485 if (!LHSIsNull && !RHSIsNull) { 9486 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9487 ->getPointeeType()->isVoidType()) 9488 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9489 ->getPointeeType()->isVoidType()))) 9490 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9491 << LHSType << RHSType << LHS.get()->getSourceRange() 9492 << RHS.get()->getSourceRange(); 9493 } 9494 if (LHSIsNull && !RHSIsNull) 9495 LHS = ImpCastExprToType(LHS.get(), RHSType, 9496 RHSType->isPointerType() ? CK_BitCast 9497 : CK_AnyPointerToBlockPointerCast); 9498 else 9499 RHS = ImpCastExprToType(RHS.get(), LHSType, 9500 LHSType->isPointerType() ? CK_BitCast 9501 : CK_AnyPointerToBlockPointerCast); 9502 return ResultTy; 9503 } 9504 9505 if (LHSType->isObjCObjectPointerType() || 9506 RHSType->isObjCObjectPointerType()) { 9507 const PointerType *LPT = LHSType->getAs<PointerType>(); 9508 const PointerType *RPT = RHSType->getAs<PointerType>(); 9509 if (LPT || RPT) { 9510 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9511 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9512 9513 if (!LPtrToVoid && !RPtrToVoid && 9514 !Context.typesAreCompatible(LHSType, RHSType)) { 9515 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9516 /*isError*/false); 9517 } 9518 if (LHSIsNull && !RHSIsNull) { 9519 Expr *E = LHS.get(); 9520 if (getLangOpts().ObjCAutoRefCount) 9521 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9522 LHS = ImpCastExprToType(E, RHSType, 9523 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9524 } 9525 else { 9526 Expr *E = RHS.get(); 9527 if (getLangOpts().ObjCAutoRefCount) 9528 CheckObjCARCConversion(SourceRange(), LHSType, E, 9529 CCK_ImplicitConversion, /*Diagnose=*/true, 9530 /*DiagnoseCFAudited=*/false, Opc); 9531 RHS = ImpCastExprToType(E, LHSType, 9532 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9533 } 9534 return ResultTy; 9535 } 9536 if (LHSType->isObjCObjectPointerType() && 9537 RHSType->isObjCObjectPointerType()) { 9538 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9539 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9540 /*isError*/false); 9541 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9542 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9543 9544 if (LHSIsNull && !RHSIsNull) 9545 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9546 else 9547 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9548 return ResultTy; 9549 } 9550 } 9551 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9552 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9553 unsigned DiagID = 0; 9554 bool isError = false; 9555 if (LangOpts.DebuggerSupport) { 9556 // Under a debugger, allow the comparison of pointers to integers, 9557 // since users tend to want to compare addresses. 9558 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9559 (RHSIsNull && RHSType->isIntegerType())) { 9560 if (IsRelational) { 9561 isError = getLangOpts().CPlusPlus; 9562 DiagID = 9563 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9564 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9565 } 9566 } else if (getLangOpts().CPlusPlus) { 9567 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9568 isError = true; 9569 } else if (IsRelational) 9570 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9571 else 9572 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9573 9574 if (DiagID) { 9575 Diag(Loc, DiagID) 9576 << LHSType << RHSType << LHS.get()->getSourceRange() 9577 << RHS.get()->getSourceRange(); 9578 if (isError) 9579 return QualType(); 9580 } 9581 9582 if (LHSType->isIntegerType()) 9583 LHS = ImpCastExprToType(LHS.get(), RHSType, 9584 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9585 else 9586 RHS = ImpCastExprToType(RHS.get(), LHSType, 9587 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9588 return ResultTy; 9589 } 9590 9591 // Handle block pointers. 9592 if (!IsRelational && RHSIsNull 9593 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9594 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9595 return ResultTy; 9596 } 9597 if (!IsRelational && LHSIsNull 9598 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9599 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9600 return ResultTy; 9601 } 9602 9603 return InvalidOperands(Loc, LHS, RHS); 9604 } 9605 9606 9607 // Return a signed type that is of identical size and number of elements. 9608 // For floating point vectors, return an integer type of identical size 9609 // and number of elements. 9610 QualType Sema::GetSignedVectorType(QualType V) { 9611 const VectorType *VTy = V->getAs<VectorType>(); 9612 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9613 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9614 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9615 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9616 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9617 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9618 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9619 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9620 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9621 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9622 "Unhandled vector element size in vector compare"); 9623 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9624 } 9625 9626 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9627 /// operates on extended vector types. Instead of producing an IntTy result, 9628 /// like a scalar comparison, a vector comparison produces a vector of integer 9629 /// types. 9630 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9631 SourceLocation Loc, 9632 bool IsRelational) { 9633 // Check to make sure we're operating on vectors of the same type and width, 9634 // Allowing one side to be a scalar of element type. 9635 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9636 /*AllowBothBool*/true, 9637 /*AllowBoolConversions*/getLangOpts().ZVector); 9638 if (vType.isNull()) 9639 return vType; 9640 9641 QualType LHSType = LHS.get()->getType(); 9642 9643 // If AltiVec, the comparison results in a numeric type, i.e. 9644 // bool for C++, int for C 9645 if (getLangOpts().AltiVec && 9646 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9647 return Context.getLogicalOperationType(); 9648 9649 // For non-floating point types, check for self-comparisons of the form 9650 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9651 // often indicate logic errors in the program. 9652 if (!LHSType->hasFloatingRepresentation() && 9653 ActiveTemplateInstantiations.empty()) { 9654 if (DeclRefExpr* DRL 9655 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9656 if (DeclRefExpr* DRR 9657 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9658 if (DRL->getDecl() == DRR->getDecl()) 9659 DiagRuntimeBehavior(Loc, nullptr, 9660 PDiag(diag::warn_comparison_always) 9661 << 0 // self- 9662 << 2 // "a constant" 9663 ); 9664 } 9665 9666 // Check for comparisons of floating point operands using != and ==. 9667 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9668 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9669 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9670 } 9671 9672 // Return a signed type for the vector. 9673 return GetSignedVectorType(vType); 9674 } 9675 9676 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9677 SourceLocation Loc) { 9678 // Ensure that either both operands are of the same vector type, or 9679 // one operand is of a vector type and the other is of its element type. 9680 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9681 /*AllowBothBool*/true, 9682 /*AllowBoolConversions*/false); 9683 if (vType.isNull()) 9684 return InvalidOperands(Loc, LHS, RHS); 9685 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9686 vType->hasFloatingRepresentation()) 9687 return InvalidOperands(Loc, LHS, RHS); 9688 9689 return GetSignedVectorType(LHS.get()->getType()); 9690 } 9691 9692 inline QualType Sema::CheckBitwiseOperands( 9693 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9694 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9695 9696 if (LHS.get()->getType()->isVectorType() || 9697 RHS.get()->getType()->isVectorType()) { 9698 if (LHS.get()->getType()->hasIntegerRepresentation() && 9699 RHS.get()->getType()->hasIntegerRepresentation()) 9700 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9701 /*AllowBothBool*/true, 9702 /*AllowBoolConversions*/getLangOpts().ZVector); 9703 return InvalidOperands(Loc, LHS, RHS); 9704 } 9705 9706 ExprResult LHSResult = LHS, RHSResult = RHS; 9707 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9708 IsCompAssign); 9709 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9710 return QualType(); 9711 LHS = LHSResult.get(); 9712 RHS = RHSResult.get(); 9713 9714 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9715 return compType; 9716 return InvalidOperands(Loc, LHS, RHS); 9717 } 9718 9719 // C99 6.5.[13,14] 9720 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9721 SourceLocation Loc, 9722 BinaryOperatorKind Opc) { 9723 // Check vector operands differently. 9724 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9725 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9726 9727 // Diagnose cases where the user write a logical and/or but probably meant a 9728 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9729 // is a constant. 9730 if (LHS.get()->getType()->isIntegerType() && 9731 !LHS.get()->getType()->isBooleanType() && 9732 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9733 // Don't warn in macros or template instantiations. 9734 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9735 // If the RHS can be constant folded, and if it constant folds to something 9736 // that isn't 0 or 1 (which indicate a potential logical operation that 9737 // happened to fold to true/false) then warn. 9738 // Parens on the RHS are ignored. 9739 llvm::APSInt Result; 9740 if (RHS.get()->EvaluateAsInt(Result, Context)) 9741 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9742 !RHS.get()->getExprLoc().isMacroID()) || 9743 (Result != 0 && Result != 1)) { 9744 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9745 << RHS.get()->getSourceRange() 9746 << (Opc == BO_LAnd ? "&&" : "||"); 9747 // Suggest replacing the logical operator with the bitwise version 9748 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9749 << (Opc == BO_LAnd ? "&" : "|") 9750 << FixItHint::CreateReplacement(SourceRange( 9751 Loc, getLocForEndOfToken(Loc)), 9752 Opc == BO_LAnd ? "&" : "|"); 9753 if (Opc == BO_LAnd) 9754 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9755 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9756 << FixItHint::CreateRemoval( 9757 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9758 RHS.get()->getLocEnd())); 9759 } 9760 } 9761 9762 if (!Context.getLangOpts().CPlusPlus) { 9763 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9764 // not operate on the built-in scalar and vector float types. 9765 if (Context.getLangOpts().OpenCL && 9766 Context.getLangOpts().OpenCLVersion < 120) { 9767 if (LHS.get()->getType()->isFloatingType() || 9768 RHS.get()->getType()->isFloatingType()) 9769 return InvalidOperands(Loc, LHS, RHS); 9770 } 9771 9772 LHS = UsualUnaryConversions(LHS.get()); 9773 if (LHS.isInvalid()) 9774 return QualType(); 9775 9776 RHS = UsualUnaryConversions(RHS.get()); 9777 if (RHS.isInvalid()) 9778 return QualType(); 9779 9780 if (!LHS.get()->getType()->isScalarType() || 9781 !RHS.get()->getType()->isScalarType()) 9782 return InvalidOperands(Loc, LHS, RHS); 9783 9784 return Context.IntTy; 9785 } 9786 9787 // The following is safe because we only use this method for 9788 // non-overloadable operands. 9789 9790 // C++ [expr.log.and]p1 9791 // C++ [expr.log.or]p1 9792 // The operands are both contextually converted to type bool. 9793 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9794 if (LHSRes.isInvalid()) 9795 return InvalidOperands(Loc, LHS, RHS); 9796 LHS = LHSRes; 9797 9798 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9799 if (RHSRes.isInvalid()) 9800 return InvalidOperands(Loc, LHS, RHS); 9801 RHS = RHSRes; 9802 9803 // C++ [expr.log.and]p2 9804 // C++ [expr.log.or]p2 9805 // The result is a bool. 9806 return Context.BoolTy; 9807 } 9808 9809 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9810 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9811 if (!ME) return false; 9812 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9813 ObjCMessageExpr *Base = 9814 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9815 if (!Base) return false; 9816 return Base->getMethodDecl() != nullptr; 9817 } 9818 9819 /// Is the given expression (which must be 'const') a reference to a 9820 /// variable which was originally non-const, but which has become 9821 /// 'const' due to being captured within a block? 9822 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9823 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9824 assert(E->isLValue() && E->getType().isConstQualified()); 9825 E = E->IgnoreParens(); 9826 9827 // Must be a reference to a declaration from an enclosing scope. 9828 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9829 if (!DRE) return NCCK_None; 9830 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9831 9832 // The declaration must be a variable which is not declared 'const'. 9833 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9834 if (!var) return NCCK_None; 9835 if (var->getType().isConstQualified()) return NCCK_None; 9836 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9837 9838 // Decide whether the first capture was for a block or a lambda. 9839 DeclContext *DC = S.CurContext, *Prev = nullptr; 9840 // Decide whether the first capture was for a block or a lambda. 9841 while (DC) { 9842 // For init-capture, it is possible that the variable belongs to the 9843 // template pattern of the current context. 9844 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9845 if (var->isInitCapture() && 9846 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9847 break; 9848 if (DC == var->getDeclContext()) 9849 break; 9850 Prev = DC; 9851 DC = DC->getParent(); 9852 } 9853 // Unless we have an init-capture, we've gone one step too far. 9854 if (!var->isInitCapture()) 9855 DC = Prev; 9856 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9857 } 9858 9859 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9860 Ty = Ty.getNonReferenceType(); 9861 if (IsDereference && Ty->isPointerType()) 9862 Ty = Ty->getPointeeType(); 9863 return !Ty.isConstQualified(); 9864 } 9865 9866 /// Emit the "read-only variable not assignable" error and print notes to give 9867 /// more information about why the variable is not assignable, such as pointing 9868 /// to the declaration of a const variable, showing that a method is const, or 9869 /// that the function is returning a const reference. 9870 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9871 SourceLocation Loc) { 9872 // Update err_typecheck_assign_const and note_typecheck_assign_const 9873 // when this enum is changed. 9874 enum { 9875 ConstFunction, 9876 ConstVariable, 9877 ConstMember, 9878 ConstMethod, 9879 ConstUnknown, // Keep as last element 9880 }; 9881 9882 SourceRange ExprRange = E->getSourceRange(); 9883 9884 // Only emit one error on the first const found. All other consts will emit 9885 // a note to the error. 9886 bool DiagnosticEmitted = false; 9887 9888 // Track if the current expression is the result of a derefence, and if the 9889 // next checked expression is the result of a derefence. 9890 bool IsDereference = false; 9891 bool NextIsDereference = false; 9892 9893 // Loop to process MemberExpr chains. 9894 while (true) { 9895 IsDereference = NextIsDereference; 9896 NextIsDereference = false; 9897 9898 E = E->IgnoreParenImpCasts(); 9899 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9900 NextIsDereference = ME->isArrow(); 9901 const ValueDecl *VD = ME->getMemberDecl(); 9902 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9903 // Mutable fields can be modified even if the class is const. 9904 if (Field->isMutable()) { 9905 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9906 break; 9907 } 9908 9909 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9910 if (!DiagnosticEmitted) { 9911 S.Diag(Loc, diag::err_typecheck_assign_const) 9912 << ExprRange << ConstMember << false /*static*/ << Field 9913 << Field->getType(); 9914 DiagnosticEmitted = true; 9915 } 9916 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9917 << ConstMember << false /*static*/ << Field << Field->getType() 9918 << Field->getSourceRange(); 9919 } 9920 E = ME->getBase(); 9921 continue; 9922 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9923 if (VDecl->getType().isConstQualified()) { 9924 if (!DiagnosticEmitted) { 9925 S.Diag(Loc, diag::err_typecheck_assign_const) 9926 << ExprRange << ConstMember << true /*static*/ << VDecl 9927 << VDecl->getType(); 9928 DiagnosticEmitted = true; 9929 } 9930 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9931 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9932 << VDecl->getSourceRange(); 9933 } 9934 // Static fields do not inherit constness from parents. 9935 break; 9936 } 9937 break; 9938 } // End MemberExpr 9939 break; 9940 } 9941 9942 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9943 // Function calls 9944 const FunctionDecl *FD = CE->getDirectCallee(); 9945 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9946 if (!DiagnosticEmitted) { 9947 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9948 << ConstFunction << FD; 9949 DiagnosticEmitted = true; 9950 } 9951 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9952 diag::note_typecheck_assign_const) 9953 << ConstFunction << FD << FD->getReturnType() 9954 << FD->getReturnTypeSourceRange(); 9955 } 9956 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9957 // Point to variable declaration. 9958 if (const ValueDecl *VD = DRE->getDecl()) { 9959 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9960 if (!DiagnosticEmitted) { 9961 S.Diag(Loc, diag::err_typecheck_assign_const) 9962 << ExprRange << ConstVariable << VD << VD->getType(); 9963 DiagnosticEmitted = true; 9964 } 9965 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9966 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9967 } 9968 } 9969 } else if (isa<CXXThisExpr>(E)) { 9970 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9971 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9972 if (MD->isConst()) { 9973 if (!DiagnosticEmitted) { 9974 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9975 << ConstMethod << MD; 9976 DiagnosticEmitted = true; 9977 } 9978 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9979 << ConstMethod << MD << MD->getSourceRange(); 9980 } 9981 } 9982 } 9983 } 9984 9985 if (DiagnosticEmitted) 9986 return; 9987 9988 // Can't determine a more specific message, so display the generic error. 9989 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9990 } 9991 9992 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9993 /// emit an error and return true. If so, return false. 9994 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9995 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9996 9997 S.CheckShadowingDeclModification(E, Loc); 9998 9999 SourceLocation OrigLoc = Loc; 10000 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10001 &Loc); 10002 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10003 IsLV = Expr::MLV_InvalidMessageExpression; 10004 if (IsLV == Expr::MLV_Valid) 10005 return false; 10006 10007 unsigned DiagID = 0; 10008 bool NeedType = false; 10009 switch (IsLV) { // C99 6.5.16p2 10010 case Expr::MLV_ConstQualified: 10011 // Use a specialized diagnostic when we're assigning to an object 10012 // from an enclosing function or block. 10013 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10014 if (NCCK == NCCK_Block) 10015 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10016 else 10017 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10018 break; 10019 } 10020 10021 // In ARC, use some specialized diagnostics for occasions where we 10022 // infer 'const'. These are always pseudo-strong variables. 10023 if (S.getLangOpts().ObjCAutoRefCount) { 10024 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10025 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10026 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10027 10028 // Use the normal diagnostic if it's pseudo-__strong but the 10029 // user actually wrote 'const'. 10030 if (var->isARCPseudoStrong() && 10031 (!var->getTypeSourceInfo() || 10032 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10033 // There are two pseudo-strong cases: 10034 // - self 10035 ObjCMethodDecl *method = S.getCurMethodDecl(); 10036 if (method && var == method->getSelfDecl()) 10037 DiagID = method->isClassMethod() 10038 ? diag::err_typecheck_arc_assign_self_class_method 10039 : diag::err_typecheck_arc_assign_self; 10040 10041 // - fast enumeration variables 10042 else 10043 DiagID = diag::err_typecheck_arr_assign_enumeration; 10044 10045 SourceRange Assign; 10046 if (Loc != OrigLoc) 10047 Assign = SourceRange(OrigLoc, OrigLoc); 10048 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10049 // We need to preserve the AST regardless, so migration tool 10050 // can do its job. 10051 return false; 10052 } 10053 } 10054 } 10055 10056 // If none of the special cases above are triggered, then this is a 10057 // simple const assignment. 10058 if (DiagID == 0) { 10059 DiagnoseConstAssignment(S, E, Loc); 10060 return true; 10061 } 10062 10063 break; 10064 case Expr::MLV_ConstAddrSpace: 10065 DiagnoseConstAssignment(S, E, Loc); 10066 return true; 10067 case Expr::MLV_ArrayType: 10068 case Expr::MLV_ArrayTemporary: 10069 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10070 NeedType = true; 10071 break; 10072 case Expr::MLV_NotObjectType: 10073 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10074 NeedType = true; 10075 break; 10076 case Expr::MLV_LValueCast: 10077 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10078 break; 10079 case Expr::MLV_Valid: 10080 llvm_unreachable("did not take early return for MLV_Valid"); 10081 case Expr::MLV_InvalidExpression: 10082 case Expr::MLV_MemberFunction: 10083 case Expr::MLV_ClassTemporary: 10084 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10085 break; 10086 case Expr::MLV_IncompleteType: 10087 case Expr::MLV_IncompleteVoidType: 10088 return S.RequireCompleteType(Loc, E->getType(), 10089 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10090 case Expr::MLV_DuplicateVectorComponents: 10091 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10092 break; 10093 case Expr::MLV_NoSetterProperty: 10094 llvm_unreachable("readonly properties should be processed differently"); 10095 case Expr::MLV_InvalidMessageExpression: 10096 DiagID = diag::error_readonly_message_assignment; 10097 break; 10098 case Expr::MLV_SubObjCPropertySetting: 10099 DiagID = diag::error_no_subobject_property_setting; 10100 break; 10101 } 10102 10103 SourceRange Assign; 10104 if (Loc != OrigLoc) 10105 Assign = SourceRange(OrigLoc, OrigLoc); 10106 if (NeedType) 10107 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10108 else 10109 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10110 return true; 10111 } 10112 10113 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10114 SourceLocation Loc, 10115 Sema &Sema) { 10116 // C / C++ fields 10117 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10118 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10119 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10120 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10121 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10122 } 10123 10124 // Objective-C instance variables 10125 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10126 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10127 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10128 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10129 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10130 if (RL && RR && RL->getDecl() == RR->getDecl()) 10131 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10132 } 10133 } 10134 10135 // C99 6.5.16.1 10136 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10137 SourceLocation Loc, 10138 QualType CompoundType) { 10139 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10140 10141 // Verify that LHS is a modifiable lvalue, and emit error if not. 10142 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10143 return QualType(); 10144 10145 QualType LHSType = LHSExpr->getType(); 10146 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10147 CompoundType; 10148 // OpenCL v1.2 s6.1.1.1 p2: 10149 // The half data type can only be used to declare a pointer to a buffer that 10150 // contains half values 10151 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 10152 LHSType->isHalfType()) { 10153 Diag(Loc, diag::err_opencl_half_load_store) << 1 10154 << LHSType.getUnqualifiedType(); 10155 return QualType(); 10156 } 10157 10158 AssignConvertType ConvTy; 10159 if (CompoundType.isNull()) { 10160 Expr *RHSCheck = RHS.get(); 10161 10162 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10163 10164 QualType LHSTy(LHSType); 10165 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10166 if (RHS.isInvalid()) 10167 return QualType(); 10168 // Special case of NSObject attributes on c-style pointer types. 10169 if (ConvTy == IncompatiblePointer && 10170 ((Context.isObjCNSObjectType(LHSType) && 10171 RHSType->isObjCObjectPointerType()) || 10172 (Context.isObjCNSObjectType(RHSType) && 10173 LHSType->isObjCObjectPointerType()))) 10174 ConvTy = Compatible; 10175 10176 if (ConvTy == Compatible && 10177 LHSType->isObjCObjectType()) 10178 Diag(Loc, diag::err_objc_object_assignment) 10179 << LHSType; 10180 10181 // If the RHS is a unary plus or minus, check to see if they = and + are 10182 // right next to each other. If so, the user may have typo'd "x =+ 4" 10183 // instead of "x += 4". 10184 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10185 RHSCheck = ICE->getSubExpr(); 10186 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10187 if ((UO->getOpcode() == UO_Plus || 10188 UO->getOpcode() == UO_Minus) && 10189 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10190 // Only if the two operators are exactly adjacent. 10191 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10192 // And there is a space or other character before the subexpr of the 10193 // unary +/-. We don't want to warn on "x=-1". 10194 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10195 UO->getSubExpr()->getLocStart().isFileID()) { 10196 Diag(Loc, diag::warn_not_compound_assign) 10197 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10198 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10199 } 10200 } 10201 10202 if (ConvTy == Compatible) { 10203 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10204 // Warn about retain cycles where a block captures the LHS, but 10205 // not if the LHS is a simple variable into which the block is 10206 // being stored...unless that variable can be captured by reference! 10207 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10208 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10209 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10210 checkRetainCycles(LHSExpr, RHS.get()); 10211 10212 // It is safe to assign a weak reference into a strong variable. 10213 // Although this code can still have problems: 10214 // id x = self.weakProp; 10215 // id y = self.weakProp; 10216 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10217 // paths through the function. This should be revisited if 10218 // -Wrepeated-use-of-weak is made flow-sensitive. 10219 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10220 RHS.get()->getLocStart())) 10221 getCurFunction()->markSafeWeakUse(RHS.get()); 10222 10223 } else if (getLangOpts().ObjCAutoRefCount) { 10224 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10225 } 10226 } 10227 } else { 10228 // Compound assignment "x += y" 10229 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10230 } 10231 10232 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10233 RHS.get(), AA_Assigning)) 10234 return QualType(); 10235 10236 CheckForNullPointerDereference(*this, LHSExpr); 10237 10238 // C99 6.5.16p3: The type of an assignment expression is the type of the 10239 // left operand unless the left operand has qualified type, in which case 10240 // it is the unqualified version of the type of the left operand. 10241 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10242 // is converted to the type of the assignment expression (above). 10243 // C++ 5.17p1: the type of the assignment expression is that of its left 10244 // operand. 10245 return (getLangOpts().CPlusPlus 10246 ? LHSType : LHSType.getUnqualifiedType()); 10247 } 10248 10249 // Only ignore explicit casts to void. 10250 static bool IgnoreCommaOperand(const Expr *E) { 10251 E = E->IgnoreParens(); 10252 10253 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10254 if (CE->getCastKind() == CK_ToVoid) { 10255 return true; 10256 } 10257 } 10258 10259 return false; 10260 } 10261 10262 // Look for instances where it is likely the comma operator is confused with 10263 // another operator. There is a whitelist of acceptable expressions for the 10264 // left hand side of the comma operator, otherwise emit a warning. 10265 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10266 // No warnings in macros 10267 if (Loc.isMacroID()) 10268 return; 10269 10270 // Don't warn in template instantiations. 10271 if (!ActiveTemplateInstantiations.empty()) 10272 return; 10273 10274 // Scope isn't fine-grained enough to whitelist the specific cases, so 10275 // instead, skip more than needed, then call back into here with the 10276 // CommaVisitor in SemaStmt.cpp. 10277 // The whitelisted locations are the initialization and increment portions 10278 // of a for loop. The additional checks are on the condition of 10279 // if statements, do/while loops, and for loops. 10280 const unsigned ForIncrementFlags = 10281 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10282 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10283 const unsigned ScopeFlags = getCurScope()->getFlags(); 10284 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10285 (ScopeFlags & ForInitFlags) == ForInitFlags) 10286 return; 10287 10288 // If there are multiple comma operators used together, get the RHS of the 10289 // of the comma operator as the LHS. 10290 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10291 if (BO->getOpcode() != BO_Comma) 10292 break; 10293 LHS = BO->getRHS(); 10294 } 10295 10296 // Only allow some expressions on LHS to not warn. 10297 if (IgnoreCommaOperand(LHS)) 10298 return; 10299 10300 Diag(Loc, diag::warn_comma_operator); 10301 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10302 << LHS->getSourceRange() 10303 << FixItHint::CreateInsertion(LHS->getLocStart(), 10304 LangOpts.CPlusPlus ? "static_cast<void>(" 10305 : "(void)(") 10306 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10307 ")"); 10308 } 10309 10310 // C99 6.5.17 10311 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10312 SourceLocation Loc) { 10313 LHS = S.CheckPlaceholderExpr(LHS.get()); 10314 RHS = S.CheckPlaceholderExpr(RHS.get()); 10315 if (LHS.isInvalid() || RHS.isInvalid()) 10316 return QualType(); 10317 10318 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10319 // operands, but not unary promotions. 10320 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10321 10322 // So we treat the LHS as a ignored value, and in C++ we allow the 10323 // containing site to determine what should be done with the RHS. 10324 LHS = S.IgnoredValueConversions(LHS.get()); 10325 if (LHS.isInvalid()) 10326 return QualType(); 10327 10328 S.DiagnoseUnusedExprResult(LHS.get()); 10329 10330 if (!S.getLangOpts().CPlusPlus) { 10331 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10332 if (RHS.isInvalid()) 10333 return QualType(); 10334 if (!RHS.get()->getType()->isVoidType()) 10335 S.RequireCompleteType(Loc, RHS.get()->getType(), 10336 diag::err_incomplete_type); 10337 } 10338 10339 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10340 S.DiagnoseCommaOperator(LHS.get(), Loc); 10341 10342 return RHS.get()->getType(); 10343 } 10344 10345 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10346 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10347 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10348 ExprValueKind &VK, 10349 ExprObjectKind &OK, 10350 SourceLocation OpLoc, 10351 bool IsInc, bool IsPrefix) { 10352 if (Op->isTypeDependent()) 10353 return S.Context.DependentTy; 10354 10355 QualType ResType = Op->getType(); 10356 // Atomic types can be used for increment / decrement where the non-atomic 10357 // versions can, so ignore the _Atomic() specifier for the purpose of 10358 // checking. 10359 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10360 ResType = ResAtomicType->getValueType(); 10361 10362 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10363 10364 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10365 // Decrement of bool is not allowed. 10366 if (!IsInc) { 10367 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10368 return QualType(); 10369 } 10370 // Increment of bool sets it to true, but is deprecated. 10371 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10372 : diag::warn_increment_bool) 10373 << Op->getSourceRange(); 10374 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10375 // Error on enum increments and decrements in C++ mode 10376 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10377 return QualType(); 10378 } else if (ResType->isRealType()) { 10379 // OK! 10380 } else if (ResType->isPointerType()) { 10381 // C99 6.5.2.4p2, 6.5.6p2 10382 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10383 return QualType(); 10384 } else if (ResType->isObjCObjectPointerType()) { 10385 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10386 // Otherwise, we just need a complete type. 10387 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10388 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10389 return QualType(); 10390 } else if (ResType->isAnyComplexType()) { 10391 // C99 does not support ++/-- on complex types, we allow as an extension. 10392 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10393 << ResType << Op->getSourceRange(); 10394 } else if (ResType->isPlaceholderType()) { 10395 ExprResult PR = S.CheckPlaceholderExpr(Op); 10396 if (PR.isInvalid()) return QualType(); 10397 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10398 IsInc, IsPrefix); 10399 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10400 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10401 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10402 (ResType->getAs<VectorType>()->getVectorKind() != 10403 VectorType::AltiVecBool)) { 10404 // The z vector extensions allow ++ and -- for non-bool vectors. 10405 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10406 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10407 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10408 } else { 10409 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10410 << ResType << int(IsInc) << Op->getSourceRange(); 10411 return QualType(); 10412 } 10413 // At this point, we know we have a real, complex or pointer type. 10414 // Now make sure the operand is a modifiable lvalue. 10415 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10416 return QualType(); 10417 // In C++, a prefix increment is the same type as the operand. Otherwise 10418 // (in C or with postfix), the increment is the unqualified type of the 10419 // operand. 10420 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10421 VK = VK_LValue; 10422 OK = Op->getObjectKind(); 10423 return ResType; 10424 } else { 10425 VK = VK_RValue; 10426 return ResType.getUnqualifiedType(); 10427 } 10428 } 10429 10430 10431 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10432 /// This routine allows us to typecheck complex/recursive expressions 10433 /// where the declaration is needed for type checking. We only need to 10434 /// handle cases when the expression references a function designator 10435 /// or is an lvalue. Here are some examples: 10436 /// - &(x) => x 10437 /// - &*****f => f for f a function designator. 10438 /// - &s.xx => s 10439 /// - &s.zz[1].yy -> s, if zz is an array 10440 /// - *(x + 1) -> x, if x is an array 10441 /// - &"123"[2] -> 0 10442 /// - & __real__ x -> x 10443 static ValueDecl *getPrimaryDecl(Expr *E) { 10444 switch (E->getStmtClass()) { 10445 case Stmt::DeclRefExprClass: 10446 return cast<DeclRefExpr>(E)->getDecl(); 10447 case Stmt::MemberExprClass: 10448 // If this is an arrow operator, the address is an offset from 10449 // the base's value, so the object the base refers to is 10450 // irrelevant. 10451 if (cast<MemberExpr>(E)->isArrow()) 10452 return nullptr; 10453 // Otherwise, the expression refers to a part of the base 10454 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10455 case Stmt::ArraySubscriptExprClass: { 10456 // FIXME: This code shouldn't be necessary! We should catch the implicit 10457 // promotion of register arrays earlier. 10458 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10459 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10460 if (ICE->getSubExpr()->getType()->isArrayType()) 10461 return getPrimaryDecl(ICE->getSubExpr()); 10462 } 10463 return nullptr; 10464 } 10465 case Stmt::UnaryOperatorClass: { 10466 UnaryOperator *UO = cast<UnaryOperator>(E); 10467 10468 switch(UO->getOpcode()) { 10469 case UO_Real: 10470 case UO_Imag: 10471 case UO_Extension: 10472 return getPrimaryDecl(UO->getSubExpr()); 10473 default: 10474 return nullptr; 10475 } 10476 } 10477 case Stmt::ParenExprClass: 10478 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10479 case Stmt::ImplicitCastExprClass: 10480 // If the result of an implicit cast is an l-value, we care about 10481 // the sub-expression; otherwise, the result here doesn't matter. 10482 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10483 default: 10484 return nullptr; 10485 } 10486 } 10487 10488 namespace { 10489 enum { 10490 AO_Bit_Field = 0, 10491 AO_Vector_Element = 1, 10492 AO_Property_Expansion = 2, 10493 AO_Register_Variable = 3, 10494 AO_No_Error = 4 10495 }; 10496 } 10497 /// \brief Diagnose invalid operand for address of operations. 10498 /// 10499 /// \param Type The type of operand which cannot have its address taken. 10500 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10501 Expr *E, unsigned Type) { 10502 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10503 } 10504 10505 /// CheckAddressOfOperand - The operand of & must be either a function 10506 /// designator or an lvalue designating an object. If it is an lvalue, the 10507 /// object cannot be declared with storage class register or be a bit field. 10508 /// Note: The usual conversions are *not* applied to the operand of the & 10509 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10510 /// In C++, the operand might be an overloaded function name, in which case 10511 /// we allow the '&' but retain the overloaded-function type. 10512 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10513 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10514 if (PTy->getKind() == BuiltinType::Overload) { 10515 Expr *E = OrigOp.get()->IgnoreParens(); 10516 if (!isa<OverloadExpr>(E)) { 10517 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10518 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10519 << OrigOp.get()->getSourceRange(); 10520 return QualType(); 10521 } 10522 10523 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10524 if (isa<UnresolvedMemberExpr>(Ovl)) 10525 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10526 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10527 << OrigOp.get()->getSourceRange(); 10528 return QualType(); 10529 } 10530 10531 return Context.OverloadTy; 10532 } 10533 10534 if (PTy->getKind() == BuiltinType::UnknownAny) 10535 return Context.UnknownAnyTy; 10536 10537 if (PTy->getKind() == BuiltinType::BoundMember) { 10538 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10539 << OrigOp.get()->getSourceRange(); 10540 return QualType(); 10541 } 10542 10543 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10544 if (OrigOp.isInvalid()) return QualType(); 10545 } 10546 10547 if (OrigOp.get()->isTypeDependent()) 10548 return Context.DependentTy; 10549 10550 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10551 10552 // Make sure to ignore parentheses in subsequent checks 10553 Expr *op = OrigOp.get()->IgnoreParens(); 10554 10555 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10556 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10557 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10558 return QualType(); 10559 } 10560 10561 if (getLangOpts().C99) { 10562 // Implement C99-only parts of addressof rules. 10563 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10564 if (uOp->getOpcode() == UO_Deref) 10565 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10566 // (assuming the deref expression is valid). 10567 return uOp->getSubExpr()->getType(); 10568 } 10569 // Technically, there should be a check for array subscript 10570 // expressions here, but the result of one is always an lvalue anyway. 10571 } 10572 ValueDecl *dcl = getPrimaryDecl(op); 10573 10574 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10575 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10576 op->getLocStart())) 10577 return QualType(); 10578 10579 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10580 unsigned AddressOfError = AO_No_Error; 10581 10582 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10583 bool sfinae = (bool)isSFINAEContext(); 10584 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10585 : diag::ext_typecheck_addrof_temporary) 10586 << op->getType() << op->getSourceRange(); 10587 if (sfinae) 10588 return QualType(); 10589 // Materialize the temporary as an lvalue so that we can take its address. 10590 OrigOp = op = 10591 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10592 } else if (isa<ObjCSelectorExpr>(op)) { 10593 return Context.getPointerType(op->getType()); 10594 } else if (lval == Expr::LV_MemberFunction) { 10595 // If it's an instance method, make a member pointer. 10596 // The expression must have exactly the form &A::foo. 10597 10598 // If the underlying expression isn't a decl ref, give up. 10599 if (!isa<DeclRefExpr>(op)) { 10600 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10601 << OrigOp.get()->getSourceRange(); 10602 return QualType(); 10603 } 10604 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10605 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10606 10607 // The id-expression was parenthesized. 10608 if (OrigOp.get() != DRE) { 10609 Diag(OpLoc, diag::err_parens_pointer_member_function) 10610 << OrigOp.get()->getSourceRange(); 10611 10612 // The method was named without a qualifier. 10613 } else if (!DRE->getQualifier()) { 10614 if (MD->getParent()->getName().empty()) 10615 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10616 << op->getSourceRange(); 10617 else { 10618 SmallString<32> Str; 10619 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10620 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10621 << op->getSourceRange() 10622 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10623 } 10624 } 10625 10626 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10627 if (isa<CXXDestructorDecl>(MD)) 10628 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10629 10630 QualType MPTy = Context.getMemberPointerType( 10631 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10632 // Under the MS ABI, lock down the inheritance model now. 10633 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10634 (void)isCompleteType(OpLoc, MPTy); 10635 return MPTy; 10636 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10637 // C99 6.5.3.2p1 10638 // The operand must be either an l-value or a function designator 10639 if (!op->getType()->isFunctionType()) { 10640 // Use a special diagnostic for loads from property references. 10641 if (isa<PseudoObjectExpr>(op)) { 10642 AddressOfError = AO_Property_Expansion; 10643 } else { 10644 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10645 << op->getType() << op->getSourceRange(); 10646 return QualType(); 10647 } 10648 } 10649 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10650 // The operand cannot be a bit-field 10651 AddressOfError = AO_Bit_Field; 10652 } else if (op->getObjectKind() == OK_VectorComponent) { 10653 // The operand cannot be an element of a vector 10654 AddressOfError = AO_Vector_Element; 10655 } else if (dcl) { // C99 6.5.3.2p1 10656 // We have an lvalue with a decl. Make sure the decl is not declared 10657 // with the register storage-class specifier. 10658 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10659 // in C++ it is not error to take address of a register 10660 // variable (c++03 7.1.1P3) 10661 if (vd->getStorageClass() == SC_Register && 10662 !getLangOpts().CPlusPlus) { 10663 AddressOfError = AO_Register_Variable; 10664 } 10665 } else if (isa<MSPropertyDecl>(dcl)) { 10666 AddressOfError = AO_Property_Expansion; 10667 } else if (isa<FunctionTemplateDecl>(dcl)) { 10668 return Context.OverloadTy; 10669 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10670 // Okay: we can take the address of a field. 10671 // Could be a pointer to member, though, if there is an explicit 10672 // scope qualifier for the class. 10673 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10674 DeclContext *Ctx = dcl->getDeclContext(); 10675 if (Ctx && Ctx->isRecord()) { 10676 if (dcl->getType()->isReferenceType()) { 10677 Diag(OpLoc, 10678 diag::err_cannot_form_pointer_to_member_of_reference_type) 10679 << dcl->getDeclName() << dcl->getType(); 10680 return QualType(); 10681 } 10682 10683 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10684 Ctx = Ctx->getParent(); 10685 10686 QualType MPTy = Context.getMemberPointerType( 10687 op->getType(), 10688 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10689 // Under the MS ABI, lock down the inheritance model now. 10690 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10691 (void)isCompleteType(OpLoc, MPTy); 10692 return MPTy; 10693 } 10694 } 10695 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10696 !isa<BindingDecl>(dcl)) 10697 llvm_unreachable("Unknown/unexpected decl type"); 10698 } 10699 10700 if (AddressOfError != AO_No_Error) { 10701 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10702 return QualType(); 10703 } 10704 10705 if (lval == Expr::LV_IncompleteVoidType) { 10706 // Taking the address of a void variable is technically illegal, but we 10707 // allow it in cases which are otherwise valid. 10708 // Example: "extern void x; void* y = &x;". 10709 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10710 } 10711 10712 // If the operand has type "type", the result has type "pointer to type". 10713 if (op->getType()->isObjCObjectType()) 10714 return Context.getObjCObjectPointerType(op->getType()); 10715 10716 CheckAddressOfPackedMember(op); 10717 10718 return Context.getPointerType(op->getType()); 10719 } 10720 10721 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10722 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10723 if (!DRE) 10724 return; 10725 const Decl *D = DRE->getDecl(); 10726 if (!D) 10727 return; 10728 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10729 if (!Param) 10730 return; 10731 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10732 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10733 return; 10734 if (FunctionScopeInfo *FD = S.getCurFunction()) 10735 if (!FD->ModifiedNonNullParams.count(Param)) 10736 FD->ModifiedNonNullParams.insert(Param); 10737 } 10738 10739 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10740 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10741 SourceLocation OpLoc) { 10742 if (Op->isTypeDependent()) 10743 return S.Context.DependentTy; 10744 10745 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10746 if (ConvResult.isInvalid()) 10747 return QualType(); 10748 Op = ConvResult.get(); 10749 QualType OpTy = Op->getType(); 10750 QualType Result; 10751 10752 if (isa<CXXReinterpretCastExpr>(Op)) { 10753 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10754 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10755 Op->getSourceRange()); 10756 } 10757 10758 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10759 { 10760 Result = PT->getPointeeType(); 10761 } 10762 else if (const ObjCObjectPointerType *OPT = 10763 OpTy->getAs<ObjCObjectPointerType>()) 10764 Result = OPT->getPointeeType(); 10765 else { 10766 ExprResult PR = S.CheckPlaceholderExpr(Op); 10767 if (PR.isInvalid()) return QualType(); 10768 if (PR.get() != Op) 10769 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10770 } 10771 10772 if (Result.isNull()) { 10773 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10774 << OpTy << Op->getSourceRange(); 10775 return QualType(); 10776 } 10777 10778 // Note that per both C89 and C99, indirection is always legal, even if Result 10779 // is an incomplete type or void. It would be possible to warn about 10780 // dereferencing a void pointer, but it's completely well-defined, and such a 10781 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10782 // for pointers to 'void' but is fine for any other pointer type: 10783 // 10784 // C++ [expr.unary.op]p1: 10785 // [...] the expression to which [the unary * operator] is applied shall 10786 // be a pointer to an object type, or a pointer to a function type 10787 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10788 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10789 << OpTy << Op->getSourceRange(); 10790 10791 // Dereferences are usually l-values... 10792 VK = VK_LValue; 10793 10794 // ...except that certain expressions are never l-values in C. 10795 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10796 VK = VK_RValue; 10797 10798 return Result; 10799 } 10800 10801 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10802 BinaryOperatorKind Opc; 10803 switch (Kind) { 10804 default: llvm_unreachable("Unknown binop!"); 10805 case tok::periodstar: Opc = BO_PtrMemD; break; 10806 case tok::arrowstar: Opc = BO_PtrMemI; break; 10807 case tok::star: Opc = BO_Mul; break; 10808 case tok::slash: Opc = BO_Div; break; 10809 case tok::percent: Opc = BO_Rem; break; 10810 case tok::plus: Opc = BO_Add; break; 10811 case tok::minus: Opc = BO_Sub; break; 10812 case tok::lessless: Opc = BO_Shl; break; 10813 case tok::greatergreater: Opc = BO_Shr; break; 10814 case tok::lessequal: Opc = BO_LE; break; 10815 case tok::less: Opc = BO_LT; break; 10816 case tok::greaterequal: Opc = BO_GE; break; 10817 case tok::greater: Opc = BO_GT; break; 10818 case tok::exclaimequal: Opc = BO_NE; break; 10819 case tok::equalequal: Opc = BO_EQ; break; 10820 case tok::amp: Opc = BO_And; break; 10821 case tok::caret: Opc = BO_Xor; break; 10822 case tok::pipe: Opc = BO_Or; break; 10823 case tok::ampamp: Opc = BO_LAnd; break; 10824 case tok::pipepipe: Opc = BO_LOr; break; 10825 case tok::equal: Opc = BO_Assign; break; 10826 case tok::starequal: Opc = BO_MulAssign; break; 10827 case tok::slashequal: Opc = BO_DivAssign; break; 10828 case tok::percentequal: Opc = BO_RemAssign; break; 10829 case tok::plusequal: Opc = BO_AddAssign; break; 10830 case tok::minusequal: Opc = BO_SubAssign; break; 10831 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10832 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10833 case tok::ampequal: Opc = BO_AndAssign; break; 10834 case tok::caretequal: Opc = BO_XorAssign; break; 10835 case tok::pipeequal: Opc = BO_OrAssign; break; 10836 case tok::comma: Opc = BO_Comma; break; 10837 } 10838 return Opc; 10839 } 10840 10841 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10842 tok::TokenKind Kind) { 10843 UnaryOperatorKind Opc; 10844 switch (Kind) { 10845 default: llvm_unreachable("Unknown unary op!"); 10846 case tok::plusplus: Opc = UO_PreInc; break; 10847 case tok::minusminus: Opc = UO_PreDec; break; 10848 case tok::amp: Opc = UO_AddrOf; break; 10849 case tok::star: Opc = UO_Deref; break; 10850 case tok::plus: Opc = UO_Plus; break; 10851 case tok::minus: Opc = UO_Minus; break; 10852 case tok::tilde: Opc = UO_Not; break; 10853 case tok::exclaim: Opc = UO_LNot; break; 10854 case tok::kw___real: Opc = UO_Real; break; 10855 case tok::kw___imag: Opc = UO_Imag; break; 10856 case tok::kw___extension__: Opc = UO_Extension; break; 10857 } 10858 return Opc; 10859 } 10860 10861 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10862 /// This warning is only emitted for builtin assignment operations. It is also 10863 /// suppressed in the event of macro expansions. 10864 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10865 SourceLocation OpLoc) { 10866 if (!S.ActiveTemplateInstantiations.empty()) 10867 return; 10868 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10869 return; 10870 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10871 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10872 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10873 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10874 if (!LHSDeclRef || !RHSDeclRef || 10875 LHSDeclRef->getLocation().isMacroID() || 10876 RHSDeclRef->getLocation().isMacroID()) 10877 return; 10878 const ValueDecl *LHSDecl = 10879 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10880 const ValueDecl *RHSDecl = 10881 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10882 if (LHSDecl != RHSDecl) 10883 return; 10884 if (LHSDecl->getType().isVolatileQualified()) 10885 return; 10886 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10887 if (RefTy->getPointeeType().isVolatileQualified()) 10888 return; 10889 10890 S.Diag(OpLoc, diag::warn_self_assignment) 10891 << LHSDeclRef->getType() 10892 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10893 } 10894 10895 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10896 /// is usually indicative of introspection within the Objective-C pointer. 10897 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10898 SourceLocation OpLoc) { 10899 if (!S.getLangOpts().ObjC1) 10900 return; 10901 10902 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10903 const Expr *LHS = L.get(); 10904 const Expr *RHS = R.get(); 10905 10906 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10907 ObjCPointerExpr = LHS; 10908 OtherExpr = RHS; 10909 } 10910 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10911 ObjCPointerExpr = RHS; 10912 OtherExpr = LHS; 10913 } 10914 10915 // This warning is deliberately made very specific to reduce false 10916 // positives with logic that uses '&' for hashing. This logic mainly 10917 // looks for code trying to introspect into tagged pointers, which 10918 // code should generally never do. 10919 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10920 unsigned Diag = diag::warn_objc_pointer_masking; 10921 // Determine if we are introspecting the result of performSelectorXXX. 10922 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10923 // Special case messages to -performSelector and friends, which 10924 // can return non-pointer values boxed in a pointer value. 10925 // Some clients may wish to silence warnings in this subcase. 10926 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10927 Selector S = ME->getSelector(); 10928 StringRef SelArg0 = S.getNameForSlot(0); 10929 if (SelArg0.startswith("performSelector")) 10930 Diag = diag::warn_objc_pointer_masking_performSelector; 10931 } 10932 10933 S.Diag(OpLoc, Diag) 10934 << ObjCPointerExpr->getSourceRange(); 10935 } 10936 } 10937 10938 static NamedDecl *getDeclFromExpr(Expr *E) { 10939 if (!E) 10940 return nullptr; 10941 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10942 return DRE->getDecl(); 10943 if (auto *ME = dyn_cast<MemberExpr>(E)) 10944 return ME->getMemberDecl(); 10945 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10946 return IRE->getDecl(); 10947 return nullptr; 10948 } 10949 10950 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10951 /// operator @p Opc at location @c TokLoc. This routine only supports 10952 /// built-in operations; ActOnBinOp handles overloaded operators. 10953 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10954 BinaryOperatorKind Opc, 10955 Expr *LHSExpr, Expr *RHSExpr) { 10956 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10957 // The syntax only allows initializer lists on the RHS of assignment, 10958 // so we don't need to worry about accepting invalid code for 10959 // non-assignment operators. 10960 // C++11 5.17p9: 10961 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10962 // of x = {} is x = T(). 10963 InitializationKind Kind = 10964 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10965 InitializedEntity Entity = 10966 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10967 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10968 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10969 if (Init.isInvalid()) 10970 return Init; 10971 RHSExpr = Init.get(); 10972 } 10973 10974 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10975 QualType ResultTy; // Result type of the binary operator. 10976 // The following two variables are used for compound assignment operators 10977 QualType CompLHSTy; // Type of LHS after promotions for computation 10978 QualType CompResultTy; // Type of computation result 10979 ExprValueKind VK = VK_RValue; 10980 ExprObjectKind OK = OK_Ordinary; 10981 10982 if (!getLangOpts().CPlusPlus) { 10983 // C cannot handle TypoExpr nodes on either side of a binop because it 10984 // doesn't handle dependent types properly, so make sure any TypoExprs have 10985 // been dealt with before checking the operands. 10986 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10987 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10988 if (Opc != BO_Assign) 10989 return ExprResult(E); 10990 // Avoid correcting the RHS to the same Expr as the LHS. 10991 Decl *D = getDeclFromExpr(E); 10992 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10993 }); 10994 if (!LHS.isUsable() || !RHS.isUsable()) 10995 return ExprError(); 10996 } 10997 10998 if (getLangOpts().OpenCL) { 10999 QualType LHSTy = LHSExpr->getType(); 11000 QualType RHSTy = RHSExpr->getType(); 11001 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11002 // the ATOMIC_VAR_INIT macro. 11003 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11004 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11005 if (BO_Assign == Opc) 11006 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 11007 else 11008 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11009 return ExprError(); 11010 } 11011 11012 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11013 // only with a builtin functions and therefore should be disallowed here. 11014 if (LHSTy->isImageType() || RHSTy->isImageType() || 11015 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11016 LHSTy->isPipeType() || RHSTy->isPipeType() || 11017 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11018 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11019 return ExprError(); 11020 } 11021 } 11022 11023 switch (Opc) { 11024 case BO_Assign: 11025 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11026 if (getLangOpts().CPlusPlus && 11027 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11028 VK = LHS.get()->getValueKind(); 11029 OK = LHS.get()->getObjectKind(); 11030 } 11031 if (!ResultTy.isNull()) { 11032 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11033 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11034 } 11035 RecordModifiableNonNullParam(*this, LHS.get()); 11036 break; 11037 case BO_PtrMemD: 11038 case BO_PtrMemI: 11039 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11040 Opc == BO_PtrMemI); 11041 break; 11042 case BO_Mul: 11043 case BO_Div: 11044 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11045 Opc == BO_Div); 11046 break; 11047 case BO_Rem: 11048 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11049 break; 11050 case BO_Add: 11051 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11052 break; 11053 case BO_Sub: 11054 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11055 break; 11056 case BO_Shl: 11057 case BO_Shr: 11058 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11059 break; 11060 case BO_LE: 11061 case BO_LT: 11062 case BO_GE: 11063 case BO_GT: 11064 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11065 break; 11066 case BO_EQ: 11067 case BO_NE: 11068 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11069 break; 11070 case BO_And: 11071 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11072 case BO_Xor: 11073 case BO_Or: 11074 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 11075 break; 11076 case BO_LAnd: 11077 case BO_LOr: 11078 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11079 break; 11080 case BO_MulAssign: 11081 case BO_DivAssign: 11082 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11083 Opc == BO_DivAssign); 11084 CompLHSTy = CompResultTy; 11085 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11086 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11087 break; 11088 case BO_RemAssign: 11089 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11090 CompLHSTy = CompResultTy; 11091 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11092 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11093 break; 11094 case BO_AddAssign: 11095 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11096 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11097 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11098 break; 11099 case BO_SubAssign: 11100 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11101 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11102 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11103 break; 11104 case BO_ShlAssign: 11105 case BO_ShrAssign: 11106 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11107 CompLHSTy = CompResultTy; 11108 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11109 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11110 break; 11111 case BO_AndAssign: 11112 case BO_OrAssign: // fallthrough 11113 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11114 case BO_XorAssign: 11115 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 11116 CompLHSTy = CompResultTy; 11117 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11118 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11119 break; 11120 case BO_Comma: 11121 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11122 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11123 VK = RHS.get()->getValueKind(); 11124 OK = RHS.get()->getObjectKind(); 11125 } 11126 break; 11127 } 11128 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11129 return ExprError(); 11130 11131 // Check for array bounds violations for both sides of the BinaryOperator 11132 CheckArrayAccess(LHS.get()); 11133 CheckArrayAccess(RHS.get()); 11134 11135 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11136 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11137 &Context.Idents.get("object_setClass"), 11138 SourceLocation(), LookupOrdinaryName); 11139 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11140 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11141 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11142 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11143 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11144 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11145 } 11146 else 11147 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11148 } 11149 else if (const ObjCIvarRefExpr *OIRE = 11150 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11151 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11152 11153 if (CompResultTy.isNull()) 11154 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11155 OK, OpLoc, FPFeatures.fp_contract); 11156 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11157 OK_ObjCProperty) { 11158 VK = VK_LValue; 11159 OK = LHS.get()->getObjectKind(); 11160 } 11161 return new (Context) CompoundAssignOperator( 11162 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11163 OpLoc, FPFeatures.fp_contract); 11164 } 11165 11166 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11167 /// operators are mixed in a way that suggests that the programmer forgot that 11168 /// comparison operators have higher precedence. The most typical example of 11169 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11170 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11171 SourceLocation OpLoc, Expr *LHSExpr, 11172 Expr *RHSExpr) { 11173 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11174 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11175 11176 // Check that one of the sides is a comparison operator and the other isn't. 11177 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11178 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11179 if (isLeftComp == isRightComp) 11180 return; 11181 11182 // Bitwise operations are sometimes used as eager logical ops. 11183 // Don't diagnose this. 11184 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11185 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11186 if (isLeftBitwise || isRightBitwise) 11187 return; 11188 11189 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11190 OpLoc) 11191 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11192 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11193 SourceRange ParensRange = isLeftComp ? 11194 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11195 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11196 11197 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11198 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11199 SuggestParentheses(Self, OpLoc, 11200 Self.PDiag(diag::note_precedence_silence) << OpStr, 11201 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11202 SuggestParentheses(Self, OpLoc, 11203 Self.PDiag(diag::note_precedence_bitwise_first) 11204 << BinaryOperator::getOpcodeStr(Opc), 11205 ParensRange); 11206 } 11207 11208 /// \brief It accepts a '&&' expr that is inside a '||' one. 11209 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11210 /// in parentheses. 11211 static void 11212 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11213 BinaryOperator *Bop) { 11214 assert(Bop->getOpcode() == BO_LAnd); 11215 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11216 << Bop->getSourceRange() << OpLoc; 11217 SuggestParentheses(Self, Bop->getOperatorLoc(), 11218 Self.PDiag(diag::note_precedence_silence) 11219 << Bop->getOpcodeStr(), 11220 Bop->getSourceRange()); 11221 } 11222 11223 /// \brief Returns true if the given expression can be evaluated as a constant 11224 /// 'true'. 11225 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11226 bool Res; 11227 return !E->isValueDependent() && 11228 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11229 } 11230 11231 /// \brief Returns true if the given expression can be evaluated as a constant 11232 /// 'false'. 11233 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11234 bool Res; 11235 return !E->isValueDependent() && 11236 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11237 } 11238 11239 /// \brief Look for '&&' in the left hand of a '||' expr. 11240 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11241 Expr *LHSExpr, Expr *RHSExpr) { 11242 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11243 if (Bop->getOpcode() == BO_LAnd) { 11244 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11245 if (EvaluatesAsFalse(S, RHSExpr)) 11246 return; 11247 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11248 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11249 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11250 } else if (Bop->getOpcode() == BO_LOr) { 11251 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11252 // If it's "a || b && 1 || c" we didn't warn earlier for 11253 // "a || b && 1", but warn now. 11254 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11255 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11256 } 11257 } 11258 } 11259 } 11260 11261 /// \brief Look for '&&' in the right hand of a '||' expr. 11262 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11263 Expr *LHSExpr, Expr *RHSExpr) { 11264 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11265 if (Bop->getOpcode() == BO_LAnd) { 11266 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11267 if (EvaluatesAsFalse(S, LHSExpr)) 11268 return; 11269 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11270 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11271 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11272 } 11273 } 11274 } 11275 11276 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11277 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11278 /// the '&' expression in parentheses. 11279 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11280 SourceLocation OpLoc, Expr *SubExpr) { 11281 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11282 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11283 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11284 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11285 << Bop->getSourceRange() << OpLoc; 11286 SuggestParentheses(S, Bop->getOperatorLoc(), 11287 S.PDiag(diag::note_precedence_silence) 11288 << Bop->getOpcodeStr(), 11289 Bop->getSourceRange()); 11290 } 11291 } 11292 } 11293 11294 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11295 Expr *SubExpr, StringRef Shift) { 11296 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11297 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11298 StringRef Op = Bop->getOpcodeStr(); 11299 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11300 << Bop->getSourceRange() << OpLoc << Shift << Op; 11301 SuggestParentheses(S, Bop->getOperatorLoc(), 11302 S.PDiag(diag::note_precedence_silence) << Op, 11303 Bop->getSourceRange()); 11304 } 11305 } 11306 } 11307 11308 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11309 Expr *LHSExpr, Expr *RHSExpr) { 11310 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11311 if (!OCE) 11312 return; 11313 11314 FunctionDecl *FD = OCE->getDirectCallee(); 11315 if (!FD || !FD->isOverloadedOperator()) 11316 return; 11317 11318 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11319 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11320 return; 11321 11322 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11323 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11324 << (Kind == OO_LessLess); 11325 SuggestParentheses(S, OCE->getOperatorLoc(), 11326 S.PDiag(diag::note_precedence_silence) 11327 << (Kind == OO_LessLess ? "<<" : ">>"), 11328 OCE->getSourceRange()); 11329 SuggestParentheses(S, OpLoc, 11330 S.PDiag(diag::note_evaluate_comparison_first), 11331 SourceRange(OCE->getArg(1)->getLocStart(), 11332 RHSExpr->getLocEnd())); 11333 } 11334 11335 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11336 /// precedence. 11337 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11338 SourceLocation OpLoc, Expr *LHSExpr, 11339 Expr *RHSExpr){ 11340 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11341 if (BinaryOperator::isBitwiseOp(Opc)) 11342 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11343 11344 // Diagnose "arg1 & arg2 | arg3" 11345 if ((Opc == BO_Or || Opc == BO_Xor) && 11346 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11347 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11348 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11349 } 11350 11351 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11352 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11353 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11354 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11355 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11356 } 11357 11358 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11359 || Opc == BO_Shr) { 11360 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11361 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11362 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11363 } 11364 11365 // Warn on overloaded shift operators and comparisons, such as: 11366 // cout << 5 == 4; 11367 if (BinaryOperator::isComparisonOp(Opc)) 11368 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11369 } 11370 11371 // Binary Operators. 'Tok' is the token for the operator. 11372 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11373 tok::TokenKind Kind, 11374 Expr *LHSExpr, Expr *RHSExpr) { 11375 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11376 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11377 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11378 11379 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11380 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11381 11382 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11383 } 11384 11385 /// Build an overloaded binary operator expression in the given scope. 11386 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11387 BinaryOperatorKind Opc, 11388 Expr *LHS, Expr *RHS) { 11389 // Find all of the overloaded operators visible from this 11390 // point. We perform both an operator-name lookup from the local 11391 // scope and an argument-dependent lookup based on the types of 11392 // the arguments. 11393 UnresolvedSet<16> Functions; 11394 OverloadedOperatorKind OverOp 11395 = BinaryOperator::getOverloadedOperator(Opc); 11396 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11397 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11398 RHS->getType(), Functions); 11399 11400 // Build the (potentially-overloaded, potentially-dependent) 11401 // binary operation. 11402 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11403 } 11404 11405 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11406 BinaryOperatorKind Opc, 11407 Expr *LHSExpr, Expr *RHSExpr) { 11408 // We want to end up calling one of checkPseudoObjectAssignment 11409 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11410 // both expressions are overloadable or either is type-dependent), 11411 // or CreateBuiltinBinOp (in any other case). We also want to get 11412 // any placeholder types out of the way. 11413 11414 // Handle pseudo-objects in the LHS. 11415 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11416 // Assignments with a pseudo-object l-value need special analysis. 11417 if (pty->getKind() == BuiltinType::PseudoObject && 11418 BinaryOperator::isAssignmentOp(Opc)) 11419 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11420 11421 // Don't resolve overloads if the other type is overloadable. 11422 if (pty->getKind() == BuiltinType::Overload) { 11423 // We can't actually test that if we still have a placeholder, 11424 // though. Fortunately, none of the exceptions we see in that 11425 // code below are valid when the LHS is an overload set. Note 11426 // that an overload set can be dependently-typed, but it never 11427 // instantiates to having an overloadable type. 11428 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11429 if (resolvedRHS.isInvalid()) return ExprError(); 11430 RHSExpr = resolvedRHS.get(); 11431 11432 if (RHSExpr->isTypeDependent() || 11433 RHSExpr->getType()->isOverloadableType()) 11434 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11435 } 11436 11437 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11438 if (LHS.isInvalid()) return ExprError(); 11439 LHSExpr = LHS.get(); 11440 } 11441 11442 // Handle pseudo-objects in the RHS. 11443 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11444 // An overload in the RHS can potentially be resolved by the type 11445 // being assigned to. 11446 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11447 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11448 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11449 11450 if (LHSExpr->getType()->isOverloadableType()) 11451 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11452 11453 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11454 } 11455 11456 // Don't resolve overloads if the other type is overloadable. 11457 if (pty->getKind() == BuiltinType::Overload && 11458 LHSExpr->getType()->isOverloadableType()) 11459 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11460 11461 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11462 if (!resolvedRHS.isUsable()) return ExprError(); 11463 RHSExpr = resolvedRHS.get(); 11464 } 11465 11466 if (getLangOpts().CPlusPlus) { 11467 // If either expression is type-dependent, always build an 11468 // overloaded op. 11469 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11470 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11471 11472 // Otherwise, build an overloaded op if either expression has an 11473 // overloadable type. 11474 if (LHSExpr->getType()->isOverloadableType() || 11475 RHSExpr->getType()->isOverloadableType()) 11476 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11477 } 11478 11479 // Build a built-in binary operation. 11480 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11481 } 11482 11483 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11484 UnaryOperatorKind Opc, 11485 Expr *InputExpr) { 11486 ExprResult Input = InputExpr; 11487 ExprValueKind VK = VK_RValue; 11488 ExprObjectKind OK = OK_Ordinary; 11489 QualType resultType; 11490 if (getLangOpts().OpenCL) { 11491 QualType Ty = InputExpr->getType(); 11492 // The only legal unary operation for atomics is '&'. 11493 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11494 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11495 // only with a builtin functions and therefore should be disallowed here. 11496 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11497 || Ty->isBlockPointerType())) { 11498 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11499 << InputExpr->getType() 11500 << Input.get()->getSourceRange()); 11501 } 11502 } 11503 switch (Opc) { 11504 case UO_PreInc: 11505 case UO_PreDec: 11506 case UO_PostInc: 11507 case UO_PostDec: 11508 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11509 OpLoc, 11510 Opc == UO_PreInc || 11511 Opc == UO_PostInc, 11512 Opc == UO_PreInc || 11513 Opc == UO_PreDec); 11514 break; 11515 case UO_AddrOf: 11516 resultType = CheckAddressOfOperand(Input, OpLoc); 11517 RecordModifiableNonNullParam(*this, InputExpr); 11518 break; 11519 case UO_Deref: { 11520 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11521 if (Input.isInvalid()) return ExprError(); 11522 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11523 break; 11524 } 11525 case UO_Plus: 11526 case UO_Minus: 11527 Input = UsualUnaryConversions(Input.get()); 11528 if (Input.isInvalid()) return ExprError(); 11529 resultType = Input.get()->getType(); 11530 if (resultType->isDependentType()) 11531 break; 11532 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11533 break; 11534 else if (resultType->isVectorType() && 11535 // The z vector extensions don't allow + or - with bool vectors. 11536 (!Context.getLangOpts().ZVector || 11537 resultType->getAs<VectorType>()->getVectorKind() != 11538 VectorType::AltiVecBool)) 11539 break; 11540 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11541 Opc == UO_Plus && 11542 resultType->isPointerType()) 11543 break; 11544 11545 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11546 << resultType << Input.get()->getSourceRange()); 11547 11548 case UO_Not: // bitwise complement 11549 Input = UsualUnaryConversions(Input.get()); 11550 if (Input.isInvalid()) 11551 return ExprError(); 11552 resultType = Input.get()->getType(); 11553 if (resultType->isDependentType()) 11554 break; 11555 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11556 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11557 // C99 does not support '~' for complex conjugation. 11558 Diag(OpLoc, diag::ext_integer_complement_complex) 11559 << resultType << Input.get()->getSourceRange(); 11560 else if (resultType->hasIntegerRepresentation()) 11561 break; 11562 else if (resultType->isExtVectorType()) { 11563 if (Context.getLangOpts().OpenCL) { 11564 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11565 // on vector float types. 11566 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11567 if (!T->isIntegerType()) 11568 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11569 << resultType << Input.get()->getSourceRange()); 11570 } 11571 break; 11572 } else { 11573 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11574 << resultType << Input.get()->getSourceRange()); 11575 } 11576 break; 11577 11578 case UO_LNot: // logical negation 11579 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11580 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11581 if (Input.isInvalid()) return ExprError(); 11582 resultType = Input.get()->getType(); 11583 11584 // Though we still have to promote half FP to float... 11585 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11586 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11587 resultType = Context.FloatTy; 11588 } 11589 11590 if (resultType->isDependentType()) 11591 break; 11592 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11593 // C99 6.5.3.3p1: ok, fallthrough; 11594 if (Context.getLangOpts().CPlusPlus) { 11595 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11596 // operand contextually converted to bool. 11597 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11598 ScalarTypeToBooleanCastKind(resultType)); 11599 } else if (Context.getLangOpts().OpenCL && 11600 Context.getLangOpts().OpenCLVersion < 120) { 11601 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11602 // operate on scalar float types. 11603 if (!resultType->isIntegerType()) 11604 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11605 << resultType << Input.get()->getSourceRange()); 11606 } 11607 } else if (resultType->isExtVectorType()) { 11608 if (Context.getLangOpts().OpenCL && 11609 Context.getLangOpts().OpenCLVersion < 120) { 11610 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11611 // operate on vector float types. 11612 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11613 if (!T->isIntegerType()) 11614 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11615 << resultType << Input.get()->getSourceRange()); 11616 } 11617 // Vector logical not returns the signed variant of the operand type. 11618 resultType = GetSignedVectorType(resultType); 11619 break; 11620 } else { 11621 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11622 << resultType << Input.get()->getSourceRange()); 11623 } 11624 11625 // LNot always has type int. C99 6.5.3.3p5. 11626 // In C++, it's bool. C++ 5.3.1p8 11627 resultType = Context.getLogicalOperationType(); 11628 break; 11629 case UO_Real: 11630 case UO_Imag: 11631 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11632 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11633 // complex l-values to ordinary l-values and all other values to r-values. 11634 if (Input.isInvalid()) return ExprError(); 11635 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11636 if (Input.get()->getValueKind() != VK_RValue && 11637 Input.get()->getObjectKind() == OK_Ordinary) 11638 VK = Input.get()->getValueKind(); 11639 } else if (!getLangOpts().CPlusPlus) { 11640 // In C, a volatile scalar is read by __imag. In C++, it is not. 11641 Input = DefaultLvalueConversion(Input.get()); 11642 } 11643 break; 11644 case UO_Extension: 11645 case UO_Coawait: 11646 resultType = Input.get()->getType(); 11647 VK = Input.get()->getValueKind(); 11648 OK = Input.get()->getObjectKind(); 11649 break; 11650 } 11651 if (resultType.isNull() || Input.isInvalid()) 11652 return ExprError(); 11653 11654 // Check for array bounds violations in the operand of the UnaryOperator, 11655 // except for the '*' and '&' operators that have to be handled specially 11656 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11657 // that are explicitly defined as valid by the standard). 11658 if (Opc != UO_AddrOf && Opc != UO_Deref) 11659 CheckArrayAccess(Input.get()); 11660 11661 return new (Context) 11662 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11663 } 11664 11665 /// \brief Determine whether the given expression is a qualified member 11666 /// access expression, of a form that could be turned into a pointer to member 11667 /// with the address-of operator. 11668 static bool isQualifiedMemberAccess(Expr *E) { 11669 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11670 if (!DRE->getQualifier()) 11671 return false; 11672 11673 ValueDecl *VD = DRE->getDecl(); 11674 if (!VD->isCXXClassMember()) 11675 return false; 11676 11677 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11678 return true; 11679 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11680 return Method->isInstance(); 11681 11682 return false; 11683 } 11684 11685 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11686 if (!ULE->getQualifier()) 11687 return false; 11688 11689 for (NamedDecl *D : ULE->decls()) { 11690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11691 if (Method->isInstance()) 11692 return true; 11693 } else { 11694 // Overload set does not contain methods. 11695 break; 11696 } 11697 } 11698 11699 return false; 11700 } 11701 11702 return false; 11703 } 11704 11705 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11706 UnaryOperatorKind Opc, Expr *Input) { 11707 // First things first: handle placeholders so that the 11708 // overloaded-operator check considers the right type. 11709 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11710 // Increment and decrement of pseudo-object references. 11711 if (pty->getKind() == BuiltinType::PseudoObject && 11712 UnaryOperator::isIncrementDecrementOp(Opc)) 11713 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11714 11715 // extension is always a builtin operator. 11716 if (Opc == UO_Extension) 11717 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11718 11719 // & gets special logic for several kinds of placeholder. 11720 // The builtin code knows what to do. 11721 if (Opc == UO_AddrOf && 11722 (pty->getKind() == BuiltinType::Overload || 11723 pty->getKind() == BuiltinType::UnknownAny || 11724 pty->getKind() == BuiltinType::BoundMember)) 11725 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11726 11727 // Anything else needs to be handled now. 11728 ExprResult Result = CheckPlaceholderExpr(Input); 11729 if (Result.isInvalid()) return ExprError(); 11730 Input = Result.get(); 11731 } 11732 11733 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11734 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11735 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11736 // Find all of the overloaded operators visible from this 11737 // point. We perform both an operator-name lookup from the local 11738 // scope and an argument-dependent lookup based on the types of 11739 // the arguments. 11740 UnresolvedSet<16> Functions; 11741 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11742 if (S && OverOp != OO_None) 11743 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11744 Functions); 11745 11746 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11747 } 11748 11749 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11750 } 11751 11752 // Unary Operators. 'Tok' is the token for the operator. 11753 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11754 tok::TokenKind Op, Expr *Input) { 11755 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11756 } 11757 11758 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11759 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11760 LabelDecl *TheDecl) { 11761 TheDecl->markUsed(Context); 11762 // Create the AST node. The address of a label always has type 'void*'. 11763 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11764 Context.getPointerType(Context.VoidTy)); 11765 } 11766 11767 /// Given the last statement in a statement-expression, check whether 11768 /// the result is a producing expression (like a call to an 11769 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11770 /// release out of the full-expression. Otherwise, return null. 11771 /// Cannot fail. 11772 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11773 // Should always be wrapped with one of these. 11774 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11775 if (!cleanups) return nullptr; 11776 11777 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11778 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11779 return nullptr; 11780 11781 // Splice out the cast. This shouldn't modify any interesting 11782 // features of the statement. 11783 Expr *producer = cast->getSubExpr(); 11784 assert(producer->getType() == cast->getType()); 11785 assert(producer->getValueKind() == cast->getValueKind()); 11786 cleanups->setSubExpr(producer); 11787 return cleanups; 11788 } 11789 11790 void Sema::ActOnStartStmtExpr() { 11791 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11792 } 11793 11794 void Sema::ActOnStmtExprError() { 11795 // Note that function is also called by TreeTransform when leaving a 11796 // StmtExpr scope without rebuilding anything. 11797 11798 DiscardCleanupsInEvaluationContext(); 11799 PopExpressionEvaluationContext(); 11800 } 11801 11802 ExprResult 11803 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11804 SourceLocation RPLoc) { // "({..})" 11805 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11806 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11807 11808 if (hasAnyUnrecoverableErrorsInThisFunction()) 11809 DiscardCleanupsInEvaluationContext(); 11810 assert(!Cleanup.exprNeedsCleanups() && 11811 "cleanups within StmtExpr not correctly bound!"); 11812 PopExpressionEvaluationContext(); 11813 11814 // FIXME: there are a variety of strange constraints to enforce here, for 11815 // example, it is not possible to goto into a stmt expression apparently. 11816 // More semantic analysis is needed. 11817 11818 // If there are sub-stmts in the compound stmt, take the type of the last one 11819 // as the type of the stmtexpr. 11820 QualType Ty = Context.VoidTy; 11821 bool StmtExprMayBindToTemp = false; 11822 if (!Compound->body_empty()) { 11823 Stmt *LastStmt = Compound->body_back(); 11824 LabelStmt *LastLabelStmt = nullptr; 11825 // If LastStmt is a label, skip down through into the body. 11826 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11827 LastLabelStmt = Label; 11828 LastStmt = Label->getSubStmt(); 11829 } 11830 11831 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11832 // Do function/array conversion on the last expression, but not 11833 // lvalue-to-rvalue. However, initialize an unqualified type. 11834 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11835 if (LastExpr.isInvalid()) 11836 return ExprError(); 11837 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11838 11839 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11840 // In ARC, if the final expression ends in a consume, splice 11841 // the consume out and bind it later. In the alternate case 11842 // (when dealing with a retainable type), the result 11843 // initialization will create a produce. In both cases the 11844 // result will be +1, and we'll need to balance that out with 11845 // a bind. 11846 if (Expr *rebuiltLastStmt 11847 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11848 LastExpr = rebuiltLastStmt; 11849 } else { 11850 LastExpr = PerformCopyInitialization( 11851 InitializedEntity::InitializeResult(LPLoc, 11852 Ty, 11853 false), 11854 SourceLocation(), 11855 LastExpr); 11856 } 11857 11858 if (LastExpr.isInvalid()) 11859 return ExprError(); 11860 if (LastExpr.get() != nullptr) { 11861 if (!LastLabelStmt) 11862 Compound->setLastStmt(LastExpr.get()); 11863 else 11864 LastLabelStmt->setSubStmt(LastExpr.get()); 11865 StmtExprMayBindToTemp = true; 11866 } 11867 } 11868 } 11869 } 11870 11871 // FIXME: Check that expression type is complete/non-abstract; statement 11872 // expressions are not lvalues. 11873 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11874 if (StmtExprMayBindToTemp) 11875 return MaybeBindToTemporary(ResStmtExpr); 11876 return ResStmtExpr; 11877 } 11878 11879 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11880 TypeSourceInfo *TInfo, 11881 ArrayRef<OffsetOfComponent> Components, 11882 SourceLocation RParenLoc) { 11883 QualType ArgTy = TInfo->getType(); 11884 bool Dependent = ArgTy->isDependentType(); 11885 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11886 11887 // We must have at least one component that refers to the type, and the first 11888 // one is known to be a field designator. Verify that the ArgTy represents 11889 // a struct/union/class. 11890 if (!Dependent && !ArgTy->isRecordType()) 11891 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11892 << ArgTy << TypeRange); 11893 11894 // Type must be complete per C99 7.17p3 because a declaring a variable 11895 // with an incomplete type would be ill-formed. 11896 if (!Dependent 11897 && RequireCompleteType(BuiltinLoc, ArgTy, 11898 diag::err_offsetof_incomplete_type, TypeRange)) 11899 return ExprError(); 11900 11901 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11902 // GCC extension, diagnose them. 11903 // FIXME: This diagnostic isn't actually visible because the location is in 11904 // a system header! 11905 if (Components.size() != 1) 11906 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11907 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11908 11909 bool DidWarnAboutNonPOD = false; 11910 QualType CurrentType = ArgTy; 11911 SmallVector<OffsetOfNode, 4> Comps; 11912 SmallVector<Expr*, 4> Exprs; 11913 for (const OffsetOfComponent &OC : Components) { 11914 if (OC.isBrackets) { 11915 // Offset of an array sub-field. TODO: Should we allow vector elements? 11916 if (!CurrentType->isDependentType()) { 11917 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11918 if(!AT) 11919 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11920 << CurrentType); 11921 CurrentType = AT->getElementType(); 11922 } else 11923 CurrentType = Context.DependentTy; 11924 11925 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11926 if (IdxRval.isInvalid()) 11927 return ExprError(); 11928 Expr *Idx = IdxRval.get(); 11929 11930 // The expression must be an integral expression. 11931 // FIXME: An integral constant expression? 11932 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11933 !Idx->getType()->isIntegerType()) 11934 return ExprError(Diag(Idx->getLocStart(), 11935 diag::err_typecheck_subscript_not_integer) 11936 << Idx->getSourceRange()); 11937 11938 // Record this array index. 11939 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11940 Exprs.push_back(Idx); 11941 continue; 11942 } 11943 11944 // Offset of a field. 11945 if (CurrentType->isDependentType()) { 11946 // We have the offset of a field, but we can't look into the dependent 11947 // type. Just record the identifier of the field. 11948 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11949 CurrentType = Context.DependentTy; 11950 continue; 11951 } 11952 11953 // We need to have a complete type to look into. 11954 if (RequireCompleteType(OC.LocStart, CurrentType, 11955 diag::err_offsetof_incomplete_type)) 11956 return ExprError(); 11957 11958 // Look for the designated field. 11959 const RecordType *RC = CurrentType->getAs<RecordType>(); 11960 if (!RC) 11961 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11962 << CurrentType); 11963 RecordDecl *RD = RC->getDecl(); 11964 11965 // C++ [lib.support.types]p5: 11966 // The macro offsetof accepts a restricted set of type arguments in this 11967 // International Standard. type shall be a POD structure or a POD union 11968 // (clause 9). 11969 // C++11 [support.types]p4: 11970 // If type is not a standard-layout class (Clause 9), the results are 11971 // undefined. 11972 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11973 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11974 unsigned DiagID = 11975 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11976 : diag::ext_offsetof_non_pod_type; 11977 11978 if (!IsSafe && !DidWarnAboutNonPOD && 11979 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11980 PDiag(DiagID) 11981 << SourceRange(Components[0].LocStart, OC.LocEnd) 11982 << CurrentType)) 11983 DidWarnAboutNonPOD = true; 11984 } 11985 11986 // Look for the field. 11987 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11988 LookupQualifiedName(R, RD); 11989 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11990 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11991 if (!MemberDecl) { 11992 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11993 MemberDecl = IndirectMemberDecl->getAnonField(); 11994 } 11995 11996 if (!MemberDecl) 11997 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11998 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11999 OC.LocEnd)); 12000 12001 // C99 7.17p3: 12002 // (If the specified member is a bit-field, the behavior is undefined.) 12003 // 12004 // We diagnose this as an error. 12005 if (MemberDecl->isBitField()) { 12006 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12007 << MemberDecl->getDeclName() 12008 << SourceRange(BuiltinLoc, RParenLoc); 12009 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12010 return ExprError(); 12011 } 12012 12013 RecordDecl *Parent = MemberDecl->getParent(); 12014 if (IndirectMemberDecl) 12015 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12016 12017 // If the member was found in a base class, introduce OffsetOfNodes for 12018 // the base class indirections. 12019 CXXBasePaths Paths; 12020 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12021 Paths)) { 12022 if (Paths.getDetectedVirtual()) { 12023 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12024 << MemberDecl->getDeclName() 12025 << SourceRange(BuiltinLoc, RParenLoc); 12026 return ExprError(); 12027 } 12028 12029 CXXBasePath &Path = Paths.front(); 12030 for (const CXXBasePathElement &B : Path) 12031 Comps.push_back(OffsetOfNode(B.Base)); 12032 } 12033 12034 if (IndirectMemberDecl) { 12035 for (auto *FI : IndirectMemberDecl->chain()) { 12036 assert(isa<FieldDecl>(FI)); 12037 Comps.push_back(OffsetOfNode(OC.LocStart, 12038 cast<FieldDecl>(FI), OC.LocEnd)); 12039 } 12040 } else 12041 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12042 12043 CurrentType = MemberDecl->getType().getNonReferenceType(); 12044 } 12045 12046 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12047 Comps, Exprs, RParenLoc); 12048 } 12049 12050 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12051 SourceLocation BuiltinLoc, 12052 SourceLocation TypeLoc, 12053 ParsedType ParsedArgTy, 12054 ArrayRef<OffsetOfComponent> Components, 12055 SourceLocation RParenLoc) { 12056 12057 TypeSourceInfo *ArgTInfo; 12058 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12059 if (ArgTy.isNull()) 12060 return ExprError(); 12061 12062 if (!ArgTInfo) 12063 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12064 12065 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12066 } 12067 12068 12069 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12070 Expr *CondExpr, 12071 Expr *LHSExpr, Expr *RHSExpr, 12072 SourceLocation RPLoc) { 12073 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12074 12075 ExprValueKind VK = VK_RValue; 12076 ExprObjectKind OK = OK_Ordinary; 12077 QualType resType; 12078 bool ValueDependent = false; 12079 bool CondIsTrue = false; 12080 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12081 resType = Context.DependentTy; 12082 ValueDependent = true; 12083 } else { 12084 // The conditional expression is required to be a constant expression. 12085 llvm::APSInt condEval(32); 12086 ExprResult CondICE 12087 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12088 diag::err_typecheck_choose_expr_requires_constant, false); 12089 if (CondICE.isInvalid()) 12090 return ExprError(); 12091 CondExpr = CondICE.get(); 12092 CondIsTrue = condEval.getZExtValue(); 12093 12094 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12095 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12096 12097 resType = ActiveExpr->getType(); 12098 ValueDependent = ActiveExpr->isValueDependent(); 12099 VK = ActiveExpr->getValueKind(); 12100 OK = ActiveExpr->getObjectKind(); 12101 } 12102 12103 return new (Context) 12104 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12105 CondIsTrue, resType->isDependentType(), ValueDependent); 12106 } 12107 12108 //===----------------------------------------------------------------------===// 12109 // Clang Extensions. 12110 //===----------------------------------------------------------------------===// 12111 12112 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12113 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12114 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12115 12116 if (LangOpts.CPlusPlus) { 12117 Decl *ManglingContextDecl; 12118 if (MangleNumberingContext *MCtx = 12119 getCurrentMangleNumberContext(Block->getDeclContext(), 12120 ManglingContextDecl)) { 12121 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12122 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12123 } 12124 } 12125 12126 PushBlockScope(CurScope, Block); 12127 CurContext->addDecl(Block); 12128 if (CurScope) 12129 PushDeclContext(CurScope, Block); 12130 else 12131 CurContext = Block; 12132 12133 getCurBlock()->HasImplicitReturnType = true; 12134 12135 // Enter a new evaluation context to insulate the block from any 12136 // cleanups from the enclosing full-expression. 12137 PushExpressionEvaluationContext(PotentiallyEvaluated); 12138 } 12139 12140 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12141 Scope *CurScope) { 12142 assert(ParamInfo.getIdentifier() == nullptr && 12143 "block-id should have no identifier!"); 12144 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12145 BlockScopeInfo *CurBlock = getCurBlock(); 12146 12147 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12148 QualType T = Sig->getType(); 12149 12150 // FIXME: We should allow unexpanded parameter packs here, but that would, 12151 // in turn, make the block expression contain unexpanded parameter packs. 12152 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12153 // Drop the parameters. 12154 FunctionProtoType::ExtProtoInfo EPI; 12155 EPI.HasTrailingReturn = false; 12156 EPI.TypeQuals |= DeclSpec::TQ_const; 12157 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12158 Sig = Context.getTrivialTypeSourceInfo(T); 12159 } 12160 12161 // GetTypeForDeclarator always produces a function type for a block 12162 // literal signature. Furthermore, it is always a FunctionProtoType 12163 // unless the function was written with a typedef. 12164 assert(T->isFunctionType() && 12165 "GetTypeForDeclarator made a non-function block signature"); 12166 12167 // Look for an explicit signature in that function type. 12168 FunctionProtoTypeLoc ExplicitSignature; 12169 12170 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12171 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12172 12173 // Check whether that explicit signature was synthesized by 12174 // GetTypeForDeclarator. If so, don't save that as part of the 12175 // written signature. 12176 if (ExplicitSignature.getLocalRangeBegin() == 12177 ExplicitSignature.getLocalRangeEnd()) { 12178 // This would be much cheaper if we stored TypeLocs instead of 12179 // TypeSourceInfos. 12180 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12181 unsigned Size = Result.getFullDataSize(); 12182 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12183 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12184 12185 ExplicitSignature = FunctionProtoTypeLoc(); 12186 } 12187 } 12188 12189 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12190 CurBlock->FunctionType = T; 12191 12192 const FunctionType *Fn = T->getAs<FunctionType>(); 12193 QualType RetTy = Fn->getReturnType(); 12194 bool isVariadic = 12195 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12196 12197 CurBlock->TheDecl->setIsVariadic(isVariadic); 12198 12199 // Context.DependentTy is used as a placeholder for a missing block 12200 // return type. TODO: what should we do with declarators like: 12201 // ^ * { ... } 12202 // If the answer is "apply template argument deduction".... 12203 if (RetTy != Context.DependentTy) { 12204 CurBlock->ReturnType = RetTy; 12205 CurBlock->TheDecl->setBlockMissingReturnType(false); 12206 CurBlock->HasImplicitReturnType = false; 12207 } 12208 12209 // Push block parameters from the declarator if we had them. 12210 SmallVector<ParmVarDecl*, 8> Params; 12211 if (ExplicitSignature) { 12212 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12213 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12214 if (Param->getIdentifier() == nullptr && 12215 !Param->isImplicit() && 12216 !Param->isInvalidDecl() && 12217 !getLangOpts().CPlusPlus) 12218 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12219 Params.push_back(Param); 12220 } 12221 12222 // Fake up parameter variables if we have a typedef, like 12223 // ^ fntype { ... } 12224 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12225 for (const auto &I : Fn->param_types()) { 12226 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12227 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12228 Params.push_back(Param); 12229 } 12230 } 12231 12232 // Set the parameters on the block decl. 12233 if (!Params.empty()) { 12234 CurBlock->TheDecl->setParams(Params); 12235 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12236 /*CheckParameterNames=*/false); 12237 } 12238 12239 // Finally we can process decl attributes. 12240 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12241 12242 // Put the parameter variables in scope. 12243 for (auto AI : CurBlock->TheDecl->parameters()) { 12244 AI->setOwningFunction(CurBlock->TheDecl); 12245 12246 // If this has an identifier, add it to the scope stack. 12247 if (AI->getIdentifier()) { 12248 CheckShadow(CurBlock->TheScope, AI); 12249 12250 PushOnScopeChains(AI, CurBlock->TheScope); 12251 } 12252 } 12253 } 12254 12255 /// ActOnBlockError - If there is an error parsing a block, this callback 12256 /// is invoked to pop the information about the block from the action impl. 12257 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12258 // Leave the expression-evaluation context. 12259 DiscardCleanupsInEvaluationContext(); 12260 PopExpressionEvaluationContext(); 12261 12262 // Pop off CurBlock, handle nested blocks. 12263 PopDeclContext(); 12264 PopFunctionScopeInfo(); 12265 } 12266 12267 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12268 /// literal was successfully completed. ^(int x){...} 12269 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12270 Stmt *Body, Scope *CurScope) { 12271 // If blocks are disabled, emit an error. 12272 if (!LangOpts.Blocks) 12273 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12274 12275 // Leave the expression-evaluation context. 12276 if (hasAnyUnrecoverableErrorsInThisFunction()) 12277 DiscardCleanupsInEvaluationContext(); 12278 assert(!Cleanup.exprNeedsCleanups() && 12279 "cleanups within block not correctly bound!"); 12280 PopExpressionEvaluationContext(); 12281 12282 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12283 12284 if (BSI->HasImplicitReturnType) 12285 deduceClosureReturnType(*BSI); 12286 12287 PopDeclContext(); 12288 12289 QualType RetTy = Context.VoidTy; 12290 if (!BSI->ReturnType.isNull()) 12291 RetTy = BSI->ReturnType; 12292 12293 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12294 QualType BlockTy; 12295 12296 // Set the captured variables on the block. 12297 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12298 SmallVector<BlockDecl::Capture, 4> Captures; 12299 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12300 if (Cap.isThisCapture()) 12301 continue; 12302 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12303 Cap.isNested(), Cap.getInitExpr()); 12304 Captures.push_back(NewCap); 12305 } 12306 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12307 12308 // If the user wrote a function type in some form, try to use that. 12309 if (!BSI->FunctionType.isNull()) { 12310 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12311 12312 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12313 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12314 12315 // Turn protoless block types into nullary block types. 12316 if (isa<FunctionNoProtoType>(FTy)) { 12317 FunctionProtoType::ExtProtoInfo EPI; 12318 EPI.ExtInfo = Ext; 12319 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12320 12321 // Otherwise, if we don't need to change anything about the function type, 12322 // preserve its sugar structure. 12323 } else if (FTy->getReturnType() == RetTy && 12324 (!NoReturn || FTy->getNoReturnAttr())) { 12325 BlockTy = BSI->FunctionType; 12326 12327 // Otherwise, make the minimal modifications to the function type. 12328 } else { 12329 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12330 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12331 EPI.TypeQuals = 0; // FIXME: silently? 12332 EPI.ExtInfo = Ext; 12333 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12334 } 12335 12336 // If we don't have a function type, just build one from nothing. 12337 } else { 12338 FunctionProtoType::ExtProtoInfo EPI; 12339 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12340 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12341 } 12342 12343 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12344 BlockTy = Context.getBlockPointerType(BlockTy); 12345 12346 // If needed, diagnose invalid gotos and switches in the block. 12347 if (getCurFunction()->NeedsScopeChecking() && 12348 !PP.isCodeCompletionEnabled()) 12349 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12350 12351 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12352 12353 // Try to apply the named return value optimization. We have to check again 12354 // if we can do this, though, because blocks keep return statements around 12355 // to deduce an implicit return type. 12356 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12357 !BSI->TheDecl->isDependentContext()) 12358 computeNRVO(Body, BSI); 12359 12360 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12361 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12362 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12363 12364 // If the block isn't obviously global, i.e. it captures anything at 12365 // all, then we need to do a few things in the surrounding context: 12366 if (Result->getBlockDecl()->hasCaptures()) { 12367 // First, this expression has a new cleanup object. 12368 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12369 Cleanup.setExprNeedsCleanups(true); 12370 12371 // It also gets a branch-protected scope if any of the captured 12372 // variables needs destruction. 12373 for (const auto &CI : Result->getBlockDecl()->captures()) { 12374 const VarDecl *var = CI.getVariable(); 12375 if (var->getType().isDestructedType() != QualType::DK_none) { 12376 getCurFunction()->setHasBranchProtectedScope(); 12377 break; 12378 } 12379 } 12380 } 12381 12382 return Result; 12383 } 12384 12385 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12386 SourceLocation RPLoc) { 12387 TypeSourceInfo *TInfo; 12388 GetTypeFromParser(Ty, &TInfo); 12389 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12390 } 12391 12392 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12393 Expr *E, TypeSourceInfo *TInfo, 12394 SourceLocation RPLoc) { 12395 Expr *OrigExpr = E; 12396 bool IsMS = false; 12397 12398 // CUDA device code does not support varargs. 12399 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12400 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12401 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12402 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12403 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12404 } 12405 } 12406 12407 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12408 // as Microsoft ABI on an actual Microsoft platform, where 12409 // __builtin_ms_va_list and __builtin_va_list are the same.) 12410 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12411 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12412 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12413 if (Context.hasSameType(MSVaListType, E->getType())) { 12414 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12415 return ExprError(); 12416 IsMS = true; 12417 } 12418 } 12419 12420 // Get the va_list type 12421 QualType VaListType = Context.getBuiltinVaListType(); 12422 if (!IsMS) { 12423 if (VaListType->isArrayType()) { 12424 // Deal with implicit array decay; for example, on x86-64, 12425 // va_list is an array, but it's supposed to decay to 12426 // a pointer for va_arg. 12427 VaListType = Context.getArrayDecayedType(VaListType); 12428 // Make sure the input expression also decays appropriately. 12429 ExprResult Result = UsualUnaryConversions(E); 12430 if (Result.isInvalid()) 12431 return ExprError(); 12432 E = Result.get(); 12433 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12434 // If va_list is a record type and we are compiling in C++ mode, 12435 // check the argument using reference binding. 12436 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12437 Context, Context.getLValueReferenceType(VaListType), false); 12438 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12439 if (Init.isInvalid()) 12440 return ExprError(); 12441 E = Init.getAs<Expr>(); 12442 } else { 12443 // Otherwise, the va_list argument must be an l-value because 12444 // it is modified by va_arg. 12445 if (!E->isTypeDependent() && 12446 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12447 return ExprError(); 12448 } 12449 } 12450 12451 if (!IsMS && !E->isTypeDependent() && 12452 !Context.hasSameType(VaListType, E->getType())) 12453 return ExprError(Diag(E->getLocStart(), 12454 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12455 << OrigExpr->getType() << E->getSourceRange()); 12456 12457 if (!TInfo->getType()->isDependentType()) { 12458 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12459 diag::err_second_parameter_to_va_arg_incomplete, 12460 TInfo->getTypeLoc())) 12461 return ExprError(); 12462 12463 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12464 TInfo->getType(), 12465 diag::err_second_parameter_to_va_arg_abstract, 12466 TInfo->getTypeLoc())) 12467 return ExprError(); 12468 12469 if (!TInfo->getType().isPODType(Context)) { 12470 Diag(TInfo->getTypeLoc().getBeginLoc(), 12471 TInfo->getType()->isObjCLifetimeType() 12472 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12473 : diag::warn_second_parameter_to_va_arg_not_pod) 12474 << TInfo->getType() 12475 << TInfo->getTypeLoc().getSourceRange(); 12476 } 12477 12478 // Check for va_arg where arguments of the given type will be promoted 12479 // (i.e. this va_arg is guaranteed to have undefined behavior). 12480 QualType PromoteType; 12481 if (TInfo->getType()->isPromotableIntegerType()) { 12482 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12483 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12484 PromoteType = QualType(); 12485 } 12486 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12487 PromoteType = Context.DoubleTy; 12488 if (!PromoteType.isNull()) 12489 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12490 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12491 << TInfo->getType() 12492 << PromoteType 12493 << TInfo->getTypeLoc().getSourceRange()); 12494 } 12495 12496 QualType T = TInfo->getType().getNonLValueExprType(Context); 12497 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12498 } 12499 12500 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12501 // The type of __null will be int or long, depending on the size of 12502 // pointers on the target. 12503 QualType Ty; 12504 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12505 if (pw == Context.getTargetInfo().getIntWidth()) 12506 Ty = Context.IntTy; 12507 else if (pw == Context.getTargetInfo().getLongWidth()) 12508 Ty = Context.LongTy; 12509 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12510 Ty = Context.LongLongTy; 12511 else { 12512 llvm_unreachable("I don't know size of pointer!"); 12513 } 12514 12515 return new (Context) GNUNullExpr(Ty, TokenLoc); 12516 } 12517 12518 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12519 bool Diagnose) { 12520 if (!getLangOpts().ObjC1) 12521 return false; 12522 12523 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12524 if (!PT) 12525 return false; 12526 12527 if (!PT->isObjCIdType()) { 12528 // Check if the destination is the 'NSString' interface. 12529 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12530 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12531 return false; 12532 } 12533 12534 // Ignore any parens, implicit casts (should only be 12535 // array-to-pointer decays), and not-so-opaque values. The last is 12536 // important for making this trigger for property assignments. 12537 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12538 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12539 if (OV->getSourceExpr()) 12540 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12541 12542 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12543 if (!SL || !SL->isAscii()) 12544 return false; 12545 if (Diagnose) { 12546 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12547 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12548 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12549 } 12550 return true; 12551 } 12552 12553 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12554 const Expr *SrcExpr) { 12555 if (!DstType->isFunctionPointerType() || 12556 !SrcExpr->getType()->isFunctionType()) 12557 return false; 12558 12559 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12560 if (!DRE) 12561 return false; 12562 12563 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12564 if (!FD) 12565 return false; 12566 12567 return !S.checkAddressOfFunctionIsAvailable(FD, 12568 /*Complain=*/true, 12569 SrcExpr->getLocStart()); 12570 } 12571 12572 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12573 SourceLocation Loc, 12574 QualType DstType, QualType SrcType, 12575 Expr *SrcExpr, AssignmentAction Action, 12576 bool *Complained) { 12577 if (Complained) 12578 *Complained = false; 12579 12580 // Decode the result (notice that AST's are still created for extensions). 12581 bool CheckInferredResultType = false; 12582 bool isInvalid = false; 12583 unsigned DiagKind = 0; 12584 FixItHint Hint; 12585 ConversionFixItGenerator ConvHints; 12586 bool MayHaveConvFixit = false; 12587 bool MayHaveFunctionDiff = false; 12588 const ObjCInterfaceDecl *IFace = nullptr; 12589 const ObjCProtocolDecl *PDecl = nullptr; 12590 12591 switch (ConvTy) { 12592 case Compatible: 12593 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12594 return false; 12595 12596 case PointerToInt: 12597 DiagKind = diag::ext_typecheck_convert_pointer_int; 12598 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12599 MayHaveConvFixit = true; 12600 break; 12601 case IntToPointer: 12602 DiagKind = diag::ext_typecheck_convert_int_pointer; 12603 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12604 MayHaveConvFixit = true; 12605 break; 12606 case IncompatiblePointer: 12607 if (Action == AA_Passing_CFAudited) 12608 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12609 else if (SrcType->isFunctionPointerType() && 12610 DstType->isFunctionPointerType()) 12611 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12612 else 12613 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12614 12615 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12616 SrcType->isObjCObjectPointerType(); 12617 if (Hint.isNull() && !CheckInferredResultType) { 12618 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12619 } 12620 else if (CheckInferredResultType) { 12621 SrcType = SrcType.getUnqualifiedType(); 12622 DstType = DstType.getUnqualifiedType(); 12623 } 12624 MayHaveConvFixit = true; 12625 break; 12626 case IncompatiblePointerSign: 12627 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12628 break; 12629 case FunctionVoidPointer: 12630 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12631 break; 12632 case IncompatiblePointerDiscardsQualifiers: { 12633 // Perform array-to-pointer decay if necessary. 12634 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12635 12636 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12637 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12638 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12639 DiagKind = diag::err_typecheck_incompatible_address_space; 12640 break; 12641 12642 12643 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12644 DiagKind = diag::err_typecheck_incompatible_ownership; 12645 break; 12646 } 12647 12648 llvm_unreachable("unknown error case for discarding qualifiers!"); 12649 // fallthrough 12650 } 12651 case CompatiblePointerDiscardsQualifiers: 12652 // If the qualifiers lost were because we were applying the 12653 // (deprecated) C++ conversion from a string literal to a char* 12654 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12655 // Ideally, this check would be performed in 12656 // checkPointerTypesForAssignment. However, that would require a 12657 // bit of refactoring (so that the second argument is an 12658 // expression, rather than a type), which should be done as part 12659 // of a larger effort to fix checkPointerTypesForAssignment for 12660 // C++ semantics. 12661 if (getLangOpts().CPlusPlus && 12662 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12663 return false; 12664 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12665 break; 12666 case IncompatibleNestedPointerQualifiers: 12667 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12668 break; 12669 case IntToBlockPointer: 12670 DiagKind = diag::err_int_to_block_pointer; 12671 break; 12672 case IncompatibleBlockPointer: 12673 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12674 break; 12675 case IncompatibleObjCQualifiedId: { 12676 if (SrcType->isObjCQualifiedIdType()) { 12677 const ObjCObjectPointerType *srcOPT = 12678 SrcType->getAs<ObjCObjectPointerType>(); 12679 for (auto *srcProto : srcOPT->quals()) { 12680 PDecl = srcProto; 12681 break; 12682 } 12683 if (const ObjCInterfaceType *IFaceT = 12684 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12685 IFace = IFaceT->getDecl(); 12686 } 12687 else if (DstType->isObjCQualifiedIdType()) { 12688 const ObjCObjectPointerType *dstOPT = 12689 DstType->getAs<ObjCObjectPointerType>(); 12690 for (auto *dstProto : dstOPT->quals()) { 12691 PDecl = dstProto; 12692 break; 12693 } 12694 if (const ObjCInterfaceType *IFaceT = 12695 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12696 IFace = IFaceT->getDecl(); 12697 } 12698 DiagKind = diag::warn_incompatible_qualified_id; 12699 break; 12700 } 12701 case IncompatibleVectors: 12702 DiagKind = diag::warn_incompatible_vectors; 12703 break; 12704 case IncompatibleObjCWeakRef: 12705 DiagKind = diag::err_arc_weak_unavailable_assign; 12706 break; 12707 case Incompatible: 12708 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12709 if (Complained) 12710 *Complained = true; 12711 return true; 12712 } 12713 12714 DiagKind = diag::err_typecheck_convert_incompatible; 12715 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12716 MayHaveConvFixit = true; 12717 isInvalid = true; 12718 MayHaveFunctionDiff = true; 12719 break; 12720 } 12721 12722 QualType FirstType, SecondType; 12723 switch (Action) { 12724 case AA_Assigning: 12725 case AA_Initializing: 12726 // The destination type comes first. 12727 FirstType = DstType; 12728 SecondType = SrcType; 12729 break; 12730 12731 case AA_Returning: 12732 case AA_Passing: 12733 case AA_Passing_CFAudited: 12734 case AA_Converting: 12735 case AA_Sending: 12736 case AA_Casting: 12737 // The source type comes first. 12738 FirstType = SrcType; 12739 SecondType = DstType; 12740 break; 12741 } 12742 12743 PartialDiagnostic FDiag = PDiag(DiagKind); 12744 if (Action == AA_Passing_CFAudited) 12745 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12746 else 12747 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12748 12749 // If we can fix the conversion, suggest the FixIts. 12750 assert(ConvHints.isNull() || Hint.isNull()); 12751 if (!ConvHints.isNull()) { 12752 for (FixItHint &H : ConvHints.Hints) 12753 FDiag << H; 12754 } else { 12755 FDiag << Hint; 12756 } 12757 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12758 12759 if (MayHaveFunctionDiff) 12760 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12761 12762 Diag(Loc, FDiag); 12763 if (DiagKind == diag::warn_incompatible_qualified_id && 12764 PDecl && IFace && !IFace->hasDefinition()) 12765 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12766 << IFace->getName() << PDecl->getName(); 12767 12768 if (SecondType == Context.OverloadTy) 12769 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12770 FirstType, /*TakingAddress=*/true); 12771 12772 if (CheckInferredResultType) 12773 EmitRelatedResultTypeNote(SrcExpr); 12774 12775 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12776 EmitRelatedResultTypeNoteForReturn(DstType); 12777 12778 if (Complained) 12779 *Complained = true; 12780 return isInvalid; 12781 } 12782 12783 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12784 llvm::APSInt *Result) { 12785 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12786 public: 12787 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12788 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12789 } 12790 } Diagnoser; 12791 12792 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12793 } 12794 12795 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12796 llvm::APSInt *Result, 12797 unsigned DiagID, 12798 bool AllowFold) { 12799 class IDDiagnoser : public VerifyICEDiagnoser { 12800 unsigned DiagID; 12801 12802 public: 12803 IDDiagnoser(unsigned DiagID) 12804 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12805 12806 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12807 S.Diag(Loc, DiagID) << SR; 12808 } 12809 } Diagnoser(DiagID); 12810 12811 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12812 } 12813 12814 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12815 SourceRange SR) { 12816 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12817 } 12818 12819 ExprResult 12820 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12821 VerifyICEDiagnoser &Diagnoser, 12822 bool AllowFold) { 12823 SourceLocation DiagLoc = E->getLocStart(); 12824 12825 if (getLangOpts().CPlusPlus11) { 12826 // C++11 [expr.const]p5: 12827 // If an expression of literal class type is used in a context where an 12828 // integral constant expression is required, then that class type shall 12829 // have a single non-explicit conversion function to an integral or 12830 // unscoped enumeration type 12831 ExprResult Converted; 12832 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12833 public: 12834 CXX11ConvertDiagnoser(bool Silent) 12835 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12836 Silent, true) {} 12837 12838 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12839 QualType T) override { 12840 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12841 } 12842 12843 SemaDiagnosticBuilder diagnoseIncomplete( 12844 Sema &S, SourceLocation Loc, QualType T) override { 12845 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12846 } 12847 12848 SemaDiagnosticBuilder diagnoseExplicitConv( 12849 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12850 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12851 } 12852 12853 SemaDiagnosticBuilder noteExplicitConv( 12854 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12855 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12856 << ConvTy->isEnumeralType() << ConvTy; 12857 } 12858 12859 SemaDiagnosticBuilder diagnoseAmbiguous( 12860 Sema &S, SourceLocation Loc, QualType T) override { 12861 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12862 } 12863 12864 SemaDiagnosticBuilder noteAmbiguous( 12865 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12866 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12867 << ConvTy->isEnumeralType() << ConvTy; 12868 } 12869 12870 SemaDiagnosticBuilder diagnoseConversion( 12871 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12872 llvm_unreachable("conversion functions are permitted"); 12873 } 12874 } ConvertDiagnoser(Diagnoser.Suppress); 12875 12876 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12877 ConvertDiagnoser); 12878 if (Converted.isInvalid()) 12879 return Converted; 12880 E = Converted.get(); 12881 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12882 return ExprError(); 12883 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12884 // An ICE must be of integral or unscoped enumeration type. 12885 if (!Diagnoser.Suppress) 12886 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12887 return ExprError(); 12888 } 12889 12890 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12891 // in the non-ICE case. 12892 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12893 if (Result) 12894 *Result = E->EvaluateKnownConstInt(Context); 12895 return E; 12896 } 12897 12898 Expr::EvalResult EvalResult; 12899 SmallVector<PartialDiagnosticAt, 8> Notes; 12900 EvalResult.Diag = &Notes; 12901 12902 // Try to evaluate the expression, and produce diagnostics explaining why it's 12903 // not a constant expression as a side-effect. 12904 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12905 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12906 12907 // In C++11, we can rely on diagnostics being produced for any expression 12908 // which is not a constant expression. If no diagnostics were produced, then 12909 // this is a constant expression. 12910 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12911 if (Result) 12912 *Result = EvalResult.Val.getInt(); 12913 return E; 12914 } 12915 12916 // If our only note is the usual "invalid subexpression" note, just point 12917 // the caret at its location rather than producing an essentially 12918 // redundant note. 12919 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12920 diag::note_invalid_subexpr_in_const_expr) { 12921 DiagLoc = Notes[0].first; 12922 Notes.clear(); 12923 } 12924 12925 if (!Folded || !AllowFold) { 12926 if (!Diagnoser.Suppress) { 12927 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12928 for (const PartialDiagnosticAt &Note : Notes) 12929 Diag(Note.first, Note.second); 12930 } 12931 12932 return ExprError(); 12933 } 12934 12935 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12936 for (const PartialDiagnosticAt &Note : Notes) 12937 Diag(Note.first, Note.second); 12938 12939 if (Result) 12940 *Result = EvalResult.Val.getInt(); 12941 return E; 12942 } 12943 12944 namespace { 12945 // Handle the case where we conclude a expression which we speculatively 12946 // considered to be unevaluated is actually evaluated. 12947 class TransformToPE : public TreeTransform<TransformToPE> { 12948 typedef TreeTransform<TransformToPE> BaseTransform; 12949 12950 public: 12951 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12952 12953 // Make sure we redo semantic analysis 12954 bool AlwaysRebuild() { return true; } 12955 12956 // Make sure we handle LabelStmts correctly. 12957 // FIXME: This does the right thing, but maybe we need a more general 12958 // fix to TreeTransform? 12959 StmtResult TransformLabelStmt(LabelStmt *S) { 12960 S->getDecl()->setStmt(nullptr); 12961 return BaseTransform::TransformLabelStmt(S); 12962 } 12963 12964 // We need to special-case DeclRefExprs referring to FieldDecls which 12965 // are not part of a member pointer formation; normal TreeTransforming 12966 // doesn't catch this case because of the way we represent them in the AST. 12967 // FIXME: This is a bit ugly; is it really the best way to handle this 12968 // case? 12969 // 12970 // Error on DeclRefExprs referring to FieldDecls. 12971 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12972 if (isa<FieldDecl>(E->getDecl()) && 12973 !SemaRef.isUnevaluatedContext()) 12974 return SemaRef.Diag(E->getLocation(), 12975 diag::err_invalid_non_static_member_use) 12976 << E->getDecl() << E->getSourceRange(); 12977 12978 return BaseTransform::TransformDeclRefExpr(E); 12979 } 12980 12981 // Exception: filter out member pointer formation 12982 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12983 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12984 return E; 12985 12986 return BaseTransform::TransformUnaryOperator(E); 12987 } 12988 12989 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12990 // Lambdas never need to be transformed. 12991 return E; 12992 } 12993 }; 12994 } 12995 12996 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12997 assert(isUnevaluatedContext() && 12998 "Should only transform unevaluated expressions"); 12999 ExprEvalContexts.back().Context = 13000 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13001 if (isUnevaluatedContext()) 13002 return E; 13003 return TransformToPE(*this).TransformExpr(E); 13004 } 13005 13006 void 13007 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13008 Decl *LambdaContextDecl, 13009 bool IsDecltype) { 13010 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13011 LambdaContextDecl, IsDecltype); 13012 Cleanup.reset(); 13013 if (!MaybeODRUseExprs.empty()) 13014 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13015 } 13016 13017 void 13018 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13019 ReuseLambdaContextDecl_t, 13020 bool IsDecltype) { 13021 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13022 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13023 } 13024 13025 void Sema::PopExpressionEvaluationContext() { 13026 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13027 unsigned NumTypos = Rec.NumTypos; 13028 13029 if (!Rec.Lambdas.empty()) { 13030 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13031 unsigned D; 13032 if (Rec.isUnevaluated()) { 13033 // C++11 [expr.prim.lambda]p2: 13034 // A lambda-expression shall not appear in an unevaluated operand 13035 // (Clause 5). 13036 D = diag::err_lambda_unevaluated_operand; 13037 } else { 13038 // C++1y [expr.const]p2: 13039 // A conditional-expression e is a core constant expression unless the 13040 // evaluation of e, following the rules of the abstract machine, would 13041 // evaluate [...] a lambda-expression. 13042 D = diag::err_lambda_in_constant_expression; 13043 } 13044 for (const auto *L : Rec.Lambdas) 13045 Diag(L->getLocStart(), D); 13046 } else { 13047 // Mark the capture expressions odr-used. This was deferred 13048 // during lambda expression creation. 13049 for (auto *Lambda : Rec.Lambdas) { 13050 for (auto *C : Lambda->capture_inits()) 13051 MarkDeclarationsReferencedInExpr(C); 13052 } 13053 } 13054 } 13055 13056 // When are coming out of an unevaluated context, clear out any 13057 // temporaries that we may have created as part of the evaluation of 13058 // the expression in that context: they aren't relevant because they 13059 // will never be constructed. 13060 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13061 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13062 ExprCleanupObjects.end()); 13063 Cleanup = Rec.ParentCleanup; 13064 CleanupVarDeclMarking(); 13065 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13066 // Otherwise, merge the contexts together. 13067 } else { 13068 Cleanup.mergeFrom(Rec.ParentCleanup); 13069 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13070 Rec.SavedMaybeODRUseExprs.end()); 13071 } 13072 13073 // Pop the current expression evaluation context off the stack. 13074 ExprEvalContexts.pop_back(); 13075 13076 if (!ExprEvalContexts.empty()) 13077 ExprEvalContexts.back().NumTypos += NumTypos; 13078 else 13079 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13080 "last ExpressionEvaluationContextRecord"); 13081 } 13082 13083 void Sema::DiscardCleanupsInEvaluationContext() { 13084 ExprCleanupObjects.erase( 13085 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13086 ExprCleanupObjects.end()); 13087 Cleanup.reset(); 13088 MaybeODRUseExprs.clear(); 13089 } 13090 13091 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13092 if (!E->getType()->isVariablyModifiedType()) 13093 return E; 13094 return TransformToPotentiallyEvaluated(E); 13095 } 13096 13097 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13098 // Do not mark anything as "used" within a dependent context; wait for 13099 // an instantiation. 13100 if (SemaRef.CurContext->isDependentContext()) 13101 return false; 13102 13103 switch (SemaRef.ExprEvalContexts.back().Context) { 13104 case Sema::Unevaluated: 13105 case Sema::UnevaluatedAbstract: 13106 // We are in an expression that is not potentially evaluated; do nothing. 13107 // (Depending on how you read the standard, we actually do need to do 13108 // something here for null pointer constants, but the standard's 13109 // definition of a null pointer constant is completely crazy.) 13110 return false; 13111 13112 case Sema::DiscardedStatement: 13113 // These are technically a potentially evaluated but they have the effect 13114 // of suppressing use marking. 13115 return false; 13116 13117 case Sema::ConstantEvaluated: 13118 case Sema::PotentiallyEvaluated: 13119 // We are in a potentially evaluated expression (or a constant-expression 13120 // in C++03); we need to do implicit template instantiation, implicitly 13121 // define class members, and mark most declarations as used. 13122 return true; 13123 13124 case Sema::PotentiallyEvaluatedIfUsed: 13125 // Referenced declarations will only be used if the construct in the 13126 // containing expression is used. 13127 return false; 13128 } 13129 llvm_unreachable("Invalid context"); 13130 } 13131 13132 /// \brief Mark a function referenced, and check whether it is odr-used 13133 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13134 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13135 bool MightBeOdrUse) { 13136 assert(Func && "No function?"); 13137 13138 Func->setReferenced(); 13139 13140 // C++11 [basic.def.odr]p3: 13141 // A function whose name appears as a potentially-evaluated expression is 13142 // odr-used if it is the unique lookup result or the selected member of a 13143 // set of overloaded functions [...]. 13144 // 13145 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13146 // can just check that here. 13147 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13148 13149 // Determine whether we require a function definition to exist, per 13150 // C++11 [temp.inst]p3: 13151 // Unless a function template specialization has been explicitly 13152 // instantiated or explicitly specialized, the function template 13153 // specialization is implicitly instantiated when the specialization is 13154 // referenced in a context that requires a function definition to exist. 13155 // 13156 // We consider constexpr function templates to be referenced in a context 13157 // that requires a definition to exist whenever they are referenced. 13158 // 13159 // FIXME: This instantiates constexpr functions too frequently. If this is 13160 // really an unevaluated context (and we're not just in the definition of a 13161 // function template or overload resolution or other cases which we 13162 // incorrectly consider to be unevaluated contexts), and we're not in a 13163 // subexpression which we actually need to evaluate (for instance, a 13164 // template argument, array bound or an expression in a braced-init-list), 13165 // we are not permitted to instantiate this constexpr function definition. 13166 // 13167 // FIXME: This also implicitly defines special members too frequently. They 13168 // are only supposed to be implicitly defined if they are odr-used, but they 13169 // are not odr-used from constant expressions in unevaluated contexts. 13170 // However, they cannot be referenced if they are deleted, and they are 13171 // deleted whenever the implicit definition of the special member would 13172 // fail (with very few exceptions). 13173 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13174 bool NeedDefinition = 13175 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13176 (MD && !MD->isUserProvided()))); 13177 13178 // C++14 [temp.expl.spec]p6: 13179 // If a template [...] is explicitly specialized then that specialization 13180 // shall be declared before the first use of that specialization that would 13181 // cause an implicit instantiation to take place, in every translation unit 13182 // in which such a use occurs 13183 if (NeedDefinition && 13184 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13185 Func->getMemberSpecializationInfo())) 13186 checkSpecializationVisibility(Loc, Func); 13187 13188 // C++14 [except.spec]p17: 13189 // An exception-specification is considered to be needed when: 13190 // - the function is odr-used or, if it appears in an unevaluated operand, 13191 // would be odr-used if the expression were potentially-evaluated; 13192 // 13193 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13194 // function is a pure virtual function we're calling, and in that case the 13195 // function was selected by overload resolution and we need to resolve its 13196 // exception specification for a different reason. 13197 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13198 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13199 ResolveExceptionSpec(Loc, FPT); 13200 13201 // If we don't need to mark the function as used, and we don't need to 13202 // try to provide a definition, there's nothing more to do. 13203 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13204 (!NeedDefinition || Func->getBody())) 13205 return; 13206 13207 // Note that this declaration has been used. 13208 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13209 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13210 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13211 if (Constructor->isDefaultConstructor()) { 13212 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13213 return; 13214 DefineImplicitDefaultConstructor(Loc, Constructor); 13215 } else if (Constructor->isCopyConstructor()) { 13216 DefineImplicitCopyConstructor(Loc, Constructor); 13217 } else if (Constructor->isMoveConstructor()) { 13218 DefineImplicitMoveConstructor(Loc, Constructor); 13219 } 13220 } else if (Constructor->getInheritedConstructor()) { 13221 DefineInheritingConstructor(Loc, Constructor); 13222 } 13223 } else if (CXXDestructorDecl *Destructor = 13224 dyn_cast<CXXDestructorDecl>(Func)) { 13225 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13226 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13227 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13228 return; 13229 DefineImplicitDestructor(Loc, Destructor); 13230 } 13231 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13232 MarkVTableUsed(Loc, Destructor->getParent()); 13233 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13234 if (MethodDecl->isOverloadedOperator() && 13235 MethodDecl->getOverloadedOperator() == OO_Equal) { 13236 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13237 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13238 if (MethodDecl->isCopyAssignmentOperator()) 13239 DefineImplicitCopyAssignment(Loc, MethodDecl); 13240 else if (MethodDecl->isMoveAssignmentOperator()) 13241 DefineImplicitMoveAssignment(Loc, MethodDecl); 13242 } 13243 } else if (isa<CXXConversionDecl>(MethodDecl) && 13244 MethodDecl->getParent()->isLambda()) { 13245 CXXConversionDecl *Conversion = 13246 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13247 if (Conversion->isLambdaToBlockPointerConversion()) 13248 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13249 else 13250 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13251 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13252 MarkVTableUsed(Loc, MethodDecl->getParent()); 13253 } 13254 13255 // Recursive functions should be marked when used from another function. 13256 // FIXME: Is this really right? 13257 if (CurContext == Func) return; 13258 13259 // Implicit instantiation of function templates and member functions of 13260 // class templates. 13261 if (Func->isImplicitlyInstantiable()) { 13262 bool AlreadyInstantiated = false; 13263 SourceLocation PointOfInstantiation = Loc; 13264 if (FunctionTemplateSpecializationInfo *SpecInfo 13265 = Func->getTemplateSpecializationInfo()) { 13266 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13267 SpecInfo->setPointOfInstantiation(Loc); 13268 else if (SpecInfo->getTemplateSpecializationKind() 13269 == TSK_ImplicitInstantiation) { 13270 AlreadyInstantiated = true; 13271 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13272 } 13273 } else if (MemberSpecializationInfo *MSInfo 13274 = Func->getMemberSpecializationInfo()) { 13275 if (MSInfo->getPointOfInstantiation().isInvalid()) 13276 MSInfo->setPointOfInstantiation(Loc); 13277 else if (MSInfo->getTemplateSpecializationKind() 13278 == TSK_ImplicitInstantiation) { 13279 AlreadyInstantiated = true; 13280 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13281 } 13282 } 13283 13284 if (!AlreadyInstantiated || Func->isConstexpr()) { 13285 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13286 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13287 ActiveTemplateInstantiations.size()) 13288 PendingLocalImplicitInstantiations.push_back( 13289 std::make_pair(Func, PointOfInstantiation)); 13290 else if (Func->isConstexpr()) 13291 // Do not defer instantiations of constexpr functions, to avoid the 13292 // expression evaluator needing to call back into Sema if it sees a 13293 // call to such a function. 13294 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13295 else { 13296 PendingInstantiations.push_back(std::make_pair(Func, 13297 PointOfInstantiation)); 13298 // Notify the consumer that a function was implicitly instantiated. 13299 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13300 } 13301 } 13302 } else { 13303 // Walk redefinitions, as some of them may be instantiable. 13304 for (auto i : Func->redecls()) { 13305 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13306 MarkFunctionReferenced(Loc, i, OdrUse); 13307 } 13308 } 13309 13310 if (!OdrUse) return; 13311 13312 // Keep track of used but undefined functions. 13313 if (!Func->isDefined()) { 13314 if (mightHaveNonExternalLinkage(Func)) 13315 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13316 else if (Func->getMostRecentDecl()->isInlined() && 13317 !LangOpts.GNUInline && 13318 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13319 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13320 } 13321 13322 Func->markUsed(Context); 13323 } 13324 13325 static void 13326 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13327 ValueDecl *var, DeclContext *DC) { 13328 DeclContext *VarDC = var->getDeclContext(); 13329 13330 // If the parameter still belongs to the translation unit, then 13331 // we're actually just using one parameter in the declaration of 13332 // the next. 13333 if (isa<ParmVarDecl>(var) && 13334 isa<TranslationUnitDecl>(VarDC)) 13335 return; 13336 13337 // For C code, don't diagnose about capture if we're not actually in code 13338 // right now; it's impossible to write a non-constant expression outside of 13339 // function context, so we'll get other (more useful) diagnostics later. 13340 // 13341 // For C++, things get a bit more nasty... it would be nice to suppress this 13342 // diagnostic for certain cases like using a local variable in an array bound 13343 // for a member of a local class, but the correct predicate is not obvious. 13344 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13345 return; 13346 13347 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13348 unsigned ContextKind = 3; // unknown 13349 if (isa<CXXMethodDecl>(VarDC) && 13350 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13351 ContextKind = 2; 13352 } else if (isa<FunctionDecl>(VarDC)) { 13353 ContextKind = 0; 13354 } else if (isa<BlockDecl>(VarDC)) { 13355 ContextKind = 1; 13356 } 13357 13358 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13359 << var << ValueKind << ContextKind << VarDC; 13360 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13361 << var; 13362 13363 // FIXME: Add additional diagnostic info about class etc. which prevents 13364 // capture. 13365 } 13366 13367 13368 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13369 bool &SubCapturesAreNested, 13370 QualType &CaptureType, 13371 QualType &DeclRefType) { 13372 // Check whether we've already captured it. 13373 if (CSI->CaptureMap.count(Var)) { 13374 // If we found a capture, any subcaptures are nested. 13375 SubCapturesAreNested = true; 13376 13377 // Retrieve the capture type for this variable. 13378 CaptureType = CSI->getCapture(Var).getCaptureType(); 13379 13380 // Compute the type of an expression that refers to this variable. 13381 DeclRefType = CaptureType.getNonReferenceType(); 13382 13383 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13384 // are mutable in the sense that user can change their value - they are 13385 // private instances of the captured declarations. 13386 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13387 if (Cap.isCopyCapture() && 13388 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13389 !(isa<CapturedRegionScopeInfo>(CSI) && 13390 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13391 DeclRefType.addConst(); 13392 return true; 13393 } 13394 return false; 13395 } 13396 13397 // Only block literals, captured statements, and lambda expressions can 13398 // capture; other scopes don't work. 13399 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13400 SourceLocation Loc, 13401 const bool Diagnose, Sema &S) { 13402 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13403 return getLambdaAwareParentOfDeclContext(DC); 13404 else if (Var->hasLocalStorage()) { 13405 if (Diagnose) 13406 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13407 } 13408 return nullptr; 13409 } 13410 13411 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13412 // certain types of variables (unnamed, variably modified types etc.) 13413 // so check for eligibility. 13414 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13415 SourceLocation Loc, 13416 const bool Diagnose, Sema &S) { 13417 13418 bool IsBlock = isa<BlockScopeInfo>(CSI); 13419 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13420 13421 // Lambdas are not allowed to capture unnamed variables 13422 // (e.g. anonymous unions). 13423 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13424 // assuming that's the intent. 13425 if (IsLambda && !Var->getDeclName()) { 13426 if (Diagnose) { 13427 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13428 S.Diag(Var->getLocation(), diag::note_declared_at); 13429 } 13430 return false; 13431 } 13432 13433 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13434 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13435 if (Diagnose) { 13436 S.Diag(Loc, diag::err_ref_vm_type); 13437 S.Diag(Var->getLocation(), diag::note_previous_decl) 13438 << Var->getDeclName(); 13439 } 13440 return false; 13441 } 13442 // Prohibit structs with flexible array members too. 13443 // We cannot capture what is in the tail end of the struct. 13444 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13445 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13446 if (Diagnose) { 13447 if (IsBlock) 13448 S.Diag(Loc, diag::err_ref_flexarray_type); 13449 else 13450 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13451 << Var->getDeclName(); 13452 S.Diag(Var->getLocation(), diag::note_previous_decl) 13453 << Var->getDeclName(); 13454 } 13455 return false; 13456 } 13457 } 13458 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13459 // Lambdas and captured statements are not allowed to capture __block 13460 // variables; they don't support the expected semantics. 13461 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13462 if (Diagnose) { 13463 S.Diag(Loc, diag::err_capture_block_variable) 13464 << Var->getDeclName() << !IsLambda; 13465 S.Diag(Var->getLocation(), diag::note_previous_decl) 13466 << Var->getDeclName(); 13467 } 13468 return false; 13469 } 13470 13471 return true; 13472 } 13473 13474 // Returns true if the capture by block was successful. 13475 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13476 SourceLocation Loc, 13477 const bool BuildAndDiagnose, 13478 QualType &CaptureType, 13479 QualType &DeclRefType, 13480 const bool Nested, 13481 Sema &S) { 13482 Expr *CopyExpr = nullptr; 13483 bool ByRef = false; 13484 13485 // Blocks are not allowed to capture arrays. 13486 if (CaptureType->isArrayType()) { 13487 if (BuildAndDiagnose) { 13488 S.Diag(Loc, diag::err_ref_array_type); 13489 S.Diag(Var->getLocation(), diag::note_previous_decl) 13490 << Var->getDeclName(); 13491 } 13492 return false; 13493 } 13494 13495 // Forbid the block-capture of autoreleasing variables. 13496 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13497 if (BuildAndDiagnose) { 13498 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13499 << /*block*/ 0; 13500 S.Diag(Var->getLocation(), diag::note_previous_decl) 13501 << Var->getDeclName(); 13502 } 13503 return false; 13504 } 13505 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13506 if (HasBlocksAttr || CaptureType->isReferenceType() || 13507 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13508 // Block capture by reference does not change the capture or 13509 // declaration reference types. 13510 ByRef = true; 13511 } else { 13512 // Block capture by copy introduces 'const'. 13513 CaptureType = CaptureType.getNonReferenceType().withConst(); 13514 DeclRefType = CaptureType; 13515 13516 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13517 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13518 // The capture logic needs the destructor, so make sure we mark it. 13519 // Usually this is unnecessary because most local variables have 13520 // their destructors marked at declaration time, but parameters are 13521 // an exception because it's technically only the call site that 13522 // actually requires the destructor. 13523 if (isa<ParmVarDecl>(Var)) 13524 S.FinalizeVarWithDestructor(Var, Record); 13525 13526 // Enter a new evaluation context to insulate the copy 13527 // full-expression. 13528 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13529 13530 // According to the blocks spec, the capture of a variable from 13531 // the stack requires a const copy constructor. This is not true 13532 // of the copy/move done to move a __block variable to the heap. 13533 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13534 DeclRefType.withConst(), 13535 VK_LValue, Loc); 13536 13537 ExprResult Result 13538 = S.PerformCopyInitialization( 13539 InitializedEntity::InitializeBlock(Var->getLocation(), 13540 CaptureType, false), 13541 Loc, DeclRef); 13542 13543 // Build a full-expression copy expression if initialization 13544 // succeeded and used a non-trivial constructor. Recover from 13545 // errors by pretending that the copy isn't necessary. 13546 if (!Result.isInvalid() && 13547 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13548 ->isTrivial()) { 13549 Result = S.MaybeCreateExprWithCleanups(Result); 13550 CopyExpr = Result.get(); 13551 } 13552 } 13553 } 13554 } 13555 13556 // Actually capture the variable. 13557 if (BuildAndDiagnose) 13558 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13559 SourceLocation(), CaptureType, CopyExpr); 13560 13561 return true; 13562 13563 } 13564 13565 13566 /// \brief Capture the given variable in the captured region. 13567 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13568 VarDecl *Var, 13569 SourceLocation Loc, 13570 const bool BuildAndDiagnose, 13571 QualType &CaptureType, 13572 QualType &DeclRefType, 13573 const bool RefersToCapturedVariable, 13574 Sema &S) { 13575 // By default, capture variables by reference. 13576 bool ByRef = true; 13577 // Using an LValue reference type is consistent with Lambdas (see below). 13578 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13579 if (S.IsOpenMPCapturedDecl(Var)) 13580 DeclRefType = DeclRefType.getUnqualifiedType(); 13581 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13582 } 13583 13584 if (ByRef) 13585 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13586 else 13587 CaptureType = DeclRefType; 13588 13589 Expr *CopyExpr = nullptr; 13590 if (BuildAndDiagnose) { 13591 // The current implementation assumes that all variables are captured 13592 // by references. Since there is no capture by copy, no expression 13593 // evaluation will be needed. 13594 RecordDecl *RD = RSI->TheRecordDecl; 13595 13596 FieldDecl *Field 13597 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13598 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13599 nullptr, false, ICIS_NoInit); 13600 Field->setImplicit(true); 13601 Field->setAccess(AS_private); 13602 RD->addDecl(Field); 13603 13604 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13605 DeclRefType, VK_LValue, Loc); 13606 Var->setReferenced(true); 13607 Var->markUsed(S.Context); 13608 } 13609 13610 // Actually capture the variable. 13611 if (BuildAndDiagnose) 13612 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13613 SourceLocation(), CaptureType, CopyExpr); 13614 13615 13616 return true; 13617 } 13618 13619 /// \brief Create a field within the lambda class for the variable 13620 /// being captured. 13621 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13622 QualType FieldType, QualType DeclRefType, 13623 SourceLocation Loc, 13624 bool RefersToCapturedVariable) { 13625 CXXRecordDecl *Lambda = LSI->Lambda; 13626 13627 // Build the non-static data member. 13628 FieldDecl *Field 13629 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13630 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13631 nullptr, false, ICIS_NoInit); 13632 Field->setImplicit(true); 13633 Field->setAccess(AS_private); 13634 Lambda->addDecl(Field); 13635 } 13636 13637 /// \brief Capture the given variable in the lambda. 13638 static bool captureInLambda(LambdaScopeInfo *LSI, 13639 VarDecl *Var, 13640 SourceLocation Loc, 13641 const bool BuildAndDiagnose, 13642 QualType &CaptureType, 13643 QualType &DeclRefType, 13644 const bool RefersToCapturedVariable, 13645 const Sema::TryCaptureKind Kind, 13646 SourceLocation EllipsisLoc, 13647 const bool IsTopScope, 13648 Sema &S) { 13649 13650 // Determine whether we are capturing by reference or by value. 13651 bool ByRef = false; 13652 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13653 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13654 } else { 13655 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13656 } 13657 13658 // Compute the type of the field that will capture this variable. 13659 if (ByRef) { 13660 // C++11 [expr.prim.lambda]p15: 13661 // An entity is captured by reference if it is implicitly or 13662 // explicitly captured but not captured by copy. It is 13663 // unspecified whether additional unnamed non-static data 13664 // members are declared in the closure type for entities 13665 // captured by reference. 13666 // 13667 // FIXME: It is not clear whether we want to build an lvalue reference 13668 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13669 // to do the former, while EDG does the latter. Core issue 1249 will 13670 // clarify, but for now we follow GCC because it's a more permissive and 13671 // easily defensible position. 13672 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13673 } else { 13674 // C++11 [expr.prim.lambda]p14: 13675 // For each entity captured by copy, an unnamed non-static 13676 // data member is declared in the closure type. The 13677 // declaration order of these members is unspecified. The type 13678 // of such a data member is the type of the corresponding 13679 // captured entity if the entity is not a reference to an 13680 // object, or the referenced type otherwise. [Note: If the 13681 // captured entity is a reference to a function, the 13682 // corresponding data member is also a reference to a 13683 // function. - end note ] 13684 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13685 if (!RefType->getPointeeType()->isFunctionType()) 13686 CaptureType = RefType->getPointeeType(); 13687 } 13688 13689 // Forbid the lambda copy-capture of autoreleasing variables. 13690 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13691 if (BuildAndDiagnose) { 13692 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13693 S.Diag(Var->getLocation(), diag::note_previous_decl) 13694 << Var->getDeclName(); 13695 } 13696 return false; 13697 } 13698 13699 // Make sure that by-copy captures are of a complete and non-abstract type. 13700 if (BuildAndDiagnose) { 13701 if (!CaptureType->isDependentType() && 13702 S.RequireCompleteType(Loc, CaptureType, 13703 diag::err_capture_of_incomplete_type, 13704 Var->getDeclName())) 13705 return false; 13706 13707 if (S.RequireNonAbstractType(Loc, CaptureType, 13708 diag::err_capture_of_abstract_type)) 13709 return false; 13710 } 13711 } 13712 13713 // Capture this variable in the lambda. 13714 if (BuildAndDiagnose) 13715 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13716 RefersToCapturedVariable); 13717 13718 // Compute the type of a reference to this captured variable. 13719 if (ByRef) 13720 DeclRefType = CaptureType.getNonReferenceType(); 13721 else { 13722 // C++ [expr.prim.lambda]p5: 13723 // The closure type for a lambda-expression has a public inline 13724 // function call operator [...]. This function call operator is 13725 // declared const (9.3.1) if and only if the lambda-expression's 13726 // parameter-declaration-clause is not followed by mutable. 13727 DeclRefType = CaptureType.getNonReferenceType(); 13728 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13729 DeclRefType.addConst(); 13730 } 13731 13732 // Add the capture. 13733 if (BuildAndDiagnose) 13734 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13735 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13736 13737 return true; 13738 } 13739 13740 bool Sema::tryCaptureVariable( 13741 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13742 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13743 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13744 // An init-capture is notionally from the context surrounding its 13745 // declaration, but its parent DC is the lambda class. 13746 DeclContext *VarDC = Var->getDeclContext(); 13747 if (Var->isInitCapture()) 13748 VarDC = VarDC->getParent(); 13749 13750 DeclContext *DC = CurContext; 13751 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13752 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13753 // We need to sync up the Declaration Context with the 13754 // FunctionScopeIndexToStopAt 13755 if (FunctionScopeIndexToStopAt) { 13756 unsigned FSIndex = FunctionScopes.size() - 1; 13757 while (FSIndex != MaxFunctionScopesIndex) { 13758 DC = getLambdaAwareParentOfDeclContext(DC); 13759 --FSIndex; 13760 } 13761 } 13762 13763 13764 // If the variable is declared in the current context, there is no need to 13765 // capture it. 13766 if (VarDC == DC) return true; 13767 13768 // Capture global variables if it is required to use private copy of this 13769 // variable. 13770 bool IsGlobal = !Var->hasLocalStorage(); 13771 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13772 return true; 13773 13774 // Walk up the stack to determine whether we can capture the variable, 13775 // performing the "simple" checks that don't depend on type. We stop when 13776 // we've either hit the declared scope of the variable or find an existing 13777 // capture of that variable. We start from the innermost capturing-entity 13778 // (the DC) and ensure that all intervening capturing-entities 13779 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13780 // declcontext can either capture the variable or have already captured 13781 // the variable. 13782 CaptureType = Var->getType(); 13783 DeclRefType = CaptureType.getNonReferenceType(); 13784 bool Nested = false; 13785 bool Explicit = (Kind != TryCapture_Implicit); 13786 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13787 do { 13788 // Only block literals, captured statements, and lambda expressions can 13789 // capture; other scopes don't work. 13790 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13791 ExprLoc, 13792 BuildAndDiagnose, 13793 *this); 13794 // We need to check for the parent *first* because, if we *have* 13795 // private-captured a global variable, we need to recursively capture it in 13796 // intermediate blocks, lambdas, etc. 13797 if (!ParentDC) { 13798 if (IsGlobal) { 13799 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13800 break; 13801 } 13802 return true; 13803 } 13804 13805 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13806 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13807 13808 13809 // Check whether we've already captured it. 13810 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13811 DeclRefType)) 13812 break; 13813 // If we are instantiating a generic lambda call operator body, 13814 // we do not want to capture new variables. What was captured 13815 // during either a lambdas transformation or initial parsing 13816 // should be used. 13817 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13818 if (BuildAndDiagnose) { 13819 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13820 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13821 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13822 Diag(Var->getLocation(), diag::note_previous_decl) 13823 << Var->getDeclName(); 13824 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13825 } else 13826 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13827 } 13828 return true; 13829 } 13830 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13831 // certain types of variables (unnamed, variably modified types etc.) 13832 // so check for eligibility. 13833 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13834 return true; 13835 13836 // Try to capture variable-length arrays types. 13837 if (Var->getType()->isVariablyModifiedType()) { 13838 // We're going to walk down into the type and look for VLA 13839 // expressions. 13840 QualType QTy = Var->getType(); 13841 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13842 QTy = PVD->getOriginalType(); 13843 captureVariablyModifiedType(Context, QTy, CSI); 13844 } 13845 13846 if (getLangOpts().OpenMP) { 13847 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13848 // OpenMP private variables should not be captured in outer scope, so 13849 // just break here. Similarly, global variables that are captured in a 13850 // target region should not be captured outside the scope of the region. 13851 if (RSI->CapRegionKind == CR_OpenMP) { 13852 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13853 // When we detect target captures we are looking from inside the 13854 // target region, therefore we need to propagate the capture from the 13855 // enclosing region. Therefore, the capture is not initially nested. 13856 if (IsTargetCap) 13857 FunctionScopesIndex--; 13858 13859 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13860 Nested = !IsTargetCap; 13861 DeclRefType = DeclRefType.getUnqualifiedType(); 13862 CaptureType = Context.getLValueReferenceType(DeclRefType); 13863 break; 13864 } 13865 } 13866 } 13867 } 13868 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13869 // No capture-default, and this is not an explicit capture 13870 // so cannot capture this variable. 13871 if (BuildAndDiagnose) { 13872 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13873 Diag(Var->getLocation(), diag::note_previous_decl) 13874 << Var->getDeclName(); 13875 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13876 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13877 diag::note_lambda_decl); 13878 // FIXME: If we error out because an outer lambda can not implicitly 13879 // capture a variable that an inner lambda explicitly captures, we 13880 // should have the inner lambda do the explicit capture - because 13881 // it makes for cleaner diagnostics later. This would purely be done 13882 // so that the diagnostic does not misleadingly claim that a variable 13883 // can not be captured by a lambda implicitly even though it is captured 13884 // explicitly. Suggestion: 13885 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13886 // at the function head 13887 // - cache the StartingDeclContext - this must be a lambda 13888 // - captureInLambda in the innermost lambda the variable. 13889 } 13890 return true; 13891 } 13892 13893 FunctionScopesIndex--; 13894 DC = ParentDC; 13895 Explicit = false; 13896 } while (!VarDC->Equals(DC)); 13897 13898 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13899 // computing the type of the capture at each step, checking type-specific 13900 // requirements, and adding captures if requested. 13901 // If the variable had already been captured previously, we start capturing 13902 // at the lambda nested within that one. 13903 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13904 ++I) { 13905 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13906 13907 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13908 if (!captureInBlock(BSI, Var, ExprLoc, 13909 BuildAndDiagnose, CaptureType, 13910 DeclRefType, Nested, *this)) 13911 return true; 13912 Nested = true; 13913 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13914 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13915 BuildAndDiagnose, CaptureType, 13916 DeclRefType, Nested, *this)) 13917 return true; 13918 Nested = true; 13919 } else { 13920 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13921 if (!captureInLambda(LSI, Var, ExprLoc, 13922 BuildAndDiagnose, CaptureType, 13923 DeclRefType, Nested, Kind, EllipsisLoc, 13924 /*IsTopScope*/I == N - 1, *this)) 13925 return true; 13926 Nested = true; 13927 } 13928 } 13929 return false; 13930 } 13931 13932 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13933 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13934 QualType CaptureType; 13935 QualType DeclRefType; 13936 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13937 /*BuildAndDiagnose=*/true, CaptureType, 13938 DeclRefType, nullptr); 13939 } 13940 13941 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13942 QualType CaptureType; 13943 QualType DeclRefType; 13944 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13945 /*BuildAndDiagnose=*/false, CaptureType, 13946 DeclRefType, nullptr); 13947 } 13948 13949 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13950 QualType CaptureType; 13951 QualType DeclRefType; 13952 13953 // Determine whether we can capture this variable. 13954 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13955 /*BuildAndDiagnose=*/false, CaptureType, 13956 DeclRefType, nullptr)) 13957 return QualType(); 13958 13959 return DeclRefType; 13960 } 13961 13962 13963 13964 // If either the type of the variable or the initializer is dependent, 13965 // return false. Otherwise, determine whether the variable is a constant 13966 // expression. Use this if you need to know if a variable that might or 13967 // might not be dependent is truly a constant expression. 13968 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13969 ASTContext &Context) { 13970 13971 if (Var->getType()->isDependentType()) 13972 return false; 13973 const VarDecl *DefVD = nullptr; 13974 Var->getAnyInitializer(DefVD); 13975 if (!DefVD) 13976 return false; 13977 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13978 Expr *Init = cast<Expr>(Eval->Value); 13979 if (Init->isValueDependent()) 13980 return false; 13981 return IsVariableAConstantExpression(Var, Context); 13982 } 13983 13984 13985 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13986 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13987 // an object that satisfies the requirements for appearing in a 13988 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13989 // is immediately applied." This function handles the lvalue-to-rvalue 13990 // conversion part. 13991 MaybeODRUseExprs.erase(E->IgnoreParens()); 13992 13993 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13994 // to a variable that is a constant expression, and if so, identify it as 13995 // a reference to a variable that does not involve an odr-use of that 13996 // variable. 13997 if (LambdaScopeInfo *LSI = getCurLambda()) { 13998 Expr *SansParensExpr = E->IgnoreParens(); 13999 VarDecl *Var = nullptr; 14000 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14001 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14002 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14003 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14004 14005 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14006 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14007 } 14008 } 14009 14010 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14011 Res = CorrectDelayedTyposInExpr(Res); 14012 14013 if (!Res.isUsable()) 14014 return Res; 14015 14016 // If a constant-expression is a reference to a variable where we delay 14017 // deciding whether it is an odr-use, just assume we will apply the 14018 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14019 // (a non-type template argument), we have special handling anyway. 14020 UpdateMarkingForLValueToRValue(Res.get()); 14021 return Res; 14022 } 14023 14024 void Sema::CleanupVarDeclMarking() { 14025 for (Expr *E : MaybeODRUseExprs) { 14026 VarDecl *Var; 14027 SourceLocation Loc; 14028 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14029 Var = cast<VarDecl>(DRE->getDecl()); 14030 Loc = DRE->getLocation(); 14031 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14032 Var = cast<VarDecl>(ME->getMemberDecl()); 14033 Loc = ME->getMemberLoc(); 14034 } else { 14035 llvm_unreachable("Unexpected expression"); 14036 } 14037 14038 MarkVarDeclODRUsed(Var, Loc, *this, 14039 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14040 } 14041 14042 MaybeODRUseExprs.clear(); 14043 } 14044 14045 14046 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14047 VarDecl *Var, Expr *E) { 14048 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14049 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14050 Var->setReferenced(); 14051 14052 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14053 bool MarkODRUsed = true; 14054 14055 // If the context is not potentially evaluated, this is not an odr-use and 14056 // does not trigger instantiation. 14057 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 14058 if (SemaRef.isUnevaluatedContext()) 14059 return; 14060 14061 // If we don't yet know whether this context is going to end up being an 14062 // evaluated context, and we're referencing a variable from an enclosing 14063 // scope, add a potential capture. 14064 // 14065 // FIXME: Is this necessary? These contexts are only used for default 14066 // arguments, where local variables can't be used. 14067 const bool RefersToEnclosingScope = 14068 (SemaRef.CurContext != Var->getDeclContext() && 14069 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14070 if (RefersToEnclosingScope) { 14071 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 14072 // If a variable could potentially be odr-used, defer marking it so 14073 // until we finish analyzing the full expression for any 14074 // lvalue-to-rvalue 14075 // or discarded value conversions that would obviate odr-use. 14076 // Add it to the list of potential captures that will be analyzed 14077 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14078 // unless the variable is a reference that was initialized by a constant 14079 // expression (this will never need to be captured or odr-used). 14080 assert(E && "Capture variable should be used in an expression."); 14081 if (!Var->getType()->isReferenceType() || 14082 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14083 LSI->addPotentialCapture(E->IgnoreParens()); 14084 } 14085 } 14086 14087 if (!isTemplateInstantiation(TSK)) 14088 return; 14089 14090 // Instantiate, but do not mark as odr-used, variable templates. 14091 MarkODRUsed = false; 14092 } 14093 14094 VarTemplateSpecializationDecl *VarSpec = 14095 dyn_cast<VarTemplateSpecializationDecl>(Var); 14096 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14097 "Can't instantiate a partial template specialization."); 14098 14099 // If this might be a member specialization of a static data member, check 14100 // the specialization is visible. We already did the checks for variable 14101 // template specializations when we created them. 14102 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14103 SemaRef.checkSpecializationVisibility(Loc, Var); 14104 14105 // Perform implicit instantiation of static data members, static data member 14106 // templates of class templates, and variable template specializations. Delay 14107 // instantiations of variable templates, except for those that could be used 14108 // in a constant expression. 14109 if (isTemplateInstantiation(TSK)) { 14110 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14111 14112 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14113 if (Var->getPointOfInstantiation().isInvalid()) { 14114 // This is a modification of an existing AST node. Notify listeners. 14115 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14116 L->StaticDataMemberInstantiated(Var); 14117 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14118 // Don't bother trying to instantiate it again, unless we might need 14119 // its initializer before we get to the end of the TU. 14120 TryInstantiating = false; 14121 } 14122 14123 if (Var->getPointOfInstantiation().isInvalid()) 14124 Var->setTemplateSpecializationKind(TSK, Loc); 14125 14126 if (TryInstantiating) { 14127 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14128 bool InstantiationDependent = false; 14129 bool IsNonDependent = 14130 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14131 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14132 : true; 14133 14134 // Do not instantiate specializations that are still type-dependent. 14135 if (IsNonDependent) { 14136 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14137 // Do not defer instantiations of variables which could be used in a 14138 // constant expression. 14139 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14140 } else { 14141 SemaRef.PendingInstantiations 14142 .push_back(std::make_pair(Var, PointOfInstantiation)); 14143 } 14144 } 14145 } 14146 } 14147 14148 if (!MarkODRUsed) 14149 return; 14150 14151 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14152 // the requirements for appearing in a constant expression (5.19) and, if 14153 // it is an object, the lvalue-to-rvalue conversion (4.1) 14154 // is immediately applied." We check the first part here, and 14155 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14156 // Note that we use the C++11 definition everywhere because nothing in 14157 // C++03 depends on whether we get the C++03 version correct. The second 14158 // part does not apply to references, since they are not objects. 14159 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14160 // A reference initialized by a constant expression can never be 14161 // odr-used, so simply ignore it. 14162 if (!Var->getType()->isReferenceType()) 14163 SemaRef.MaybeODRUseExprs.insert(E); 14164 } else 14165 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14166 /*MaxFunctionScopeIndex ptr*/ nullptr); 14167 } 14168 14169 /// \brief Mark a variable referenced, and check whether it is odr-used 14170 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14171 /// used directly for normal expressions referring to VarDecl. 14172 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14173 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14174 } 14175 14176 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14177 Decl *D, Expr *E, bool MightBeOdrUse) { 14178 if (SemaRef.isInOpenMPDeclareTargetContext()) 14179 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14180 14181 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14182 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14183 return; 14184 } 14185 14186 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14187 14188 // If this is a call to a method via a cast, also mark the method in the 14189 // derived class used in case codegen can devirtualize the call. 14190 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14191 if (!ME) 14192 return; 14193 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14194 if (!MD) 14195 return; 14196 // Only attempt to devirtualize if this is truly a virtual call. 14197 bool IsVirtualCall = MD->isVirtual() && 14198 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14199 if (!IsVirtualCall) 14200 return; 14201 const Expr *Base = ME->getBase(); 14202 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14203 if (!MostDerivedClassDecl) 14204 return; 14205 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14206 if (!DM || DM->isPure()) 14207 return; 14208 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14209 } 14210 14211 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14212 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14213 // TODO: update this with DR# once a defect report is filed. 14214 // C++11 defect. The address of a pure member should not be an ODR use, even 14215 // if it's a qualified reference. 14216 bool OdrUse = true; 14217 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14218 if (Method->isVirtual()) 14219 OdrUse = false; 14220 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14221 } 14222 14223 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14224 void Sema::MarkMemberReferenced(MemberExpr *E) { 14225 // C++11 [basic.def.odr]p2: 14226 // A non-overloaded function whose name appears as a potentially-evaluated 14227 // expression or a member of a set of candidate functions, if selected by 14228 // overload resolution when referred to from a potentially-evaluated 14229 // expression, is odr-used, unless it is a pure virtual function and its 14230 // name is not explicitly qualified. 14231 bool MightBeOdrUse = true; 14232 if (E->performsVirtualDispatch(getLangOpts())) { 14233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14234 if (Method->isPure()) 14235 MightBeOdrUse = false; 14236 } 14237 SourceLocation Loc = E->getMemberLoc().isValid() ? 14238 E->getMemberLoc() : E->getLocStart(); 14239 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14240 } 14241 14242 /// \brief Perform marking for a reference to an arbitrary declaration. It 14243 /// marks the declaration referenced, and performs odr-use checking for 14244 /// functions and variables. This method should not be used when building a 14245 /// normal expression which refers to a variable. 14246 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14247 bool MightBeOdrUse) { 14248 if (MightBeOdrUse) { 14249 if (auto *VD = dyn_cast<VarDecl>(D)) { 14250 MarkVariableReferenced(Loc, VD); 14251 return; 14252 } 14253 } 14254 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14255 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14256 return; 14257 } 14258 D->setReferenced(); 14259 } 14260 14261 namespace { 14262 // Mark all of the declarations referenced 14263 // FIXME: Not fully implemented yet! We need to have a better understanding 14264 // of when we're entering 14265 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14266 Sema &S; 14267 SourceLocation Loc; 14268 14269 public: 14270 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14271 14272 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14273 14274 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14275 bool TraverseRecordType(RecordType *T); 14276 }; 14277 } 14278 14279 bool MarkReferencedDecls::TraverseTemplateArgument( 14280 const TemplateArgument &Arg) { 14281 if (Arg.getKind() == TemplateArgument::Declaration) { 14282 if (Decl *D = Arg.getAsDecl()) 14283 S.MarkAnyDeclReferenced(Loc, D, true); 14284 } 14285 14286 return Inherited::TraverseTemplateArgument(Arg); 14287 } 14288 14289 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14290 if (ClassTemplateSpecializationDecl *Spec 14291 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14292 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14293 return TraverseTemplateArguments(Args.data(), Args.size()); 14294 } 14295 14296 return true; 14297 } 14298 14299 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14300 MarkReferencedDecls Marker(*this, Loc); 14301 Marker.TraverseType(Context.getCanonicalType(T)); 14302 } 14303 14304 namespace { 14305 /// \brief Helper class that marks all of the declarations referenced by 14306 /// potentially-evaluated subexpressions as "referenced". 14307 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14308 Sema &S; 14309 bool SkipLocalVariables; 14310 14311 public: 14312 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14313 14314 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14315 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14316 14317 void VisitDeclRefExpr(DeclRefExpr *E) { 14318 // If we were asked not to visit local variables, don't. 14319 if (SkipLocalVariables) { 14320 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14321 if (VD->hasLocalStorage()) 14322 return; 14323 } 14324 14325 S.MarkDeclRefReferenced(E); 14326 } 14327 14328 void VisitMemberExpr(MemberExpr *E) { 14329 S.MarkMemberReferenced(E); 14330 Inherited::VisitMemberExpr(E); 14331 } 14332 14333 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14334 S.MarkFunctionReferenced(E->getLocStart(), 14335 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14336 Visit(E->getSubExpr()); 14337 } 14338 14339 void VisitCXXNewExpr(CXXNewExpr *E) { 14340 if (E->getOperatorNew()) 14341 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14342 if (E->getOperatorDelete()) 14343 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14344 Inherited::VisitCXXNewExpr(E); 14345 } 14346 14347 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14348 if (E->getOperatorDelete()) 14349 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14350 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14351 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14352 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14353 S.MarkFunctionReferenced(E->getLocStart(), 14354 S.LookupDestructor(Record)); 14355 } 14356 14357 Inherited::VisitCXXDeleteExpr(E); 14358 } 14359 14360 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14361 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14362 Inherited::VisitCXXConstructExpr(E); 14363 } 14364 14365 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14366 Visit(E->getExpr()); 14367 } 14368 14369 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14370 Inherited::VisitImplicitCastExpr(E); 14371 14372 if (E->getCastKind() == CK_LValueToRValue) 14373 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14374 } 14375 }; 14376 } 14377 14378 /// \brief Mark any declarations that appear within this expression or any 14379 /// potentially-evaluated subexpressions as "referenced". 14380 /// 14381 /// \param SkipLocalVariables If true, don't mark local variables as 14382 /// 'referenced'. 14383 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14384 bool SkipLocalVariables) { 14385 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14386 } 14387 14388 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14389 /// of the program being compiled. 14390 /// 14391 /// This routine emits the given diagnostic when the code currently being 14392 /// type-checked is "potentially evaluated", meaning that there is a 14393 /// possibility that the code will actually be executable. Code in sizeof() 14394 /// expressions, code used only during overload resolution, etc., are not 14395 /// potentially evaluated. This routine will suppress such diagnostics or, 14396 /// in the absolutely nutty case of potentially potentially evaluated 14397 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14398 /// later. 14399 /// 14400 /// This routine should be used for all diagnostics that describe the run-time 14401 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14402 /// Failure to do so will likely result in spurious diagnostics or failures 14403 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14404 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14405 const PartialDiagnostic &PD) { 14406 switch (ExprEvalContexts.back().Context) { 14407 case Unevaluated: 14408 case UnevaluatedAbstract: 14409 case DiscardedStatement: 14410 // The argument will never be evaluated, so don't complain. 14411 break; 14412 14413 case ConstantEvaluated: 14414 // Relevant diagnostics should be produced by constant evaluation. 14415 break; 14416 14417 case PotentiallyEvaluated: 14418 case PotentiallyEvaluatedIfUsed: 14419 if (Statement && getCurFunctionOrMethodDecl()) { 14420 FunctionScopes.back()->PossiblyUnreachableDiags. 14421 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14422 } 14423 else 14424 Diag(Loc, PD); 14425 14426 return true; 14427 } 14428 14429 return false; 14430 } 14431 14432 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14433 CallExpr *CE, FunctionDecl *FD) { 14434 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14435 return false; 14436 14437 // If we're inside a decltype's expression, don't check for a valid return 14438 // type or construct temporaries until we know whether this is the last call. 14439 if (ExprEvalContexts.back().IsDecltype) { 14440 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14441 return false; 14442 } 14443 14444 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14445 FunctionDecl *FD; 14446 CallExpr *CE; 14447 14448 public: 14449 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14450 : FD(FD), CE(CE) { } 14451 14452 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14453 if (!FD) { 14454 S.Diag(Loc, diag::err_call_incomplete_return) 14455 << T << CE->getSourceRange(); 14456 return; 14457 } 14458 14459 S.Diag(Loc, diag::err_call_function_incomplete_return) 14460 << CE->getSourceRange() << FD->getDeclName() << T; 14461 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14462 << FD->getDeclName(); 14463 } 14464 } Diagnoser(FD, CE); 14465 14466 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14467 return true; 14468 14469 return false; 14470 } 14471 14472 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14473 // will prevent this condition from triggering, which is what we want. 14474 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14475 SourceLocation Loc; 14476 14477 unsigned diagnostic = diag::warn_condition_is_assignment; 14478 bool IsOrAssign = false; 14479 14480 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14481 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14482 return; 14483 14484 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14485 14486 // Greylist some idioms by putting them into a warning subcategory. 14487 if (ObjCMessageExpr *ME 14488 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14489 Selector Sel = ME->getSelector(); 14490 14491 // self = [<foo> init...] 14492 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14493 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14494 14495 // <foo> = [<bar> nextObject] 14496 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14497 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14498 } 14499 14500 Loc = Op->getOperatorLoc(); 14501 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14502 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14503 return; 14504 14505 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14506 Loc = Op->getOperatorLoc(); 14507 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14508 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14509 else { 14510 // Not an assignment. 14511 return; 14512 } 14513 14514 Diag(Loc, diagnostic) << E->getSourceRange(); 14515 14516 SourceLocation Open = E->getLocStart(); 14517 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14518 Diag(Loc, diag::note_condition_assign_silence) 14519 << FixItHint::CreateInsertion(Open, "(") 14520 << FixItHint::CreateInsertion(Close, ")"); 14521 14522 if (IsOrAssign) 14523 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14524 << FixItHint::CreateReplacement(Loc, "!="); 14525 else 14526 Diag(Loc, diag::note_condition_assign_to_comparison) 14527 << FixItHint::CreateReplacement(Loc, "=="); 14528 } 14529 14530 /// \brief Redundant parentheses over an equality comparison can indicate 14531 /// that the user intended an assignment used as condition. 14532 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14533 // Don't warn if the parens came from a macro. 14534 SourceLocation parenLoc = ParenE->getLocStart(); 14535 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14536 return; 14537 // Don't warn for dependent expressions. 14538 if (ParenE->isTypeDependent()) 14539 return; 14540 14541 Expr *E = ParenE->IgnoreParens(); 14542 14543 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14544 if (opE->getOpcode() == BO_EQ && 14545 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14546 == Expr::MLV_Valid) { 14547 SourceLocation Loc = opE->getOperatorLoc(); 14548 14549 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14550 SourceRange ParenERange = ParenE->getSourceRange(); 14551 Diag(Loc, diag::note_equality_comparison_silence) 14552 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14553 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14554 Diag(Loc, diag::note_equality_comparison_to_assign) 14555 << FixItHint::CreateReplacement(Loc, "="); 14556 } 14557 } 14558 14559 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14560 bool IsConstexpr) { 14561 DiagnoseAssignmentAsCondition(E); 14562 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14563 DiagnoseEqualityWithExtraParens(parenE); 14564 14565 ExprResult result = CheckPlaceholderExpr(E); 14566 if (result.isInvalid()) return ExprError(); 14567 E = result.get(); 14568 14569 if (!E->isTypeDependent()) { 14570 if (getLangOpts().CPlusPlus) 14571 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14572 14573 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14574 if (ERes.isInvalid()) 14575 return ExprError(); 14576 E = ERes.get(); 14577 14578 QualType T = E->getType(); 14579 if (!T->isScalarType()) { // C99 6.8.4.1p1 14580 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14581 << T << E->getSourceRange(); 14582 return ExprError(); 14583 } 14584 CheckBoolLikeConversion(E, Loc); 14585 } 14586 14587 return E; 14588 } 14589 14590 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14591 Expr *SubExpr, ConditionKind CK) { 14592 // Empty conditions are valid in for-statements. 14593 if (!SubExpr) 14594 return ConditionResult(); 14595 14596 ExprResult Cond; 14597 switch (CK) { 14598 case ConditionKind::Boolean: 14599 Cond = CheckBooleanCondition(Loc, SubExpr); 14600 break; 14601 14602 case ConditionKind::ConstexprIf: 14603 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14604 break; 14605 14606 case ConditionKind::Switch: 14607 Cond = CheckSwitchCondition(Loc, SubExpr); 14608 break; 14609 } 14610 if (Cond.isInvalid()) 14611 return ConditionError(); 14612 14613 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14614 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14615 if (!FullExpr.get()) 14616 return ConditionError(); 14617 14618 return ConditionResult(*this, nullptr, FullExpr, 14619 CK == ConditionKind::ConstexprIf); 14620 } 14621 14622 namespace { 14623 /// A visitor for rebuilding a call to an __unknown_any expression 14624 /// to have an appropriate type. 14625 struct RebuildUnknownAnyFunction 14626 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14627 14628 Sema &S; 14629 14630 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14631 14632 ExprResult VisitStmt(Stmt *S) { 14633 llvm_unreachable("unexpected statement!"); 14634 } 14635 14636 ExprResult VisitExpr(Expr *E) { 14637 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14638 << E->getSourceRange(); 14639 return ExprError(); 14640 } 14641 14642 /// Rebuild an expression which simply semantically wraps another 14643 /// expression which it shares the type and value kind of. 14644 template <class T> ExprResult rebuildSugarExpr(T *E) { 14645 ExprResult SubResult = Visit(E->getSubExpr()); 14646 if (SubResult.isInvalid()) return ExprError(); 14647 14648 Expr *SubExpr = SubResult.get(); 14649 E->setSubExpr(SubExpr); 14650 E->setType(SubExpr->getType()); 14651 E->setValueKind(SubExpr->getValueKind()); 14652 assert(E->getObjectKind() == OK_Ordinary); 14653 return E; 14654 } 14655 14656 ExprResult VisitParenExpr(ParenExpr *E) { 14657 return rebuildSugarExpr(E); 14658 } 14659 14660 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14661 return rebuildSugarExpr(E); 14662 } 14663 14664 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14665 ExprResult SubResult = Visit(E->getSubExpr()); 14666 if (SubResult.isInvalid()) return ExprError(); 14667 14668 Expr *SubExpr = SubResult.get(); 14669 E->setSubExpr(SubExpr); 14670 E->setType(S.Context.getPointerType(SubExpr->getType())); 14671 assert(E->getValueKind() == VK_RValue); 14672 assert(E->getObjectKind() == OK_Ordinary); 14673 return E; 14674 } 14675 14676 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14677 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14678 14679 E->setType(VD->getType()); 14680 14681 assert(E->getValueKind() == VK_RValue); 14682 if (S.getLangOpts().CPlusPlus && 14683 !(isa<CXXMethodDecl>(VD) && 14684 cast<CXXMethodDecl>(VD)->isInstance())) 14685 E->setValueKind(VK_LValue); 14686 14687 return E; 14688 } 14689 14690 ExprResult VisitMemberExpr(MemberExpr *E) { 14691 return resolveDecl(E, E->getMemberDecl()); 14692 } 14693 14694 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14695 return resolveDecl(E, E->getDecl()); 14696 } 14697 }; 14698 } 14699 14700 /// Given a function expression of unknown-any type, try to rebuild it 14701 /// to have a function type. 14702 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14703 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14704 if (Result.isInvalid()) return ExprError(); 14705 return S.DefaultFunctionArrayConversion(Result.get()); 14706 } 14707 14708 namespace { 14709 /// A visitor for rebuilding an expression of type __unknown_anytype 14710 /// into one which resolves the type directly on the referring 14711 /// expression. Strict preservation of the original source 14712 /// structure is not a goal. 14713 struct RebuildUnknownAnyExpr 14714 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14715 14716 Sema &S; 14717 14718 /// The current destination type. 14719 QualType DestType; 14720 14721 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14722 : S(S), DestType(CastType) {} 14723 14724 ExprResult VisitStmt(Stmt *S) { 14725 llvm_unreachable("unexpected statement!"); 14726 } 14727 14728 ExprResult VisitExpr(Expr *E) { 14729 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14730 << E->getSourceRange(); 14731 return ExprError(); 14732 } 14733 14734 ExprResult VisitCallExpr(CallExpr *E); 14735 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14736 14737 /// Rebuild an expression which simply semantically wraps another 14738 /// expression which it shares the type and value kind of. 14739 template <class T> ExprResult rebuildSugarExpr(T *E) { 14740 ExprResult SubResult = Visit(E->getSubExpr()); 14741 if (SubResult.isInvalid()) return ExprError(); 14742 Expr *SubExpr = SubResult.get(); 14743 E->setSubExpr(SubExpr); 14744 E->setType(SubExpr->getType()); 14745 E->setValueKind(SubExpr->getValueKind()); 14746 assert(E->getObjectKind() == OK_Ordinary); 14747 return E; 14748 } 14749 14750 ExprResult VisitParenExpr(ParenExpr *E) { 14751 return rebuildSugarExpr(E); 14752 } 14753 14754 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14755 return rebuildSugarExpr(E); 14756 } 14757 14758 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14759 const PointerType *Ptr = DestType->getAs<PointerType>(); 14760 if (!Ptr) { 14761 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14762 << E->getSourceRange(); 14763 return ExprError(); 14764 } 14765 assert(E->getValueKind() == VK_RValue); 14766 assert(E->getObjectKind() == OK_Ordinary); 14767 E->setType(DestType); 14768 14769 // Build the sub-expression as if it were an object of the pointee type. 14770 DestType = Ptr->getPointeeType(); 14771 ExprResult SubResult = Visit(E->getSubExpr()); 14772 if (SubResult.isInvalid()) return ExprError(); 14773 E->setSubExpr(SubResult.get()); 14774 return E; 14775 } 14776 14777 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14778 14779 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14780 14781 ExprResult VisitMemberExpr(MemberExpr *E) { 14782 return resolveDecl(E, E->getMemberDecl()); 14783 } 14784 14785 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14786 return resolveDecl(E, E->getDecl()); 14787 } 14788 }; 14789 } 14790 14791 /// Rebuilds a call expression which yielded __unknown_anytype. 14792 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14793 Expr *CalleeExpr = E->getCallee(); 14794 14795 enum FnKind { 14796 FK_MemberFunction, 14797 FK_FunctionPointer, 14798 FK_BlockPointer 14799 }; 14800 14801 FnKind Kind; 14802 QualType CalleeType = CalleeExpr->getType(); 14803 if (CalleeType == S.Context.BoundMemberTy) { 14804 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14805 Kind = FK_MemberFunction; 14806 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14807 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14808 CalleeType = Ptr->getPointeeType(); 14809 Kind = FK_FunctionPointer; 14810 } else { 14811 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14812 Kind = FK_BlockPointer; 14813 } 14814 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14815 14816 // Verify that this is a legal result type of a function. 14817 if (DestType->isArrayType() || DestType->isFunctionType()) { 14818 unsigned diagID = diag::err_func_returning_array_function; 14819 if (Kind == FK_BlockPointer) 14820 diagID = diag::err_block_returning_array_function; 14821 14822 S.Diag(E->getExprLoc(), diagID) 14823 << DestType->isFunctionType() << DestType; 14824 return ExprError(); 14825 } 14826 14827 // Otherwise, go ahead and set DestType as the call's result. 14828 E->setType(DestType.getNonLValueExprType(S.Context)); 14829 E->setValueKind(Expr::getValueKindForType(DestType)); 14830 assert(E->getObjectKind() == OK_Ordinary); 14831 14832 // Rebuild the function type, replacing the result type with DestType. 14833 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14834 if (Proto) { 14835 // __unknown_anytype(...) is a special case used by the debugger when 14836 // it has no idea what a function's signature is. 14837 // 14838 // We want to build this call essentially under the K&R 14839 // unprototyped rules, but making a FunctionNoProtoType in C++ 14840 // would foul up all sorts of assumptions. However, we cannot 14841 // simply pass all arguments as variadic arguments, nor can we 14842 // portably just call the function under a non-variadic type; see 14843 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14844 // However, it turns out that in practice it is generally safe to 14845 // call a function declared as "A foo(B,C,D);" under the prototype 14846 // "A foo(B,C,D,...);". The only known exception is with the 14847 // Windows ABI, where any variadic function is implicitly cdecl 14848 // regardless of its normal CC. Therefore we change the parameter 14849 // types to match the types of the arguments. 14850 // 14851 // This is a hack, but it is far superior to moving the 14852 // corresponding target-specific code from IR-gen to Sema/AST. 14853 14854 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14855 SmallVector<QualType, 8> ArgTypes; 14856 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14857 ArgTypes.reserve(E->getNumArgs()); 14858 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14859 Expr *Arg = E->getArg(i); 14860 QualType ArgType = Arg->getType(); 14861 if (E->isLValue()) { 14862 ArgType = S.Context.getLValueReferenceType(ArgType); 14863 } else if (E->isXValue()) { 14864 ArgType = S.Context.getRValueReferenceType(ArgType); 14865 } 14866 ArgTypes.push_back(ArgType); 14867 } 14868 ParamTypes = ArgTypes; 14869 } 14870 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14871 Proto->getExtProtoInfo()); 14872 } else { 14873 DestType = S.Context.getFunctionNoProtoType(DestType, 14874 FnType->getExtInfo()); 14875 } 14876 14877 // Rebuild the appropriate pointer-to-function type. 14878 switch (Kind) { 14879 case FK_MemberFunction: 14880 // Nothing to do. 14881 break; 14882 14883 case FK_FunctionPointer: 14884 DestType = S.Context.getPointerType(DestType); 14885 break; 14886 14887 case FK_BlockPointer: 14888 DestType = S.Context.getBlockPointerType(DestType); 14889 break; 14890 } 14891 14892 // Finally, we can recurse. 14893 ExprResult CalleeResult = Visit(CalleeExpr); 14894 if (!CalleeResult.isUsable()) return ExprError(); 14895 E->setCallee(CalleeResult.get()); 14896 14897 // Bind a temporary if necessary. 14898 return S.MaybeBindToTemporary(E); 14899 } 14900 14901 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14902 // Verify that this is a legal result type of a call. 14903 if (DestType->isArrayType() || DestType->isFunctionType()) { 14904 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14905 << DestType->isFunctionType() << DestType; 14906 return ExprError(); 14907 } 14908 14909 // Rewrite the method result type if available. 14910 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14911 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14912 Method->setReturnType(DestType); 14913 } 14914 14915 // Change the type of the message. 14916 E->setType(DestType.getNonReferenceType()); 14917 E->setValueKind(Expr::getValueKindForType(DestType)); 14918 14919 return S.MaybeBindToTemporary(E); 14920 } 14921 14922 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14923 // The only case we should ever see here is a function-to-pointer decay. 14924 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14925 assert(E->getValueKind() == VK_RValue); 14926 assert(E->getObjectKind() == OK_Ordinary); 14927 14928 E->setType(DestType); 14929 14930 // Rebuild the sub-expression as the pointee (function) type. 14931 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14932 14933 ExprResult Result = Visit(E->getSubExpr()); 14934 if (!Result.isUsable()) return ExprError(); 14935 14936 E->setSubExpr(Result.get()); 14937 return E; 14938 } else if (E->getCastKind() == CK_LValueToRValue) { 14939 assert(E->getValueKind() == VK_RValue); 14940 assert(E->getObjectKind() == OK_Ordinary); 14941 14942 assert(isa<BlockPointerType>(E->getType())); 14943 14944 E->setType(DestType); 14945 14946 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14947 DestType = S.Context.getLValueReferenceType(DestType); 14948 14949 ExprResult Result = Visit(E->getSubExpr()); 14950 if (!Result.isUsable()) return ExprError(); 14951 14952 E->setSubExpr(Result.get()); 14953 return E; 14954 } else { 14955 llvm_unreachable("Unhandled cast type!"); 14956 } 14957 } 14958 14959 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14960 ExprValueKind ValueKind = VK_LValue; 14961 QualType Type = DestType; 14962 14963 // We know how to make this work for certain kinds of decls: 14964 14965 // - functions 14966 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14967 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14968 DestType = Ptr->getPointeeType(); 14969 ExprResult Result = resolveDecl(E, VD); 14970 if (Result.isInvalid()) return ExprError(); 14971 return S.ImpCastExprToType(Result.get(), Type, 14972 CK_FunctionToPointerDecay, VK_RValue); 14973 } 14974 14975 if (!Type->isFunctionType()) { 14976 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14977 << VD << E->getSourceRange(); 14978 return ExprError(); 14979 } 14980 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14981 // We must match the FunctionDecl's type to the hack introduced in 14982 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14983 // type. See the lengthy commentary in that routine. 14984 QualType FDT = FD->getType(); 14985 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14986 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14987 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14988 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14989 SourceLocation Loc = FD->getLocation(); 14990 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14991 FD->getDeclContext(), 14992 Loc, Loc, FD->getNameInfo().getName(), 14993 DestType, FD->getTypeSourceInfo(), 14994 SC_None, false/*isInlineSpecified*/, 14995 FD->hasPrototype(), 14996 false/*isConstexprSpecified*/); 14997 14998 if (FD->getQualifier()) 14999 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15000 15001 SmallVector<ParmVarDecl*, 16> Params; 15002 for (const auto &AI : FT->param_types()) { 15003 ParmVarDecl *Param = 15004 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15005 Param->setScopeInfo(0, Params.size()); 15006 Params.push_back(Param); 15007 } 15008 NewFD->setParams(Params); 15009 DRE->setDecl(NewFD); 15010 VD = DRE->getDecl(); 15011 } 15012 } 15013 15014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15015 if (MD->isInstance()) { 15016 ValueKind = VK_RValue; 15017 Type = S.Context.BoundMemberTy; 15018 } 15019 15020 // Function references aren't l-values in C. 15021 if (!S.getLangOpts().CPlusPlus) 15022 ValueKind = VK_RValue; 15023 15024 // - variables 15025 } else if (isa<VarDecl>(VD)) { 15026 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15027 Type = RefTy->getPointeeType(); 15028 } else if (Type->isFunctionType()) { 15029 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15030 << VD << E->getSourceRange(); 15031 return ExprError(); 15032 } 15033 15034 // - nothing else 15035 } else { 15036 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15037 << VD << E->getSourceRange(); 15038 return ExprError(); 15039 } 15040 15041 // Modifying the declaration like this is friendly to IR-gen but 15042 // also really dangerous. 15043 VD->setType(DestType); 15044 E->setType(Type); 15045 E->setValueKind(ValueKind); 15046 return E; 15047 } 15048 15049 /// Check a cast of an unknown-any type. We intentionally only 15050 /// trigger this for C-style casts. 15051 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15052 Expr *CastExpr, CastKind &CastKind, 15053 ExprValueKind &VK, CXXCastPath &Path) { 15054 // The type we're casting to must be either void or complete. 15055 if (!CastType->isVoidType() && 15056 RequireCompleteType(TypeRange.getBegin(), CastType, 15057 diag::err_typecheck_cast_to_incomplete)) 15058 return ExprError(); 15059 15060 // Rewrite the casted expression from scratch. 15061 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15062 if (!result.isUsable()) return ExprError(); 15063 15064 CastExpr = result.get(); 15065 VK = CastExpr->getValueKind(); 15066 CastKind = CK_NoOp; 15067 15068 return CastExpr; 15069 } 15070 15071 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15072 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15073 } 15074 15075 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15076 Expr *arg, QualType ¶mType) { 15077 // If the syntactic form of the argument is not an explicit cast of 15078 // any sort, just do default argument promotion. 15079 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15080 if (!castArg) { 15081 ExprResult result = DefaultArgumentPromotion(arg); 15082 if (result.isInvalid()) return ExprError(); 15083 paramType = result.get()->getType(); 15084 return result; 15085 } 15086 15087 // Otherwise, use the type that was written in the explicit cast. 15088 assert(!arg->hasPlaceholderType()); 15089 paramType = castArg->getTypeAsWritten(); 15090 15091 // Copy-initialize a parameter of that type. 15092 InitializedEntity entity = 15093 InitializedEntity::InitializeParameter(Context, paramType, 15094 /*consumed*/ false); 15095 return PerformCopyInitialization(entity, callLoc, arg); 15096 } 15097 15098 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15099 Expr *orig = E; 15100 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15101 while (true) { 15102 E = E->IgnoreParenImpCasts(); 15103 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15104 E = call->getCallee(); 15105 diagID = diag::err_uncasted_call_of_unknown_any; 15106 } else { 15107 break; 15108 } 15109 } 15110 15111 SourceLocation loc; 15112 NamedDecl *d; 15113 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15114 loc = ref->getLocation(); 15115 d = ref->getDecl(); 15116 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15117 loc = mem->getMemberLoc(); 15118 d = mem->getMemberDecl(); 15119 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15120 diagID = diag::err_uncasted_call_of_unknown_any; 15121 loc = msg->getSelectorStartLoc(); 15122 d = msg->getMethodDecl(); 15123 if (!d) { 15124 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15125 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15126 << orig->getSourceRange(); 15127 return ExprError(); 15128 } 15129 } else { 15130 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15131 << E->getSourceRange(); 15132 return ExprError(); 15133 } 15134 15135 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15136 15137 // Never recoverable. 15138 return ExprError(); 15139 } 15140 15141 /// Check for operands with placeholder types and complain if found. 15142 /// Returns true if there was an error and no recovery was possible. 15143 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15144 if (!getLangOpts().CPlusPlus) { 15145 // C cannot handle TypoExpr nodes on either side of a binop because it 15146 // doesn't handle dependent types properly, so make sure any TypoExprs have 15147 // been dealt with before checking the operands. 15148 ExprResult Result = CorrectDelayedTyposInExpr(E); 15149 if (!Result.isUsable()) return ExprError(); 15150 E = Result.get(); 15151 } 15152 15153 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15154 if (!placeholderType) return E; 15155 15156 switch (placeholderType->getKind()) { 15157 15158 // Overloaded expressions. 15159 case BuiltinType::Overload: { 15160 // Try to resolve a single function template specialization. 15161 // This is obligatory. 15162 ExprResult Result = E; 15163 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15164 return Result; 15165 15166 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15167 // leaves Result unchanged on failure. 15168 Result = E; 15169 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15170 return Result; 15171 15172 // If that failed, try to recover with a call. 15173 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15174 /*complain*/ true); 15175 return Result; 15176 } 15177 15178 // Bound member functions. 15179 case BuiltinType::BoundMember: { 15180 ExprResult result = E; 15181 const Expr *BME = E->IgnoreParens(); 15182 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15183 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15184 if (isa<CXXPseudoDestructorExpr>(BME)) { 15185 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15186 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15187 if (ME->getMemberNameInfo().getName().getNameKind() == 15188 DeclarationName::CXXDestructorName) 15189 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15190 } 15191 tryToRecoverWithCall(result, PD, 15192 /*complain*/ true); 15193 return result; 15194 } 15195 15196 // ARC unbridged casts. 15197 case BuiltinType::ARCUnbridgedCast: { 15198 Expr *realCast = stripARCUnbridgedCast(E); 15199 diagnoseARCUnbridgedCast(realCast); 15200 return realCast; 15201 } 15202 15203 // Expressions of unknown type. 15204 case BuiltinType::UnknownAny: 15205 return diagnoseUnknownAnyExpr(*this, E); 15206 15207 // Pseudo-objects. 15208 case BuiltinType::PseudoObject: 15209 return checkPseudoObjectRValue(E); 15210 15211 case BuiltinType::BuiltinFn: { 15212 // Accept __noop without parens by implicitly converting it to a call expr. 15213 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15214 if (DRE) { 15215 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15216 if (FD->getBuiltinID() == Builtin::BI__noop) { 15217 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15218 CK_BuiltinFnToFnPtr).get(); 15219 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15220 VK_RValue, SourceLocation()); 15221 } 15222 } 15223 15224 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15225 return ExprError(); 15226 } 15227 15228 // Expressions of unknown type. 15229 case BuiltinType::OMPArraySection: 15230 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15231 return ExprError(); 15232 15233 // Everything else should be impossible. 15234 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15235 case BuiltinType::Id: 15236 #include "clang/Basic/OpenCLImageTypes.def" 15237 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15238 #define PLACEHOLDER_TYPE(Id, SingletonId) 15239 #include "clang/AST/BuiltinTypes.def" 15240 break; 15241 } 15242 15243 llvm_unreachable("invalid placeholder type!"); 15244 } 15245 15246 bool Sema::CheckCaseExpression(Expr *E) { 15247 if (E->isTypeDependent()) 15248 return true; 15249 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15250 return E->getType()->isIntegralOrEnumerationType(); 15251 return false; 15252 } 15253 15254 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15255 ExprResult 15256 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15257 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15258 "Unknown Objective-C Boolean value!"); 15259 QualType BoolT = Context.ObjCBuiltinBoolTy; 15260 if (!Context.getBOOLDecl()) { 15261 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15262 Sema::LookupOrdinaryName); 15263 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15264 NamedDecl *ND = Result.getFoundDecl(); 15265 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15266 Context.setBOOLDecl(TD); 15267 } 15268 } 15269 if (Context.getBOOLDecl()) 15270 BoolT = Context.getBOOLType(); 15271 return new (Context) 15272 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15273 } 15274 15275 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15276 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15277 SourceLocation RParen) { 15278 15279 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15280 15281 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15282 [&](const AvailabilitySpec &Spec) { 15283 return Spec.getPlatform() == Platform; 15284 }); 15285 15286 VersionTuple Version; 15287 if (Spec != AvailSpecs.end()) 15288 Version = Spec->getVersion(); 15289 15290 return new (Context) 15291 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15292 } 15293