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 379 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 380 // Only the variables omp_in and omp_out are allowed in the combiner. 381 // Only the variables omp_priv and omp_orig are allowed in the 382 // initializer-clause. 383 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 384 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 385 isa<VarDecl>(D)) { 386 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 387 << getCurFunction()->HasOMPDeclareReductionCombiner; 388 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 389 return true; 390 } 391 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 392 ObjCPropertyAccess); 393 394 DiagnoseUnusedOfDecl(*this, D, Loc); 395 396 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 397 398 return false; 399 } 400 401 /// \brief Retrieve the message suffix that should be added to a 402 /// diagnostic complaining about the given function being deleted or 403 /// unavailable. 404 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 405 std::string Message; 406 if (FD->getAvailability(&Message)) 407 return ": " + Message; 408 409 return std::string(); 410 } 411 412 /// DiagnoseSentinelCalls - This routine checks whether a call or 413 /// message-send is to a declaration with the sentinel attribute, and 414 /// if so, it checks that the requirements of the sentinel are 415 /// satisfied. 416 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 417 ArrayRef<Expr *> Args) { 418 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 419 if (!attr) 420 return; 421 422 // The number of formal parameters of the declaration. 423 unsigned numFormalParams; 424 425 // The kind of declaration. This is also an index into a %select in 426 // the diagnostic. 427 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 428 429 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 430 numFormalParams = MD->param_size(); 431 calleeType = CT_Method; 432 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 433 numFormalParams = FD->param_size(); 434 calleeType = CT_Function; 435 } else if (isa<VarDecl>(D)) { 436 QualType type = cast<ValueDecl>(D)->getType(); 437 const FunctionType *fn = nullptr; 438 if (const PointerType *ptr = type->getAs<PointerType>()) { 439 fn = ptr->getPointeeType()->getAs<FunctionType>(); 440 if (!fn) return; 441 calleeType = CT_Function; 442 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 443 fn = ptr->getPointeeType()->castAs<FunctionType>(); 444 calleeType = CT_Block; 445 } else { 446 return; 447 } 448 449 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 450 numFormalParams = proto->getNumParams(); 451 } else { 452 numFormalParams = 0; 453 } 454 } else { 455 return; 456 } 457 458 // "nullPos" is the number of formal parameters at the end which 459 // effectively count as part of the variadic arguments. This is 460 // useful if you would prefer to not have *any* formal parameters, 461 // but the language forces you to have at least one. 462 unsigned nullPos = attr->getNullPos(); 463 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 464 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 465 466 // The number of arguments which should follow the sentinel. 467 unsigned numArgsAfterSentinel = attr->getSentinel(); 468 469 // If there aren't enough arguments for all the formal parameters, 470 // the sentinel, and the args after the sentinel, complain. 471 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 474 return; 475 } 476 477 // Otherwise, find the sentinel expression. 478 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 479 if (!sentinelExpr) return; 480 if (sentinelExpr->isValueDependent()) return; 481 if (Context.isSentinelNullExpr(sentinelExpr)) return; 482 483 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 484 // or 'NULL' if those are actually defined in the context. Only use 485 // 'nil' for ObjC methods, where it's much more likely that the 486 // variadic arguments form a list of object pointers. 487 SourceLocation MissingNilLoc 488 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 489 std::string NullValue; 490 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 491 NullValue = "nil"; 492 else if (getLangOpts().CPlusPlus11) 493 NullValue = "nullptr"; 494 else if (PP.isMacroDefined("NULL")) 495 NullValue = "NULL"; 496 else 497 NullValue = "(void*) 0"; 498 499 if (MissingNilLoc.isInvalid()) 500 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 501 else 502 Diag(MissingNilLoc, diag::warn_missing_sentinel) 503 << int(calleeType) 504 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 505 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 506 } 507 508 SourceRange Sema::getExprRange(Expr *E) const { 509 return E ? E->getSourceRange() : SourceRange(); 510 } 511 512 //===----------------------------------------------------------------------===// 513 // Standard Promotions and Conversions 514 //===----------------------------------------------------------------------===// 515 516 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 517 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 518 // Handle any placeholder expressions which made it here. 519 if (E->getType()->isPlaceholderType()) { 520 ExprResult result = CheckPlaceholderExpr(E); 521 if (result.isInvalid()) return ExprError(); 522 E = result.get(); 523 } 524 525 QualType Ty = E->getType(); 526 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 527 528 if (Ty->isFunctionType()) { 529 // If we are here, we are not calling a function but taking 530 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 531 if (getLangOpts().OpenCL) { 532 if (Diagnose) 533 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 534 return ExprError(); 535 } 536 537 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 538 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 539 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 540 return ExprError(); 541 542 E = ImpCastExprToType(E, Context.getPointerType(Ty), 543 CK_FunctionToPointerDecay).get(); 544 } else if (Ty->isArrayType()) { 545 // In C90 mode, arrays only promote to pointers if the array expression is 546 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 547 // type 'array of type' is converted to an expression that has type 'pointer 548 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 549 // that has type 'array of type' ...". The relevant change is "an lvalue" 550 // (C90) to "an expression" (C99). 551 // 552 // C++ 4.2p1: 553 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 554 // T" can be converted to an rvalue of type "pointer to T". 555 // 556 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 557 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 558 CK_ArrayToPointerDecay).get(); 559 } 560 return E; 561 } 562 563 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 564 // Check to see if we are dereferencing a null pointer. If so, 565 // and if not volatile-qualified, this is undefined behavior that the 566 // optimizer will delete, so warn about it. People sometimes try to use this 567 // to get a deterministic trap and are surprised by clang's behavior. This 568 // only handles the pattern "*null", which is a very syntactic check. 569 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 570 if (UO->getOpcode() == UO_Deref && 571 UO->getSubExpr()->IgnoreParenCasts()-> 572 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 573 !UO->getType().isVolatileQualified()) { 574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 575 S.PDiag(diag::warn_indirection_through_null) 576 << UO->getSubExpr()->getSourceRange()); 577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 578 S.PDiag(diag::note_indirection_through_null)); 579 } 580 } 581 582 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 583 SourceLocation AssignLoc, 584 const Expr* RHS) { 585 const ObjCIvarDecl *IV = OIRE->getDecl(); 586 if (!IV) 587 return; 588 589 DeclarationName MemberName = IV->getDeclName(); 590 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 591 if (!Member || !Member->isStr("isa")) 592 return; 593 594 const Expr *Base = OIRE->getBase(); 595 QualType BaseType = Base->getType(); 596 if (OIRE->isArrow()) 597 BaseType = BaseType->getPointeeType(); 598 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 599 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 600 ObjCInterfaceDecl *ClassDeclared = nullptr; 601 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 602 if (!ClassDeclared->getSuperClass() 603 && (*ClassDeclared->ivar_begin()) == IV) { 604 if (RHS) { 605 NamedDecl *ObjectSetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_setClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectSetClass) { 610 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 611 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 612 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 613 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 614 AssignLoc), ",") << 615 FixItHint::CreateInsertion(RHSLocEnd, ")"); 616 } 617 else 618 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 619 } else { 620 NamedDecl *ObjectGetClass = 621 S.LookupSingleName(S.TUScope, 622 &S.Context.Idents.get("object_getClass"), 623 SourceLocation(), S.LookupOrdinaryName); 624 if (ObjectGetClass) 625 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 626 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 627 FixItHint::CreateReplacement( 628 SourceRange(OIRE->getOpLoc(), 629 OIRE->getLocEnd()), ")"); 630 else 631 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 632 } 633 S.Diag(IV->getLocation(), diag::note_ivar_decl); 634 } 635 } 636 } 637 638 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 639 // Handle any placeholder expressions which made it here. 640 if (E->getType()->isPlaceholderType()) { 641 ExprResult result = CheckPlaceholderExpr(E); 642 if (result.isInvalid()) return ExprError(); 643 E = result.get(); 644 } 645 646 // C++ [conv.lval]p1: 647 // A glvalue of a non-function, non-array type T can be 648 // converted to a prvalue. 649 if (!E->isGLValue()) return E; 650 651 QualType T = E->getType(); 652 assert(!T.isNull() && "r-value conversion on typeless expression?"); 653 654 // We don't want to throw lvalue-to-rvalue casts on top of 655 // expressions of certain types in C++. 656 if (getLangOpts().CPlusPlus && 657 (E->getType() == Context.OverloadTy || 658 T->isDependentType() || 659 T->isRecordType())) 660 return E; 661 662 // The C standard is actually really unclear on this point, and 663 // DR106 tells us what the result should be but not why. It's 664 // generally best to say that void types just doesn't undergo 665 // lvalue-to-rvalue at all. Note that expressions of unqualified 666 // 'void' type are never l-values, but qualified void can be. 667 if (T->isVoidType()) 668 return E; 669 670 // OpenCL usually rejects direct accesses to values of 'half' type. 671 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 672 T->isHalfType()) { 673 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 674 << 0 << T; 675 return ExprError(); 676 } 677 678 CheckForNullPointerDereference(*this, E); 679 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 680 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 681 &Context.Idents.get("object_getClass"), 682 SourceLocation(), LookupOrdinaryName); 683 if (ObjectGetClass) 684 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 685 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 686 FixItHint::CreateReplacement( 687 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 688 else 689 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 690 } 691 else if (const ObjCIvarRefExpr *OIRE = 692 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 693 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 694 695 // C++ [conv.lval]p1: 696 // [...] If T is a non-class type, the type of the prvalue is the 697 // cv-unqualified version of T. Otherwise, the type of the 698 // rvalue is T. 699 // 700 // C99 6.3.2.1p2: 701 // If the lvalue has qualified type, the value has the unqualified 702 // version of the type of the lvalue; otherwise, the value has the 703 // type of the lvalue. 704 if (T.hasQualifiers()) 705 T = T.getUnqualifiedType(); 706 707 // Under the MS ABI, lock down the inheritance model now. 708 if (T->isMemberPointerType() && 709 Context.getTargetInfo().getCXXABI().isMicrosoft()) 710 (void)isCompleteType(E->getExprLoc(), T); 711 712 UpdateMarkingForLValueToRValue(E); 713 714 // Loading a __weak object implicitly retains the value, so we need a cleanup to 715 // balance that. 716 if (getLangOpts().ObjCAutoRefCount && 717 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 718 Cleanup.setExprNeedsCleanups(true); 719 720 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 721 nullptr, VK_RValue); 722 723 // C11 6.3.2.1p2: 724 // ... if the lvalue has atomic type, the value has the non-atomic version 725 // of the type of the lvalue ... 726 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 727 T = Atomic->getValueType().getUnqualifiedType(); 728 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 729 nullptr, VK_RValue); 730 } 731 732 return Res; 733 } 734 735 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 736 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 737 if (Res.isInvalid()) 738 return ExprError(); 739 Res = DefaultLvalueConversion(Res.get()); 740 if (Res.isInvalid()) 741 return ExprError(); 742 return Res; 743 } 744 745 /// CallExprUnaryConversions - a special case of an unary conversion 746 /// performed on a function designator of a call expression. 747 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 748 QualType Ty = E->getType(); 749 ExprResult Res = E; 750 // Only do implicit cast for a function type, but not for a pointer 751 // to function type. 752 if (Ty->isFunctionType()) { 753 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 754 CK_FunctionToPointerDecay).get(); 755 if (Res.isInvalid()) 756 return ExprError(); 757 } 758 Res = DefaultLvalueConversion(Res.get()); 759 if (Res.isInvalid()) 760 return ExprError(); 761 return Res.get(); 762 } 763 764 /// UsualUnaryConversions - Performs various conversions that are common to most 765 /// operators (C99 6.3). The conversions of array and function types are 766 /// sometimes suppressed. For example, the array->pointer conversion doesn't 767 /// apply if the array is an argument to the sizeof or address (&) operators. 768 /// In these instances, this routine should *not* be called. 769 ExprResult Sema::UsualUnaryConversions(Expr *E) { 770 // First, convert to an r-value. 771 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 772 if (Res.isInvalid()) 773 return ExprError(); 774 E = Res.get(); 775 776 QualType Ty = E->getType(); 777 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 778 779 // Half FP have to be promoted to float unless it is natively supported 780 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 781 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 782 783 // Try to perform integral promotions if the object has a theoretically 784 // promotable type. 785 if (Ty->isIntegralOrUnscopedEnumerationType()) { 786 // C99 6.3.1.1p2: 787 // 788 // The following may be used in an expression wherever an int or 789 // unsigned int may be used: 790 // - an object or expression with an integer type whose integer 791 // conversion rank is less than or equal to the rank of int 792 // and unsigned int. 793 // - A bit-field of type _Bool, int, signed int, or unsigned int. 794 // 795 // If an int can represent all values of the original type, the 796 // value is converted to an int; otherwise, it is converted to an 797 // unsigned int. These are called the integer promotions. All 798 // other types are unchanged by the integer promotions. 799 800 QualType PTy = Context.isPromotableBitField(E); 801 if (!PTy.isNull()) { 802 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 803 return E; 804 } 805 if (Ty->isPromotableIntegerType()) { 806 QualType PT = Context.getPromotedIntegerType(Ty); 807 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 808 return E; 809 } 810 } 811 return E; 812 } 813 814 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 815 /// do not have a prototype. Arguments that have type float or __fp16 816 /// are promoted to double. All other argument types are converted by 817 /// UsualUnaryConversions(). 818 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 819 QualType Ty = E->getType(); 820 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 821 822 ExprResult Res = UsualUnaryConversions(E); 823 if (Res.isInvalid()) 824 return ExprError(); 825 E = Res.get(); 826 827 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 828 // double. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) 832 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 833 834 // C++ performs lvalue-to-rvalue conversion as a default argument 835 // promotion, even on class types, but note: 836 // C++11 [conv.lval]p2: 837 // When an lvalue-to-rvalue conversion occurs in an unevaluated 838 // operand or a subexpression thereof the value contained in the 839 // referenced object is not accessed. Otherwise, if the glvalue 840 // has a class type, the conversion copy-initializes a temporary 841 // of type T from the glvalue and the result of the conversion 842 // is a prvalue for the temporary. 843 // FIXME: add some way to gate this entire thing for correctness in 844 // potentially potentially evaluated contexts. 845 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 846 ExprResult Temp = PerformCopyInitialization( 847 InitializedEntity::InitializeTemporary(E->getType()), 848 E->getExprLoc(), E); 849 if (Temp.isInvalid()) 850 return ExprError(); 851 E = Temp.get(); 852 } 853 854 return E; 855 } 856 857 /// Determine the degree of POD-ness for an expression. 858 /// Incomplete types are considered POD, since this check can be performed 859 /// when we're in an unevaluated context. 860 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 861 if (Ty->isIncompleteType()) { 862 // C++11 [expr.call]p7: 863 // After these conversions, if the argument does not have arithmetic, 864 // enumeration, pointer, pointer to member, or class type, the program 865 // is ill-formed. 866 // 867 // Since we've already performed array-to-pointer and function-to-pointer 868 // decay, the only such type in C++ is cv void. This also handles 869 // initializer lists as variadic arguments. 870 if (Ty->isVoidType()) 871 return VAK_Invalid; 872 873 if (Ty->isObjCObjectType()) 874 return VAK_Invalid; 875 return VAK_Valid; 876 } 877 878 if (Ty.isCXX98PODType(Context)) 879 return VAK_Valid; 880 881 // C++11 [expr.call]p7: 882 // Passing a potentially-evaluated argument of class type (Clause 9) 883 // having a non-trivial copy constructor, a non-trivial move constructor, 884 // or a non-trivial destructor, with no corresponding parameter, 885 // is conditionally-supported with implementation-defined semantics. 886 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 887 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 888 if (!Record->hasNonTrivialCopyConstructor() && 889 !Record->hasNonTrivialMoveConstructor() && 890 !Record->hasNonTrivialDestructor()) 891 return VAK_ValidInCXX11; 892 893 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 894 return VAK_Valid; 895 896 if (Ty->isObjCObjectType()) 897 return VAK_Invalid; 898 899 if (getLangOpts().MSVCCompat) 900 return VAK_MSVCUndefined; 901 902 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 903 // permitted to reject them. We should consider doing so. 904 return VAK_Undefined; 905 } 906 907 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 908 // Don't allow one to pass an Objective-C interface to a vararg. 909 const QualType &Ty = E->getType(); 910 VarArgKind VAK = isValidVarArgType(Ty); 911 912 // Complain about passing non-POD types through varargs. 913 switch (VAK) { 914 case VAK_ValidInCXX11: 915 DiagRuntimeBehavior( 916 E->getLocStart(), nullptr, 917 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 918 << Ty << CT); 919 // Fall through. 920 case VAK_Valid: 921 if (Ty->isRecordType()) { 922 // This is unlikely to be what the user intended. If the class has a 923 // 'c_str' member function, the user probably meant to call that. 924 DiagRuntimeBehavior(E->getLocStart(), nullptr, 925 PDiag(diag::warn_pass_class_arg_to_vararg) 926 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 927 } 928 break; 929 930 case VAK_Undefined: 931 case VAK_MSVCUndefined: 932 DiagRuntimeBehavior( 933 E->getLocStart(), nullptr, 934 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 935 << getLangOpts().CPlusPlus11 << Ty << CT); 936 break; 937 938 case VAK_Invalid: 939 if (Ty->isObjCObjectType()) 940 DiagRuntimeBehavior( 941 E->getLocStart(), nullptr, 942 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 943 << Ty << CT); 944 else 945 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 946 << isa<InitListExpr>(E) << Ty << CT; 947 break; 948 } 949 } 950 951 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 952 /// will create a trap if the resulting type is not a POD type. 953 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 954 FunctionDecl *FDecl) { 955 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 956 // Strip the unbridged-cast placeholder expression off, if applicable. 957 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 958 (CT == VariadicMethod || 959 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 960 E = stripARCUnbridgedCast(E); 961 962 // Otherwise, do normal placeholder checking. 963 } else { 964 ExprResult ExprRes = CheckPlaceholderExpr(E); 965 if (ExprRes.isInvalid()) 966 return ExprError(); 967 E = ExprRes.get(); 968 } 969 } 970 971 ExprResult ExprRes = DefaultArgumentPromotion(E); 972 if (ExprRes.isInvalid()) 973 return ExprError(); 974 E = ExprRes.get(); 975 976 // Diagnostics regarding non-POD argument types are 977 // emitted along with format string checking in Sema::CheckFunctionCall(). 978 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 979 // Turn this into a trap. 980 CXXScopeSpec SS; 981 SourceLocation TemplateKWLoc; 982 UnqualifiedId Name; 983 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 984 E->getLocStart()); 985 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 986 Name, true, false); 987 if (TrapFn.isInvalid()) 988 return ExprError(); 989 990 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 991 E->getLocStart(), None, 992 E->getLocEnd()); 993 if (Call.isInvalid()) 994 return ExprError(); 995 996 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 997 Call.get(), E); 998 if (Comma.isInvalid()) 999 return ExprError(); 1000 return Comma.get(); 1001 } 1002 1003 if (!getLangOpts().CPlusPlus && 1004 RequireCompleteType(E->getExprLoc(), E->getType(), 1005 diag::err_call_incomplete_argument)) 1006 return ExprError(); 1007 1008 return E; 1009 } 1010 1011 /// \brief Converts an integer to complex float type. Helper function of 1012 /// UsualArithmeticConversions() 1013 /// 1014 /// \return false if the integer expression is an integer type and is 1015 /// successfully converted to the complex type. 1016 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1017 ExprResult &ComplexExpr, 1018 QualType IntTy, 1019 QualType ComplexTy, 1020 bool SkipCast) { 1021 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1022 if (SkipCast) return false; 1023 if (IntTy->isIntegerType()) { 1024 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1025 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1026 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1027 CK_FloatingRealToComplex); 1028 } else { 1029 assert(IntTy->isComplexIntegerType()); 1030 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1031 CK_IntegralComplexToFloatingComplex); 1032 } 1033 return false; 1034 } 1035 1036 /// \brief Handle arithmetic conversion with complex types. Helper function of 1037 /// UsualArithmeticConversions() 1038 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1039 ExprResult &RHS, QualType LHSType, 1040 QualType RHSType, 1041 bool IsCompAssign) { 1042 // if we have an integer operand, the result is the complex type. 1043 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1044 /*skipCast*/false)) 1045 return LHSType; 1046 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1047 /*skipCast*/IsCompAssign)) 1048 return RHSType; 1049 1050 // This handles complex/complex, complex/float, or float/complex. 1051 // When both operands are complex, the shorter operand is converted to the 1052 // type of the longer, and that is the type of the result. This corresponds 1053 // to what is done when combining two real floating-point operands. 1054 // The fun begins when size promotion occur across type domains. 1055 // From H&S 6.3.4: When one operand is complex and the other is a real 1056 // floating-point type, the less precise type is converted, within it's 1057 // real or complex domain, to the precision of the other type. For example, 1058 // when combining a "long double" with a "double _Complex", the 1059 // "double _Complex" is promoted to "long double _Complex". 1060 1061 // Compute the rank of the two types, regardless of whether they are complex. 1062 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1063 1064 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1065 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1066 QualType LHSElementType = 1067 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1068 QualType RHSElementType = 1069 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1070 1071 QualType ResultType = S.Context.getComplexType(LHSElementType); 1072 if (Order < 0) { 1073 // Promote the precision of the LHS if not an assignment. 1074 ResultType = S.Context.getComplexType(RHSElementType); 1075 if (!IsCompAssign) { 1076 if (LHSComplexType) 1077 LHS = 1078 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1079 else 1080 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1081 } 1082 } else if (Order > 0) { 1083 // Promote the precision of the RHS. 1084 if (RHSComplexType) 1085 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1086 else 1087 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1088 } 1089 return ResultType; 1090 } 1091 1092 /// \brief Hande arithmetic conversion from integer to float. Helper function 1093 /// of UsualArithmeticConversions() 1094 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1095 ExprResult &IntExpr, 1096 QualType FloatTy, QualType IntTy, 1097 bool ConvertFloat, bool ConvertInt) { 1098 if (IntTy->isIntegerType()) { 1099 if (ConvertInt) 1100 // Convert intExpr to the lhs floating point type. 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1102 CK_IntegralToFloating); 1103 return FloatTy; 1104 } 1105 1106 // Convert both sides to the appropriate complex float. 1107 assert(IntTy->isComplexIntegerType()); 1108 QualType result = S.Context.getComplexType(FloatTy); 1109 1110 // _Complex int -> _Complex float 1111 if (ConvertInt) 1112 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1113 CK_IntegralComplexToFloatingComplex); 1114 1115 // float -> _Complex float 1116 if (ConvertFloat) 1117 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1118 CK_FloatingRealToComplex); 1119 1120 return result; 1121 } 1122 1123 /// \brief Handle arithmethic conversion with floating point types. Helper 1124 /// function of UsualArithmeticConversions() 1125 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1126 ExprResult &RHS, QualType LHSType, 1127 QualType RHSType, bool IsCompAssign) { 1128 bool LHSFloat = LHSType->isRealFloatingType(); 1129 bool RHSFloat = RHSType->isRealFloatingType(); 1130 1131 // If we have two real floating types, convert the smaller operand 1132 // to the bigger result. 1133 if (LHSFloat && RHSFloat) { 1134 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1135 if (order > 0) { 1136 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1137 return LHSType; 1138 } 1139 1140 assert(order < 0 && "illegal float comparison"); 1141 if (!IsCompAssign) 1142 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1143 return RHSType; 1144 } 1145 1146 if (LHSFloat) { 1147 // Half FP has to be promoted to float unless it is natively supported 1148 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1149 LHSType = S.Context.FloatTy; 1150 1151 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1152 /*convertFloat=*/!IsCompAssign, 1153 /*convertInt=*/ true); 1154 } 1155 assert(RHSFloat); 1156 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1157 /*convertInt=*/ true, 1158 /*convertFloat=*/!IsCompAssign); 1159 } 1160 1161 /// \brief Diagnose attempts to convert between __float128 and long double if 1162 /// there is no support for such conversion. Helper function of 1163 /// UsualArithmeticConversions(). 1164 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1165 QualType RHSType) { 1166 /* No issue converting if at least one of the types is not a floating point 1167 type or the two types have the same rank. 1168 */ 1169 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1170 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1171 return false; 1172 1173 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1174 "The remaining types must be floating point types."); 1175 1176 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1177 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1178 1179 QualType LHSElemType = LHSComplex ? 1180 LHSComplex->getElementType() : LHSType; 1181 QualType RHSElemType = RHSComplex ? 1182 RHSComplex->getElementType() : RHSType; 1183 1184 // No issue if the two types have the same representation 1185 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1186 &S.Context.getFloatTypeSemantics(RHSElemType)) 1187 return false; 1188 1189 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1190 RHSElemType == S.Context.LongDoubleTy); 1191 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1192 RHSElemType == S.Context.Float128Ty); 1193 1194 /* We've handled the situation where __float128 and long double have the same 1195 representation. The only other allowable conversion is if long double is 1196 really just double. 1197 */ 1198 return Float128AndLongDouble && 1199 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1200 &llvm::APFloat::IEEEdouble); 1201 } 1202 1203 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1204 1205 namespace { 1206 /// These helper callbacks are placed in an anonymous namespace to 1207 /// permit their use as function template parameters. 1208 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1209 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1210 } 1211 1212 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1213 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1214 CK_IntegralComplexCast); 1215 } 1216 } 1217 1218 /// \brief Handle integer arithmetic conversions. Helper function of 1219 /// UsualArithmeticConversions() 1220 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1221 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1222 ExprResult &RHS, QualType LHSType, 1223 QualType RHSType, bool IsCompAssign) { 1224 // The rules for this case are in C99 6.3.1.8 1225 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1226 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1227 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1228 if (LHSSigned == RHSSigned) { 1229 // Same signedness; use the higher-ranked type 1230 if (order >= 0) { 1231 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1232 return LHSType; 1233 } else if (!IsCompAssign) 1234 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1235 return RHSType; 1236 } else if (order != (LHSSigned ? 1 : -1)) { 1237 // The unsigned type has greater than or equal rank to the 1238 // signed type, so use the unsigned type 1239 if (RHSSigned) { 1240 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1241 return LHSType; 1242 } else if (!IsCompAssign) 1243 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1244 return RHSType; 1245 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1246 // The two types are different widths; if we are here, that 1247 // means the signed type is larger than the unsigned type, so 1248 // use the signed type. 1249 if (LHSSigned) { 1250 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1251 return LHSType; 1252 } else if (!IsCompAssign) 1253 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1254 return RHSType; 1255 } else { 1256 // The signed type is higher-ranked than the unsigned type, 1257 // but isn't actually any bigger (like unsigned int and long 1258 // on most 32-bit systems). Use the unsigned type corresponding 1259 // to the signed type. 1260 QualType result = 1261 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1262 RHS = (*doRHSCast)(S, RHS.get(), result); 1263 if (!IsCompAssign) 1264 LHS = (*doLHSCast)(S, LHS.get(), result); 1265 return result; 1266 } 1267 } 1268 1269 /// \brief Handle conversions with GCC complex int extension. Helper function 1270 /// of UsualArithmeticConversions() 1271 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1272 ExprResult &RHS, QualType LHSType, 1273 QualType RHSType, 1274 bool IsCompAssign) { 1275 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1276 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1277 1278 if (LHSComplexInt && RHSComplexInt) { 1279 QualType LHSEltType = LHSComplexInt->getElementType(); 1280 QualType RHSEltType = RHSComplexInt->getElementType(); 1281 QualType ScalarType = 1282 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1283 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1284 1285 return S.Context.getComplexType(ScalarType); 1286 } 1287 1288 if (LHSComplexInt) { 1289 QualType LHSEltType = LHSComplexInt->getElementType(); 1290 QualType ScalarType = 1291 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1292 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1293 QualType ComplexType = S.Context.getComplexType(ScalarType); 1294 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1295 CK_IntegralRealToComplex); 1296 1297 return ComplexType; 1298 } 1299 1300 assert(RHSComplexInt); 1301 1302 QualType RHSEltType = RHSComplexInt->getElementType(); 1303 QualType ScalarType = 1304 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1305 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1306 QualType ComplexType = S.Context.getComplexType(ScalarType); 1307 1308 if (!IsCompAssign) 1309 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1310 CK_IntegralRealToComplex); 1311 return ComplexType; 1312 } 1313 1314 /// UsualArithmeticConversions - Performs various conversions that are common to 1315 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1316 /// routine returns the first non-arithmetic type found. The client is 1317 /// responsible for emitting appropriate error diagnostics. 1318 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1319 bool IsCompAssign) { 1320 if (!IsCompAssign) { 1321 LHS = UsualUnaryConversions(LHS.get()); 1322 if (LHS.isInvalid()) 1323 return QualType(); 1324 } 1325 1326 RHS = UsualUnaryConversions(RHS.get()); 1327 if (RHS.isInvalid()) 1328 return QualType(); 1329 1330 // For conversion purposes, we ignore any qualifiers. 1331 // For example, "const float" and "float" are equivalent. 1332 QualType LHSType = 1333 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1334 QualType RHSType = 1335 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1336 1337 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1338 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1339 LHSType = AtomicLHS->getValueType(); 1340 1341 // If both types are identical, no conversion is needed. 1342 if (LHSType == RHSType) 1343 return LHSType; 1344 1345 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1346 // The caller can deal with this (e.g. pointer + int). 1347 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1348 return QualType(); 1349 1350 // Apply unary and bitfield promotions to the LHS's type. 1351 QualType LHSUnpromotedType = LHSType; 1352 if (LHSType->isPromotableIntegerType()) 1353 LHSType = Context.getPromotedIntegerType(LHSType); 1354 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1355 if (!LHSBitfieldPromoteTy.isNull()) 1356 LHSType = LHSBitfieldPromoteTy; 1357 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1358 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1359 1360 // If both types are identical, no conversion is needed. 1361 if (LHSType == RHSType) 1362 return LHSType; 1363 1364 // At this point, we have two different arithmetic types. 1365 1366 // Diagnose attempts to convert between __float128 and long double where 1367 // such conversions currently can't be handled. 1368 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1369 return QualType(); 1370 1371 // Handle complex types first (C99 6.3.1.8p1). 1372 if (LHSType->isComplexType() || RHSType->isComplexType()) 1373 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1374 IsCompAssign); 1375 1376 // Now handle "real" floating types (i.e. float, double, long double). 1377 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1378 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1379 IsCompAssign); 1380 1381 // Handle GCC complex int extension. 1382 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1383 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1384 IsCompAssign); 1385 1386 // Finally, we have two differing integer types. 1387 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1388 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1389 } 1390 1391 1392 //===----------------------------------------------------------------------===// 1393 // Semantic Analysis for various Expression Types 1394 //===----------------------------------------------------------------------===// 1395 1396 1397 ExprResult 1398 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1399 SourceLocation DefaultLoc, 1400 SourceLocation RParenLoc, 1401 Expr *ControllingExpr, 1402 ArrayRef<ParsedType> ArgTypes, 1403 ArrayRef<Expr *> ArgExprs) { 1404 unsigned NumAssocs = ArgTypes.size(); 1405 assert(NumAssocs == ArgExprs.size()); 1406 1407 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1408 for (unsigned i = 0; i < NumAssocs; ++i) { 1409 if (ArgTypes[i]) 1410 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1411 else 1412 Types[i] = nullptr; 1413 } 1414 1415 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1416 ControllingExpr, 1417 llvm::makeArrayRef(Types, NumAssocs), 1418 ArgExprs); 1419 delete [] Types; 1420 return ER; 1421 } 1422 1423 ExprResult 1424 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1425 SourceLocation DefaultLoc, 1426 SourceLocation RParenLoc, 1427 Expr *ControllingExpr, 1428 ArrayRef<TypeSourceInfo *> Types, 1429 ArrayRef<Expr *> Exprs) { 1430 unsigned NumAssocs = Types.size(); 1431 assert(NumAssocs == Exprs.size()); 1432 1433 // Decay and strip qualifiers for the controlling expression type, and handle 1434 // placeholder type replacement. See committee discussion from WG14 DR423. 1435 { 1436 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1437 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1438 if (R.isInvalid()) 1439 return ExprError(); 1440 ControllingExpr = R.get(); 1441 } 1442 1443 // The controlling expression is an unevaluated operand, so side effects are 1444 // likely unintended. 1445 if (ActiveTemplateInstantiations.empty() && 1446 ControllingExpr->HasSideEffects(Context, false)) 1447 Diag(ControllingExpr->getExprLoc(), 1448 diag::warn_side_effects_unevaluated_context); 1449 1450 bool TypeErrorFound = false, 1451 IsResultDependent = ControllingExpr->isTypeDependent(), 1452 ContainsUnexpandedParameterPack 1453 = ControllingExpr->containsUnexpandedParameterPack(); 1454 1455 for (unsigned i = 0; i < NumAssocs; ++i) { 1456 if (Exprs[i]->containsUnexpandedParameterPack()) 1457 ContainsUnexpandedParameterPack = true; 1458 1459 if (Types[i]) { 1460 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1461 ContainsUnexpandedParameterPack = true; 1462 1463 if (Types[i]->getType()->isDependentType()) { 1464 IsResultDependent = true; 1465 } else { 1466 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1467 // complete object type other than a variably modified type." 1468 unsigned D = 0; 1469 if (Types[i]->getType()->isIncompleteType()) 1470 D = diag::err_assoc_type_incomplete; 1471 else if (!Types[i]->getType()->isObjectType()) 1472 D = diag::err_assoc_type_nonobject; 1473 else if (Types[i]->getType()->isVariablyModifiedType()) 1474 D = diag::err_assoc_type_variably_modified; 1475 1476 if (D != 0) { 1477 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1478 << Types[i]->getTypeLoc().getSourceRange() 1479 << Types[i]->getType(); 1480 TypeErrorFound = true; 1481 } 1482 1483 // C11 6.5.1.1p2 "No two generic associations in the same generic 1484 // selection shall specify compatible types." 1485 for (unsigned j = i+1; j < NumAssocs; ++j) 1486 if (Types[j] && !Types[j]->getType()->isDependentType() && 1487 Context.typesAreCompatible(Types[i]->getType(), 1488 Types[j]->getType())) { 1489 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1490 diag::err_assoc_compatible_types) 1491 << Types[j]->getTypeLoc().getSourceRange() 1492 << Types[j]->getType() 1493 << Types[i]->getType(); 1494 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1495 diag::note_compat_assoc) 1496 << Types[i]->getTypeLoc().getSourceRange() 1497 << Types[i]->getType(); 1498 TypeErrorFound = true; 1499 } 1500 } 1501 } 1502 } 1503 if (TypeErrorFound) 1504 return ExprError(); 1505 1506 // If we determined that the generic selection is result-dependent, don't 1507 // try to compute the result expression. 1508 if (IsResultDependent) 1509 return new (Context) GenericSelectionExpr( 1510 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1511 ContainsUnexpandedParameterPack); 1512 1513 SmallVector<unsigned, 1> CompatIndices; 1514 unsigned DefaultIndex = -1U; 1515 for (unsigned i = 0; i < NumAssocs; ++i) { 1516 if (!Types[i]) 1517 DefaultIndex = i; 1518 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1519 Types[i]->getType())) 1520 CompatIndices.push_back(i); 1521 } 1522 1523 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1524 // type compatible with at most one of the types named in its generic 1525 // association list." 1526 if (CompatIndices.size() > 1) { 1527 // We strip parens here because the controlling expression is typically 1528 // parenthesized in macro definitions. 1529 ControllingExpr = ControllingExpr->IgnoreParens(); 1530 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1531 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1532 << (unsigned) CompatIndices.size(); 1533 for (unsigned I : CompatIndices) { 1534 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1535 diag::note_compat_assoc) 1536 << Types[I]->getTypeLoc().getSourceRange() 1537 << Types[I]->getType(); 1538 } 1539 return ExprError(); 1540 } 1541 1542 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1543 // its controlling expression shall have type compatible with exactly one of 1544 // the types named in its generic association list." 1545 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1546 // We strip parens here because the controlling expression is typically 1547 // parenthesized in macro definitions. 1548 ControllingExpr = ControllingExpr->IgnoreParens(); 1549 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1550 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1551 return ExprError(); 1552 } 1553 1554 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1555 // type name that is compatible with the type of the controlling expression, 1556 // then the result expression of the generic selection is the expression 1557 // in that generic association. Otherwise, the result expression of the 1558 // generic selection is the expression in the default generic association." 1559 unsigned ResultIndex = 1560 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1561 1562 return new (Context) GenericSelectionExpr( 1563 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1564 ContainsUnexpandedParameterPack, ResultIndex); 1565 } 1566 1567 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1568 /// location of the token and the offset of the ud-suffix within it. 1569 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1570 unsigned Offset) { 1571 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1572 S.getLangOpts()); 1573 } 1574 1575 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1576 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1577 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1578 IdentifierInfo *UDSuffix, 1579 SourceLocation UDSuffixLoc, 1580 ArrayRef<Expr*> Args, 1581 SourceLocation LitEndLoc) { 1582 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1583 1584 QualType ArgTy[2]; 1585 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1586 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1587 if (ArgTy[ArgIdx]->isArrayType()) 1588 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1589 } 1590 1591 DeclarationName OpName = 1592 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1593 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1594 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1595 1596 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1597 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1598 /*AllowRaw*/false, /*AllowTemplate*/false, 1599 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1600 return ExprError(); 1601 1602 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1603 } 1604 1605 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1606 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1607 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1608 /// multiple tokens. However, the common case is that StringToks points to one 1609 /// string. 1610 /// 1611 ExprResult 1612 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1613 assert(!StringToks.empty() && "Must have at least one string!"); 1614 1615 StringLiteralParser Literal(StringToks, PP); 1616 if (Literal.hadError) 1617 return ExprError(); 1618 1619 SmallVector<SourceLocation, 4> StringTokLocs; 1620 for (const Token &Tok : StringToks) 1621 StringTokLocs.push_back(Tok.getLocation()); 1622 1623 QualType CharTy = Context.CharTy; 1624 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1625 if (Literal.isWide()) { 1626 CharTy = Context.getWideCharType(); 1627 Kind = StringLiteral::Wide; 1628 } else if (Literal.isUTF8()) { 1629 Kind = StringLiteral::UTF8; 1630 } else if (Literal.isUTF16()) { 1631 CharTy = Context.Char16Ty; 1632 Kind = StringLiteral::UTF16; 1633 } else if (Literal.isUTF32()) { 1634 CharTy = Context.Char32Ty; 1635 Kind = StringLiteral::UTF32; 1636 } else if (Literal.isPascal()) { 1637 CharTy = Context.UnsignedCharTy; 1638 } 1639 1640 QualType CharTyConst = CharTy; 1641 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1642 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1643 CharTyConst.addConst(); 1644 1645 // Get an array type for the string, according to C99 6.4.5. This includes 1646 // the nul terminator character as well as the string length for pascal 1647 // strings. 1648 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1649 llvm::APInt(32, Literal.GetNumStringChars()+1), 1650 ArrayType::Normal, 0); 1651 1652 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1653 if (getLangOpts().OpenCL) { 1654 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1655 } 1656 1657 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1658 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1659 Kind, Literal.Pascal, StrTy, 1660 &StringTokLocs[0], 1661 StringTokLocs.size()); 1662 if (Literal.getUDSuffix().empty()) 1663 return Lit; 1664 1665 // We're building a user-defined literal. 1666 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1667 SourceLocation UDSuffixLoc = 1668 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1669 Literal.getUDSuffixOffset()); 1670 1671 // Make sure we're allowed user-defined literals here. 1672 if (!UDLScope) 1673 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1674 1675 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1676 // operator "" X (str, len) 1677 QualType SizeType = Context.getSizeType(); 1678 1679 DeclarationName OpName = 1680 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1681 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1682 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1683 1684 QualType ArgTy[] = { 1685 Context.getArrayDecayedType(StrTy), SizeType 1686 }; 1687 1688 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1689 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1690 /*AllowRaw*/false, /*AllowTemplate*/false, 1691 /*AllowStringTemplate*/true)) { 1692 1693 case LOLR_Cooked: { 1694 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1695 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1696 StringTokLocs[0]); 1697 Expr *Args[] = { Lit, LenArg }; 1698 1699 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1700 } 1701 1702 case LOLR_StringTemplate: { 1703 TemplateArgumentListInfo ExplicitArgs; 1704 1705 unsigned CharBits = Context.getIntWidth(CharTy); 1706 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1707 llvm::APSInt Value(CharBits, CharIsUnsigned); 1708 1709 TemplateArgument TypeArg(CharTy); 1710 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1711 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1712 1713 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1714 Value = Lit->getCodeUnit(I); 1715 TemplateArgument Arg(Context, Value, CharTy); 1716 TemplateArgumentLocInfo ArgInfo; 1717 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1718 } 1719 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1720 &ExplicitArgs); 1721 } 1722 case LOLR_Raw: 1723 case LOLR_Template: 1724 llvm_unreachable("unexpected literal operator lookup result"); 1725 case LOLR_Error: 1726 return ExprError(); 1727 } 1728 llvm_unreachable("unexpected literal operator lookup result"); 1729 } 1730 1731 ExprResult 1732 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1733 SourceLocation Loc, 1734 const CXXScopeSpec *SS) { 1735 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1736 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1737 } 1738 1739 /// BuildDeclRefExpr - Build an expression that references a 1740 /// declaration that does not require a closure capture. 1741 ExprResult 1742 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1743 const DeclarationNameInfo &NameInfo, 1744 const CXXScopeSpec *SS, NamedDecl *FoundD, 1745 const TemplateArgumentListInfo *TemplateArgs) { 1746 if (getLangOpts().CUDA) 1747 if (FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) 1748 if (!CheckCUDACall(NameInfo.getLoc(), Callee)) 1749 return ExprError(); 1750 1751 bool RefersToCapturedVariable = 1752 isa<VarDecl>(D) && 1753 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1754 1755 DeclRefExpr *E; 1756 if (isa<VarTemplateSpecializationDecl>(D)) { 1757 VarTemplateSpecializationDecl *VarSpec = 1758 cast<VarTemplateSpecializationDecl>(D); 1759 1760 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1761 : NestedNameSpecifierLoc(), 1762 VarSpec->getTemplateKeywordLoc(), D, 1763 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1764 FoundD, TemplateArgs); 1765 } else { 1766 assert(!TemplateArgs && "No template arguments for non-variable" 1767 " template specialization references"); 1768 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1769 : NestedNameSpecifierLoc(), 1770 SourceLocation(), D, RefersToCapturedVariable, 1771 NameInfo, Ty, VK, FoundD); 1772 } 1773 1774 MarkDeclRefReferenced(E); 1775 1776 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1777 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1778 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1779 recordUseOfEvaluatedWeak(E); 1780 1781 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1782 UnusedPrivateFields.remove(FD); 1783 // Just in case we're building an illegal pointer-to-member. 1784 if (FD->isBitField()) 1785 E->setObjectKind(OK_BitField); 1786 } 1787 1788 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1789 // designates a bit-field. 1790 if (auto *BD = dyn_cast<BindingDecl>(D)) 1791 if (auto *BE = BD->getBinding()) 1792 E->setObjectKind(BE->getObjectKind()); 1793 1794 return E; 1795 } 1796 1797 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1798 /// possibly a list of template arguments. 1799 /// 1800 /// If this produces template arguments, it is permitted to call 1801 /// DecomposeTemplateName. 1802 /// 1803 /// This actually loses a lot of source location information for 1804 /// non-standard name kinds; we should consider preserving that in 1805 /// some way. 1806 void 1807 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1808 TemplateArgumentListInfo &Buffer, 1809 DeclarationNameInfo &NameInfo, 1810 const TemplateArgumentListInfo *&TemplateArgs) { 1811 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1812 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1813 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1814 1815 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1816 Id.TemplateId->NumArgs); 1817 translateTemplateArguments(TemplateArgsPtr, Buffer); 1818 1819 TemplateName TName = Id.TemplateId->Template.get(); 1820 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1821 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1822 TemplateArgs = &Buffer; 1823 } else { 1824 NameInfo = GetNameFromUnqualifiedId(Id); 1825 TemplateArgs = nullptr; 1826 } 1827 } 1828 1829 static void emitEmptyLookupTypoDiagnostic( 1830 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1831 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1832 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1833 DeclContext *Ctx = 1834 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1835 if (!TC) { 1836 // Emit a special diagnostic for failed member lookups. 1837 // FIXME: computing the declaration context might fail here (?) 1838 if (Ctx) 1839 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1840 << SS.getRange(); 1841 else 1842 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1843 return; 1844 } 1845 1846 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1847 bool DroppedSpecifier = 1848 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1849 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1850 ? diag::note_implicit_param_decl 1851 : diag::note_previous_decl; 1852 if (!Ctx) 1853 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1854 SemaRef.PDiag(NoteID)); 1855 else 1856 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1857 << Typo << Ctx << DroppedSpecifier 1858 << SS.getRange(), 1859 SemaRef.PDiag(NoteID)); 1860 } 1861 1862 /// Diagnose an empty lookup. 1863 /// 1864 /// \return false if new lookup candidates were found 1865 bool 1866 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1867 std::unique_ptr<CorrectionCandidateCallback> CCC, 1868 TemplateArgumentListInfo *ExplicitTemplateArgs, 1869 ArrayRef<Expr *> Args, TypoExpr **Out) { 1870 DeclarationName Name = R.getLookupName(); 1871 1872 unsigned diagnostic = diag::err_undeclared_var_use; 1873 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1874 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1875 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1876 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1877 diagnostic = diag::err_undeclared_use; 1878 diagnostic_suggest = diag::err_undeclared_use_suggest; 1879 } 1880 1881 // If the original lookup was an unqualified lookup, fake an 1882 // unqualified lookup. This is useful when (for example) the 1883 // original lookup would not have found something because it was a 1884 // dependent name. 1885 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1886 while (DC) { 1887 if (isa<CXXRecordDecl>(DC)) { 1888 LookupQualifiedName(R, DC); 1889 1890 if (!R.empty()) { 1891 // Don't give errors about ambiguities in this lookup. 1892 R.suppressDiagnostics(); 1893 1894 // During a default argument instantiation the CurContext points 1895 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1896 // function parameter list, hence add an explicit check. 1897 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1898 ActiveTemplateInstantiations.back().Kind == 1899 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1900 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1901 bool isInstance = CurMethod && 1902 CurMethod->isInstance() && 1903 DC == CurMethod->getParent() && !isDefaultArgument; 1904 1905 // Give a code modification hint to insert 'this->'. 1906 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1907 // Actually quite difficult! 1908 if (getLangOpts().MSVCCompat) 1909 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1910 if (isInstance) { 1911 Diag(R.getNameLoc(), diagnostic) << Name 1912 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1913 CheckCXXThisCapture(R.getNameLoc()); 1914 } else { 1915 Diag(R.getNameLoc(), diagnostic) << Name; 1916 } 1917 1918 // Do we really want to note all of these? 1919 for (NamedDecl *D : R) 1920 Diag(D->getLocation(), diag::note_dependent_var_use); 1921 1922 // Return true if we are inside a default argument instantiation 1923 // and the found name refers to an instance member function, otherwise 1924 // the function calling DiagnoseEmptyLookup will try to create an 1925 // implicit member call and this is wrong for default argument. 1926 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1927 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1928 return true; 1929 } 1930 1931 // Tell the callee to try to recover. 1932 return false; 1933 } 1934 1935 R.clear(); 1936 } 1937 1938 // In Microsoft mode, if we are performing lookup from within a friend 1939 // function definition declared at class scope then we must set 1940 // DC to the lexical parent to be able to search into the parent 1941 // class. 1942 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1943 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1944 DC->getLexicalParent()->isRecord()) 1945 DC = DC->getLexicalParent(); 1946 else 1947 DC = DC->getParent(); 1948 } 1949 1950 // We didn't find anything, so try to correct for a typo. 1951 TypoCorrection Corrected; 1952 if (S && Out) { 1953 SourceLocation TypoLoc = R.getNameLoc(); 1954 assert(!ExplicitTemplateArgs && 1955 "Diagnosing an empty lookup with explicit template args!"); 1956 *Out = CorrectTypoDelayed( 1957 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1958 [=](const TypoCorrection &TC) { 1959 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1960 diagnostic, diagnostic_suggest); 1961 }, 1962 nullptr, CTK_ErrorRecovery); 1963 if (*Out) 1964 return true; 1965 } else if (S && (Corrected = 1966 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1967 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1968 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1969 bool DroppedSpecifier = 1970 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1971 R.setLookupName(Corrected.getCorrection()); 1972 1973 bool AcceptableWithRecovery = false; 1974 bool AcceptableWithoutRecovery = false; 1975 NamedDecl *ND = Corrected.getFoundDecl(); 1976 if (ND) { 1977 if (Corrected.isOverloaded()) { 1978 OverloadCandidateSet OCS(R.getNameLoc(), 1979 OverloadCandidateSet::CSK_Normal); 1980 OverloadCandidateSet::iterator Best; 1981 for (NamedDecl *CD : Corrected) { 1982 if (FunctionTemplateDecl *FTD = 1983 dyn_cast<FunctionTemplateDecl>(CD)) 1984 AddTemplateOverloadCandidate( 1985 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1986 Args, OCS); 1987 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1988 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1989 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1990 Args, OCS); 1991 } 1992 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1993 case OR_Success: 1994 ND = Best->FoundDecl; 1995 Corrected.setCorrectionDecl(ND); 1996 break; 1997 default: 1998 // FIXME: Arbitrarily pick the first declaration for the note. 1999 Corrected.setCorrectionDecl(ND); 2000 break; 2001 } 2002 } 2003 R.addDecl(ND); 2004 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2005 CXXRecordDecl *Record = nullptr; 2006 if (Corrected.getCorrectionSpecifier()) { 2007 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2008 Record = Ty->getAsCXXRecordDecl(); 2009 } 2010 if (!Record) 2011 Record = cast<CXXRecordDecl>( 2012 ND->getDeclContext()->getRedeclContext()); 2013 R.setNamingClass(Record); 2014 } 2015 2016 auto *UnderlyingND = ND->getUnderlyingDecl(); 2017 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2018 isa<FunctionTemplateDecl>(UnderlyingND); 2019 // FIXME: If we ended up with a typo for a type name or 2020 // Objective-C class name, we're in trouble because the parser 2021 // is in the wrong place to recover. Suggest the typo 2022 // correction, but don't make it a fix-it since we're not going 2023 // to recover well anyway. 2024 AcceptableWithoutRecovery = 2025 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2026 } else { 2027 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2028 // because we aren't able to recover. 2029 AcceptableWithoutRecovery = true; 2030 } 2031 2032 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2033 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2034 ? diag::note_implicit_param_decl 2035 : diag::note_previous_decl; 2036 if (SS.isEmpty()) 2037 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2038 PDiag(NoteID), AcceptableWithRecovery); 2039 else 2040 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2041 << Name << computeDeclContext(SS, false) 2042 << DroppedSpecifier << SS.getRange(), 2043 PDiag(NoteID), AcceptableWithRecovery); 2044 2045 // Tell the callee whether to try to recover. 2046 return !AcceptableWithRecovery; 2047 } 2048 } 2049 R.clear(); 2050 2051 // Emit a special diagnostic for failed member lookups. 2052 // FIXME: computing the declaration context might fail here (?) 2053 if (!SS.isEmpty()) { 2054 Diag(R.getNameLoc(), diag::err_no_member) 2055 << Name << computeDeclContext(SS, false) 2056 << SS.getRange(); 2057 return true; 2058 } 2059 2060 // Give up, we can't recover. 2061 Diag(R.getNameLoc(), diagnostic) << Name; 2062 return true; 2063 } 2064 2065 /// In Microsoft mode, if we are inside a template class whose parent class has 2066 /// dependent base classes, and we can't resolve an unqualified identifier, then 2067 /// assume the identifier is a member of a dependent base class. We can only 2068 /// recover successfully in static methods, instance methods, and other contexts 2069 /// where 'this' is available. This doesn't precisely match MSVC's 2070 /// instantiation model, but it's close enough. 2071 static Expr * 2072 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2073 DeclarationNameInfo &NameInfo, 2074 SourceLocation TemplateKWLoc, 2075 const TemplateArgumentListInfo *TemplateArgs) { 2076 // Only try to recover from lookup into dependent bases in static methods or 2077 // contexts where 'this' is available. 2078 QualType ThisType = S.getCurrentThisType(); 2079 const CXXRecordDecl *RD = nullptr; 2080 if (!ThisType.isNull()) 2081 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2082 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2083 RD = MD->getParent(); 2084 if (!RD || !RD->hasAnyDependentBases()) 2085 return nullptr; 2086 2087 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2088 // is available, suggest inserting 'this->' as a fixit. 2089 SourceLocation Loc = NameInfo.getLoc(); 2090 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2091 DB << NameInfo.getName() << RD; 2092 2093 if (!ThisType.isNull()) { 2094 DB << FixItHint::CreateInsertion(Loc, "this->"); 2095 return CXXDependentScopeMemberExpr::Create( 2096 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2097 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2098 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2099 } 2100 2101 // Synthesize a fake NNS that points to the derived class. This will 2102 // perform name lookup during template instantiation. 2103 CXXScopeSpec SS; 2104 auto *NNS = 2105 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2106 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2107 return DependentScopeDeclRefExpr::Create( 2108 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2109 TemplateArgs); 2110 } 2111 2112 ExprResult 2113 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2114 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2115 bool HasTrailingLParen, bool IsAddressOfOperand, 2116 std::unique_ptr<CorrectionCandidateCallback> CCC, 2117 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2118 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2119 "cannot be direct & operand and have a trailing lparen"); 2120 if (SS.isInvalid()) 2121 return ExprError(); 2122 2123 TemplateArgumentListInfo TemplateArgsBuffer; 2124 2125 // Decompose the UnqualifiedId into the following data. 2126 DeclarationNameInfo NameInfo; 2127 const TemplateArgumentListInfo *TemplateArgs; 2128 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2129 2130 DeclarationName Name = NameInfo.getName(); 2131 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2132 SourceLocation NameLoc = NameInfo.getLoc(); 2133 2134 // C++ [temp.dep.expr]p3: 2135 // An id-expression is type-dependent if it contains: 2136 // -- an identifier that was declared with a dependent type, 2137 // (note: handled after lookup) 2138 // -- a template-id that is dependent, 2139 // (note: handled in BuildTemplateIdExpr) 2140 // -- a conversion-function-id that specifies a dependent type, 2141 // -- a nested-name-specifier that contains a class-name that 2142 // names a dependent type. 2143 // Determine whether this is a member of an unknown specialization; 2144 // we need to handle these differently. 2145 bool DependentID = false; 2146 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2147 Name.getCXXNameType()->isDependentType()) { 2148 DependentID = true; 2149 } else if (SS.isSet()) { 2150 if (DeclContext *DC = computeDeclContext(SS, false)) { 2151 if (RequireCompleteDeclContext(SS, DC)) 2152 return ExprError(); 2153 } else { 2154 DependentID = true; 2155 } 2156 } 2157 2158 if (DependentID) 2159 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2160 IsAddressOfOperand, TemplateArgs); 2161 2162 // Perform the required lookup. 2163 LookupResult R(*this, NameInfo, 2164 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2165 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2166 if (TemplateArgs) { 2167 // Lookup the template name again to correctly establish the context in 2168 // which it was found. This is really unfortunate as we already did the 2169 // lookup to determine that it was a template name in the first place. If 2170 // this becomes a performance hit, we can work harder to preserve those 2171 // results until we get here but it's likely not worth it. 2172 bool MemberOfUnknownSpecialization; 2173 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2174 MemberOfUnknownSpecialization); 2175 2176 if (MemberOfUnknownSpecialization || 2177 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2178 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2179 IsAddressOfOperand, TemplateArgs); 2180 } else { 2181 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2182 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2183 2184 // If the result might be in a dependent base class, this is a dependent 2185 // id-expression. 2186 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2187 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2188 IsAddressOfOperand, TemplateArgs); 2189 2190 // If this reference is in an Objective-C method, then we need to do 2191 // some special Objective-C lookup, too. 2192 if (IvarLookupFollowUp) { 2193 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2194 if (E.isInvalid()) 2195 return ExprError(); 2196 2197 if (Expr *Ex = E.getAs<Expr>()) 2198 return Ex; 2199 } 2200 } 2201 2202 if (R.isAmbiguous()) 2203 return ExprError(); 2204 2205 // This could be an implicitly declared function reference (legal in C90, 2206 // extension in C99, forbidden in C++). 2207 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2208 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2209 if (D) R.addDecl(D); 2210 } 2211 2212 // Determine whether this name might be a candidate for 2213 // argument-dependent lookup. 2214 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2215 2216 if (R.empty() && !ADL) { 2217 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2218 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2219 TemplateKWLoc, TemplateArgs)) 2220 return E; 2221 } 2222 2223 // Don't diagnose an empty lookup for inline assembly. 2224 if (IsInlineAsmIdentifier) 2225 return ExprError(); 2226 2227 // If this name wasn't predeclared and if this is not a function 2228 // call, diagnose the problem. 2229 TypoExpr *TE = nullptr; 2230 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2231 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2232 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2233 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2234 "Typo correction callback misconfigured"); 2235 if (CCC) { 2236 // Make sure the callback knows what the typo being diagnosed is. 2237 CCC->setTypoName(II); 2238 if (SS.isValid()) 2239 CCC->setTypoNNS(SS.getScopeRep()); 2240 } 2241 if (DiagnoseEmptyLookup(S, SS, R, 2242 CCC ? std::move(CCC) : std::move(DefaultValidator), 2243 nullptr, None, &TE)) { 2244 if (TE && KeywordReplacement) { 2245 auto &State = getTypoExprState(TE); 2246 auto BestTC = State.Consumer->getNextCorrection(); 2247 if (BestTC.isKeyword()) { 2248 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2249 if (State.DiagHandler) 2250 State.DiagHandler(BestTC); 2251 KeywordReplacement->startToken(); 2252 KeywordReplacement->setKind(II->getTokenID()); 2253 KeywordReplacement->setIdentifierInfo(II); 2254 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2255 // Clean up the state associated with the TypoExpr, since it has 2256 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2257 clearDelayedTypo(TE); 2258 // Signal that a correction to a keyword was performed by returning a 2259 // valid-but-null ExprResult. 2260 return (Expr*)nullptr; 2261 } 2262 State.Consumer->resetCorrectionStream(); 2263 } 2264 return TE ? TE : ExprError(); 2265 } 2266 2267 assert(!R.empty() && 2268 "DiagnoseEmptyLookup returned false but added no results"); 2269 2270 // If we found an Objective-C instance variable, let 2271 // LookupInObjCMethod build the appropriate expression to 2272 // reference the ivar. 2273 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2274 R.clear(); 2275 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2276 // In a hopelessly buggy code, Objective-C instance variable 2277 // lookup fails and no expression will be built to reference it. 2278 if (!E.isInvalid() && !E.get()) 2279 return ExprError(); 2280 return E; 2281 } 2282 } 2283 2284 // This is guaranteed from this point on. 2285 assert(!R.empty() || ADL); 2286 2287 // Check whether this might be a C++ implicit instance member access. 2288 // C++ [class.mfct.non-static]p3: 2289 // When an id-expression that is not part of a class member access 2290 // syntax and not used to form a pointer to member is used in the 2291 // body of a non-static member function of class X, if name lookup 2292 // resolves the name in the id-expression to a non-static non-type 2293 // member of some class C, the id-expression is transformed into a 2294 // class member access expression using (*this) as the 2295 // postfix-expression to the left of the . operator. 2296 // 2297 // But we don't actually need to do this for '&' operands if R 2298 // resolved to a function or overloaded function set, because the 2299 // expression is ill-formed if it actually works out to be a 2300 // non-static member function: 2301 // 2302 // C++ [expr.ref]p4: 2303 // Otherwise, if E1.E2 refers to a non-static member function. . . 2304 // [t]he expression can be used only as the left-hand operand of a 2305 // member function call. 2306 // 2307 // There are other safeguards against such uses, but it's important 2308 // to get this right here so that we don't end up making a 2309 // spuriously dependent expression if we're inside a dependent 2310 // instance method. 2311 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2312 bool MightBeImplicitMember; 2313 if (!IsAddressOfOperand) 2314 MightBeImplicitMember = true; 2315 else if (!SS.isEmpty()) 2316 MightBeImplicitMember = false; 2317 else if (R.isOverloadedResult()) 2318 MightBeImplicitMember = false; 2319 else if (R.isUnresolvableResult()) 2320 MightBeImplicitMember = true; 2321 else 2322 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2323 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2324 isa<MSPropertyDecl>(R.getFoundDecl()); 2325 2326 if (MightBeImplicitMember) 2327 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2328 R, TemplateArgs, S); 2329 } 2330 2331 if (TemplateArgs || TemplateKWLoc.isValid()) { 2332 2333 // In C++1y, if this is a variable template id, then check it 2334 // in BuildTemplateIdExpr(). 2335 // The single lookup result must be a variable template declaration. 2336 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2337 Id.TemplateId->Kind == TNK_Var_template) { 2338 assert(R.getAsSingle<VarTemplateDecl>() && 2339 "There should only be one declaration found."); 2340 } 2341 2342 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2343 } 2344 2345 return BuildDeclarationNameExpr(SS, R, ADL); 2346 } 2347 2348 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2349 /// declaration name, generally during template instantiation. 2350 /// There's a large number of things which don't need to be done along 2351 /// this path. 2352 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2353 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2354 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2355 DeclContext *DC = computeDeclContext(SS, false); 2356 if (!DC) 2357 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2358 NameInfo, /*TemplateArgs=*/nullptr); 2359 2360 if (RequireCompleteDeclContext(SS, DC)) 2361 return ExprError(); 2362 2363 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2364 LookupQualifiedName(R, DC); 2365 2366 if (R.isAmbiguous()) 2367 return ExprError(); 2368 2369 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2370 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2371 NameInfo, /*TemplateArgs=*/nullptr); 2372 2373 if (R.empty()) { 2374 Diag(NameInfo.getLoc(), diag::err_no_member) 2375 << NameInfo.getName() << DC << SS.getRange(); 2376 return ExprError(); 2377 } 2378 2379 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2380 // Diagnose a missing typename if this resolved unambiguously to a type in 2381 // a dependent context. If we can recover with a type, downgrade this to 2382 // a warning in Microsoft compatibility mode. 2383 unsigned DiagID = diag::err_typename_missing; 2384 if (RecoveryTSI && getLangOpts().MSVCCompat) 2385 DiagID = diag::ext_typename_missing; 2386 SourceLocation Loc = SS.getBeginLoc(); 2387 auto D = Diag(Loc, DiagID); 2388 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2389 << SourceRange(Loc, NameInfo.getEndLoc()); 2390 2391 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2392 // context. 2393 if (!RecoveryTSI) 2394 return ExprError(); 2395 2396 // Only issue the fixit if we're prepared to recover. 2397 D << FixItHint::CreateInsertion(Loc, "typename "); 2398 2399 // Recover by pretending this was an elaborated type. 2400 QualType Ty = Context.getTypeDeclType(TD); 2401 TypeLocBuilder TLB; 2402 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2403 2404 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2405 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2406 QTL.setElaboratedKeywordLoc(SourceLocation()); 2407 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2408 2409 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2410 2411 return ExprEmpty(); 2412 } 2413 2414 // Defend against this resolving to an implicit member access. We usually 2415 // won't get here if this might be a legitimate a class member (we end up in 2416 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2417 // a pointer-to-member or in an unevaluated context in C++11. 2418 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2419 return BuildPossibleImplicitMemberExpr(SS, 2420 /*TemplateKWLoc=*/SourceLocation(), 2421 R, /*TemplateArgs=*/nullptr, S); 2422 2423 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2424 } 2425 2426 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2427 /// detected that we're currently inside an ObjC method. Perform some 2428 /// additional lookup. 2429 /// 2430 /// Ideally, most of this would be done by lookup, but there's 2431 /// actually quite a lot of extra work involved. 2432 /// 2433 /// Returns a null sentinel to indicate trivial success. 2434 ExprResult 2435 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2436 IdentifierInfo *II, bool AllowBuiltinCreation) { 2437 SourceLocation Loc = Lookup.getNameLoc(); 2438 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2439 2440 // Check for error condition which is already reported. 2441 if (!CurMethod) 2442 return ExprError(); 2443 2444 // There are two cases to handle here. 1) scoped lookup could have failed, 2445 // in which case we should look for an ivar. 2) scoped lookup could have 2446 // found a decl, but that decl is outside the current instance method (i.e. 2447 // a global variable). In these two cases, we do a lookup for an ivar with 2448 // this name, if the lookup sucedes, we replace it our current decl. 2449 2450 // If we're in a class method, we don't normally want to look for 2451 // ivars. But if we don't find anything else, and there's an 2452 // ivar, that's an error. 2453 bool IsClassMethod = CurMethod->isClassMethod(); 2454 2455 bool LookForIvars; 2456 if (Lookup.empty()) 2457 LookForIvars = true; 2458 else if (IsClassMethod) 2459 LookForIvars = false; 2460 else 2461 LookForIvars = (Lookup.isSingleResult() && 2462 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2463 ObjCInterfaceDecl *IFace = nullptr; 2464 if (LookForIvars) { 2465 IFace = CurMethod->getClassInterface(); 2466 ObjCInterfaceDecl *ClassDeclared; 2467 ObjCIvarDecl *IV = nullptr; 2468 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2469 // Diagnose using an ivar in a class method. 2470 if (IsClassMethod) 2471 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2472 << IV->getDeclName()); 2473 2474 // If we're referencing an invalid decl, just return this as a silent 2475 // error node. The error diagnostic was already emitted on the decl. 2476 if (IV->isInvalidDecl()) 2477 return ExprError(); 2478 2479 // Check if referencing a field with __attribute__((deprecated)). 2480 if (DiagnoseUseOfDecl(IV, Loc)) 2481 return ExprError(); 2482 2483 // Diagnose the use of an ivar outside of the declaring class. 2484 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2485 !declaresSameEntity(ClassDeclared, IFace) && 2486 !getLangOpts().DebuggerSupport) 2487 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2488 2489 // FIXME: This should use a new expr for a direct reference, don't 2490 // turn this into Self->ivar, just return a BareIVarExpr or something. 2491 IdentifierInfo &II = Context.Idents.get("self"); 2492 UnqualifiedId SelfName; 2493 SelfName.setIdentifier(&II, SourceLocation()); 2494 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2495 CXXScopeSpec SelfScopeSpec; 2496 SourceLocation TemplateKWLoc; 2497 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2498 SelfName, false, false); 2499 if (SelfExpr.isInvalid()) 2500 return ExprError(); 2501 2502 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2503 if (SelfExpr.isInvalid()) 2504 return ExprError(); 2505 2506 MarkAnyDeclReferenced(Loc, IV, true); 2507 2508 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2509 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2510 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2511 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2512 2513 ObjCIvarRefExpr *Result = new (Context) 2514 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2515 IV->getLocation(), SelfExpr.get(), true, true); 2516 2517 if (getLangOpts().ObjCAutoRefCount) { 2518 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2519 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2520 recordUseOfEvaluatedWeak(Result); 2521 } 2522 if (CurContext->isClosure()) 2523 Diag(Loc, diag::warn_implicitly_retains_self) 2524 << FixItHint::CreateInsertion(Loc, "self->"); 2525 } 2526 2527 return Result; 2528 } 2529 } else if (CurMethod->isInstanceMethod()) { 2530 // We should warn if a local variable hides an ivar. 2531 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2532 ObjCInterfaceDecl *ClassDeclared; 2533 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2534 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2535 declaresSameEntity(IFace, ClassDeclared)) 2536 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2537 } 2538 } 2539 } else if (Lookup.isSingleResult() && 2540 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2541 // If accessing a stand-alone ivar in a class method, this is an error. 2542 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2543 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2544 << IV->getDeclName()); 2545 } 2546 2547 if (Lookup.empty() && II && AllowBuiltinCreation) { 2548 // FIXME. Consolidate this with similar code in LookupName. 2549 if (unsigned BuiltinID = II->getBuiltinID()) { 2550 if (!(getLangOpts().CPlusPlus && 2551 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2552 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2553 S, Lookup.isForRedeclaration(), 2554 Lookup.getNameLoc()); 2555 if (D) Lookup.addDecl(D); 2556 } 2557 } 2558 } 2559 // Sentinel value saying that we didn't do anything special. 2560 return ExprResult((Expr *)nullptr); 2561 } 2562 2563 /// \brief Cast a base object to a member's actual type. 2564 /// 2565 /// Logically this happens in three phases: 2566 /// 2567 /// * First we cast from the base type to the naming class. 2568 /// The naming class is the class into which we were looking 2569 /// when we found the member; it's the qualifier type if a 2570 /// qualifier was provided, and otherwise it's the base type. 2571 /// 2572 /// * Next we cast from the naming class to the declaring class. 2573 /// If the member we found was brought into a class's scope by 2574 /// a using declaration, this is that class; otherwise it's 2575 /// the class declaring the member. 2576 /// 2577 /// * Finally we cast from the declaring class to the "true" 2578 /// declaring class of the member. This conversion does not 2579 /// obey access control. 2580 ExprResult 2581 Sema::PerformObjectMemberConversion(Expr *From, 2582 NestedNameSpecifier *Qualifier, 2583 NamedDecl *FoundDecl, 2584 NamedDecl *Member) { 2585 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2586 if (!RD) 2587 return From; 2588 2589 QualType DestRecordType; 2590 QualType DestType; 2591 QualType FromRecordType; 2592 QualType FromType = From->getType(); 2593 bool PointerConversions = false; 2594 if (isa<FieldDecl>(Member)) { 2595 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2596 2597 if (FromType->getAs<PointerType>()) { 2598 DestType = Context.getPointerType(DestRecordType); 2599 FromRecordType = FromType->getPointeeType(); 2600 PointerConversions = true; 2601 } else { 2602 DestType = DestRecordType; 2603 FromRecordType = FromType; 2604 } 2605 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2606 if (Method->isStatic()) 2607 return From; 2608 2609 DestType = Method->getThisType(Context); 2610 DestRecordType = DestType->getPointeeType(); 2611 2612 if (FromType->getAs<PointerType>()) { 2613 FromRecordType = FromType->getPointeeType(); 2614 PointerConversions = true; 2615 } else { 2616 FromRecordType = FromType; 2617 DestType = DestRecordType; 2618 } 2619 } else { 2620 // No conversion necessary. 2621 return From; 2622 } 2623 2624 if (DestType->isDependentType() || FromType->isDependentType()) 2625 return From; 2626 2627 // If the unqualified types are the same, no conversion is necessary. 2628 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2629 return From; 2630 2631 SourceRange FromRange = From->getSourceRange(); 2632 SourceLocation FromLoc = FromRange.getBegin(); 2633 2634 ExprValueKind VK = From->getValueKind(); 2635 2636 // C++ [class.member.lookup]p8: 2637 // [...] Ambiguities can often be resolved by qualifying a name with its 2638 // class name. 2639 // 2640 // If the member was a qualified name and the qualified referred to a 2641 // specific base subobject type, we'll cast to that intermediate type 2642 // first and then to the object in which the member is declared. That allows 2643 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2644 // 2645 // class Base { public: int x; }; 2646 // class Derived1 : public Base { }; 2647 // class Derived2 : public Base { }; 2648 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2649 // 2650 // void VeryDerived::f() { 2651 // x = 17; // error: ambiguous base subobjects 2652 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2653 // } 2654 if (Qualifier && Qualifier->getAsType()) { 2655 QualType QType = QualType(Qualifier->getAsType(), 0); 2656 assert(QType->isRecordType() && "lookup done with non-record type"); 2657 2658 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2659 2660 // In C++98, the qualifier type doesn't actually have to be a base 2661 // type of the object type, in which case we just ignore it. 2662 // Otherwise build the appropriate casts. 2663 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2664 CXXCastPath BasePath; 2665 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2666 FromLoc, FromRange, &BasePath)) 2667 return ExprError(); 2668 2669 if (PointerConversions) 2670 QType = Context.getPointerType(QType); 2671 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2672 VK, &BasePath).get(); 2673 2674 FromType = QType; 2675 FromRecordType = QRecordType; 2676 2677 // If the qualifier type was the same as the destination type, 2678 // we're done. 2679 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2680 return From; 2681 } 2682 } 2683 2684 bool IgnoreAccess = false; 2685 2686 // If we actually found the member through a using declaration, cast 2687 // down to the using declaration's type. 2688 // 2689 // Pointer equality is fine here because only one declaration of a 2690 // class ever has member declarations. 2691 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2692 assert(isa<UsingShadowDecl>(FoundDecl)); 2693 QualType URecordType = Context.getTypeDeclType( 2694 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2695 2696 // We only need to do this if the naming-class to declaring-class 2697 // conversion is non-trivial. 2698 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2699 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2700 CXXCastPath BasePath; 2701 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2702 FromLoc, FromRange, &BasePath)) 2703 return ExprError(); 2704 2705 QualType UType = URecordType; 2706 if (PointerConversions) 2707 UType = Context.getPointerType(UType); 2708 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2709 VK, &BasePath).get(); 2710 FromType = UType; 2711 FromRecordType = URecordType; 2712 } 2713 2714 // We don't do access control for the conversion from the 2715 // declaring class to the true declaring class. 2716 IgnoreAccess = true; 2717 } 2718 2719 CXXCastPath BasePath; 2720 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2721 FromLoc, FromRange, &BasePath, 2722 IgnoreAccess)) 2723 return ExprError(); 2724 2725 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2726 VK, &BasePath); 2727 } 2728 2729 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2730 const LookupResult &R, 2731 bool HasTrailingLParen) { 2732 // Only when used directly as the postfix-expression of a call. 2733 if (!HasTrailingLParen) 2734 return false; 2735 2736 // Never if a scope specifier was provided. 2737 if (SS.isSet()) 2738 return false; 2739 2740 // Only in C++ or ObjC++. 2741 if (!getLangOpts().CPlusPlus) 2742 return false; 2743 2744 // Turn off ADL when we find certain kinds of declarations during 2745 // normal lookup: 2746 for (NamedDecl *D : R) { 2747 // C++0x [basic.lookup.argdep]p3: 2748 // -- a declaration of a class member 2749 // Since using decls preserve this property, we check this on the 2750 // original decl. 2751 if (D->isCXXClassMember()) 2752 return false; 2753 2754 // C++0x [basic.lookup.argdep]p3: 2755 // -- a block-scope function declaration that is not a 2756 // using-declaration 2757 // NOTE: we also trigger this for function templates (in fact, we 2758 // don't check the decl type at all, since all other decl types 2759 // turn off ADL anyway). 2760 if (isa<UsingShadowDecl>(D)) 2761 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2762 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2763 return false; 2764 2765 // C++0x [basic.lookup.argdep]p3: 2766 // -- a declaration that is neither a function or a function 2767 // template 2768 // And also for builtin functions. 2769 if (isa<FunctionDecl>(D)) { 2770 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2771 2772 // But also builtin functions. 2773 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2774 return false; 2775 } else if (!isa<FunctionTemplateDecl>(D)) 2776 return false; 2777 } 2778 2779 return true; 2780 } 2781 2782 2783 /// Diagnoses obvious problems with the use of the given declaration 2784 /// as an expression. This is only actually called for lookups that 2785 /// were not overloaded, and it doesn't promise that the declaration 2786 /// will in fact be used. 2787 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2788 if (isa<TypedefNameDecl>(D)) { 2789 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2790 return true; 2791 } 2792 2793 if (isa<ObjCInterfaceDecl>(D)) { 2794 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2795 return true; 2796 } 2797 2798 if (isa<NamespaceDecl>(D)) { 2799 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2800 return true; 2801 } 2802 2803 return false; 2804 } 2805 2806 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2807 LookupResult &R, bool NeedsADL, 2808 bool AcceptInvalidDecl) { 2809 // If this is a single, fully-resolved result and we don't need ADL, 2810 // just build an ordinary singleton decl ref. 2811 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2812 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2813 R.getRepresentativeDecl(), nullptr, 2814 AcceptInvalidDecl); 2815 2816 // We only need to check the declaration if there's exactly one 2817 // result, because in the overloaded case the results can only be 2818 // functions and function templates. 2819 if (R.isSingleResult() && 2820 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2821 return ExprError(); 2822 2823 // Otherwise, just build an unresolved lookup expression. Suppress 2824 // any lookup-related diagnostics; we'll hash these out later, when 2825 // we've picked a target. 2826 R.suppressDiagnostics(); 2827 2828 UnresolvedLookupExpr *ULE 2829 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2830 SS.getWithLocInContext(Context), 2831 R.getLookupNameInfo(), 2832 NeedsADL, R.isOverloadedResult(), 2833 R.begin(), R.end()); 2834 2835 return ULE; 2836 } 2837 2838 static void 2839 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2840 ValueDecl *var, DeclContext *DC); 2841 2842 /// \brief Complete semantic analysis for a reference to the given declaration. 2843 ExprResult Sema::BuildDeclarationNameExpr( 2844 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2845 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2846 bool AcceptInvalidDecl) { 2847 assert(D && "Cannot refer to a NULL declaration"); 2848 assert(!isa<FunctionTemplateDecl>(D) && 2849 "Cannot refer unambiguously to a function template"); 2850 2851 SourceLocation Loc = NameInfo.getLoc(); 2852 if (CheckDeclInExpr(*this, Loc, D)) 2853 return ExprError(); 2854 2855 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2856 // Specifically diagnose references to class templates that are missing 2857 // a template argument list. 2858 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2859 << Template << SS.getRange(); 2860 Diag(Template->getLocation(), diag::note_template_decl_here); 2861 return ExprError(); 2862 } 2863 2864 // Make sure that we're referring to a value. 2865 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2866 if (!VD) { 2867 Diag(Loc, diag::err_ref_non_value) 2868 << D << SS.getRange(); 2869 Diag(D->getLocation(), diag::note_declared_at); 2870 return ExprError(); 2871 } 2872 2873 // Check whether this declaration can be used. Note that we suppress 2874 // this check when we're going to perform argument-dependent lookup 2875 // on this function name, because this might not be the function 2876 // that overload resolution actually selects. 2877 if (DiagnoseUseOfDecl(VD, Loc)) 2878 return ExprError(); 2879 2880 // Only create DeclRefExpr's for valid Decl's. 2881 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2882 return ExprError(); 2883 2884 // Handle members of anonymous structs and unions. If we got here, 2885 // and the reference is to a class member indirect field, then this 2886 // must be the subject of a pointer-to-member expression. 2887 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2888 if (!indirectField->isCXXClassMember()) 2889 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2890 indirectField); 2891 2892 { 2893 QualType type = VD->getType(); 2894 ExprValueKind valueKind = VK_RValue; 2895 2896 switch (D->getKind()) { 2897 // Ignore all the non-ValueDecl kinds. 2898 #define ABSTRACT_DECL(kind) 2899 #define VALUE(type, base) 2900 #define DECL(type, base) \ 2901 case Decl::type: 2902 #include "clang/AST/DeclNodes.inc" 2903 llvm_unreachable("invalid value decl kind"); 2904 2905 // These shouldn't make it here. 2906 case Decl::ObjCAtDefsField: 2907 case Decl::ObjCIvar: 2908 llvm_unreachable("forming non-member reference to ivar?"); 2909 2910 // Enum constants are always r-values and never references. 2911 // Unresolved using declarations are dependent. 2912 case Decl::EnumConstant: 2913 case Decl::UnresolvedUsingValue: 2914 case Decl::OMPDeclareReduction: 2915 valueKind = VK_RValue; 2916 break; 2917 2918 // Fields and indirect fields that got here must be for 2919 // pointer-to-member expressions; we just call them l-values for 2920 // internal consistency, because this subexpression doesn't really 2921 // exist in the high-level semantics. 2922 case Decl::Field: 2923 case Decl::IndirectField: 2924 assert(getLangOpts().CPlusPlus && 2925 "building reference to field in C?"); 2926 2927 // These can't have reference type in well-formed programs, but 2928 // for internal consistency we do this anyway. 2929 type = type.getNonReferenceType(); 2930 valueKind = VK_LValue; 2931 break; 2932 2933 // Non-type template parameters are either l-values or r-values 2934 // depending on the type. 2935 case Decl::NonTypeTemplateParm: { 2936 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2937 type = reftype->getPointeeType(); 2938 valueKind = VK_LValue; // even if the parameter is an r-value reference 2939 break; 2940 } 2941 2942 // For non-references, we need to strip qualifiers just in case 2943 // the template parameter was declared as 'const int' or whatever. 2944 valueKind = VK_RValue; 2945 type = type.getUnqualifiedType(); 2946 break; 2947 } 2948 2949 case Decl::Var: 2950 case Decl::VarTemplateSpecialization: 2951 case Decl::VarTemplatePartialSpecialization: 2952 case Decl::Decomposition: 2953 case Decl::OMPCapturedExpr: 2954 // In C, "extern void blah;" is valid and is an r-value. 2955 if (!getLangOpts().CPlusPlus && 2956 !type.hasQualifiers() && 2957 type->isVoidType()) { 2958 valueKind = VK_RValue; 2959 break; 2960 } 2961 // fallthrough 2962 2963 case Decl::ImplicitParam: 2964 case Decl::ParmVar: { 2965 // These are always l-values. 2966 valueKind = VK_LValue; 2967 type = type.getNonReferenceType(); 2968 2969 // FIXME: Does the addition of const really only apply in 2970 // potentially-evaluated contexts? Since the variable isn't actually 2971 // captured in an unevaluated context, it seems that the answer is no. 2972 if (!isUnevaluatedContext()) { 2973 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2974 if (!CapturedType.isNull()) 2975 type = CapturedType; 2976 } 2977 2978 break; 2979 } 2980 2981 case Decl::Binding: { 2982 // These are always lvalues. 2983 valueKind = VK_LValue; 2984 type = type.getNonReferenceType(); 2985 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2986 // decides how that's supposed to work. 2987 auto *BD = cast<BindingDecl>(VD); 2988 if (BD->getDeclContext()->isFunctionOrMethod() && 2989 BD->getDeclContext() != CurContext) 2990 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2991 break; 2992 } 2993 2994 case Decl::Function: { 2995 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2996 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2997 type = Context.BuiltinFnTy; 2998 valueKind = VK_RValue; 2999 break; 3000 } 3001 } 3002 3003 const FunctionType *fty = type->castAs<FunctionType>(); 3004 3005 // If we're referring to a function with an __unknown_anytype 3006 // result type, make the entire expression __unknown_anytype. 3007 if (fty->getReturnType() == Context.UnknownAnyTy) { 3008 type = Context.UnknownAnyTy; 3009 valueKind = VK_RValue; 3010 break; 3011 } 3012 3013 // Functions are l-values in C++. 3014 if (getLangOpts().CPlusPlus) { 3015 valueKind = VK_LValue; 3016 break; 3017 } 3018 3019 // C99 DR 316 says that, if a function type comes from a 3020 // function definition (without a prototype), that type is only 3021 // used for checking compatibility. Therefore, when referencing 3022 // the function, we pretend that we don't have the full function 3023 // type. 3024 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3025 isa<FunctionProtoType>(fty)) 3026 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3027 fty->getExtInfo()); 3028 3029 // Functions are r-values in C. 3030 valueKind = VK_RValue; 3031 break; 3032 } 3033 3034 case Decl::MSProperty: 3035 valueKind = VK_LValue; 3036 break; 3037 3038 case Decl::CXXMethod: 3039 // If we're referring to a method with an __unknown_anytype 3040 // result type, make the entire expression __unknown_anytype. 3041 // This should only be possible with a type written directly. 3042 if (const FunctionProtoType *proto 3043 = dyn_cast<FunctionProtoType>(VD->getType())) 3044 if (proto->getReturnType() == Context.UnknownAnyTy) { 3045 type = Context.UnknownAnyTy; 3046 valueKind = VK_RValue; 3047 break; 3048 } 3049 3050 // C++ methods are l-values if static, r-values if non-static. 3051 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3052 valueKind = VK_LValue; 3053 break; 3054 } 3055 // fallthrough 3056 3057 case Decl::CXXConversion: 3058 case Decl::CXXDestructor: 3059 case Decl::CXXConstructor: 3060 valueKind = VK_RValue; 3061 break; 3062 } 3063 3064 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3065 TemplateArgs); 3066 } 3067 } 3068 3069 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3070 SmallString<32> &Target) { 3071 Target.resize(CharByteWidth * (Source.size() + 1)); 3072 char *ResultPtr = &Target[0]; 3073 const UTF8 *ErrorPtr; 3074 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3075 (void)success; 3076 assert(success); 3077 Target.resize(ResultPtr - &Target[0]); 3078 } 3079 3080 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3081 PredefinedExpr::IdentType IT) { 3082 // Pick the current block, lambda, captured statement or function. 3083 Decl *currentDecl = nullptr; 3084 if (const BlockScopeInfo *BSI = getCurBlock()) 3085 currentDecl = BSI->TheDecl; 3086 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3087 currentDecl = LSI->CallOperator; 3088 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3089 currentDecl = CSI->TheCapturedDecl; 3090 else 3091 currentDecl = getCurFunctionOrMethodDecl(); 3092 3093 if (!currentDecl) { 3094 Diag(Loc, diag::ext_predef_outside_function); 3095 currentDecl = Context.getTranslationUnitDecl(); 3096 } 3097 3098 QualType ResTy; 3099 StringLiteral *SL = nullptr; 3100 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3101 ResTy = Context.DependentTy; 3102 else { 3103 // Pre-defined identifiers are of type char[x], where x is the length of 3104 // the string. 3105 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3106 unsigned Length = Str.length(); 3107 3108 llvm::APInt LengthI(32, Length + 1); 3109 if (IT == PredefinedExpr::LFunction) { 3110 ResTy = Context.WideCharTy.withConst(); 3111 SmallString<32> RawChars; 3112 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3113 Str, RawChars); 3114 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3115 /*IndexTypeQuals*/ 0); 3116 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3117 /*Pascal*/ false, ResTy, Loc); 3118 } else { 3119 ResTy = Context.CharTy.withConst(); 3120 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3121 /*IndexTypeQuals*/ 0); 3122 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3123 /*Pascal*/ false, ResTy, Loc); 3124 } 3125 } 3126 3127 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3128 } 3129 3130 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3131 PredefinedExpr::IdentType IT; 3132 3133 switch (Kind) { 3134 default: llvm_unreachable("Unknown simple primary expr!"); 3135 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3136 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3137 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3138 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3139 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3140 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3141 } 3142 3143 return BuildPredefinedExpr(Loc, IT); 3144 } 3145 3146 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3147 SmallString<16> CharBuffer; 3148 bool Invalid = false; 3149 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3150 if (Invalid) 3151 return ExprError(); 3152 3153 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3154 PP, Tok.getKind()); 3155 if (Literal.hadError()) 3156 return ExprError(); 3157 3158 QualType Ty; 3159 if (Literal.isWide()) 3160 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3161 else if (Literal.isUTF16()) 3162 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3163 else if (Literal.isUTF32()) 3164 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3165 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3166 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3167 else 3168 Ty = Context.CharTy; // 'x' -> char in C++ 3169 3170 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3171 if (Literal.isWide()) 3172 Kind = CharacterLiteral::Wide; 3173 else if (Literal.isUTF16()) 3174 Kind = CharacterLiteral::UTF16; 3175 else if (Literal.isUTF32()) 3176 Kind = CharacterLiteral::UTF32; 3177 else if (Literal.isUTF8()) 3178 Kind = CharacterLiteral::UTF8; 3179 3180 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3181 Tok.getLocation()); 3182 3183 if (Literal.getUDSuffix().empty()) 3184 return Lit; 3185 3186 // We're building a user-defined literal. 3187 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3188 SourceLocation UDSuffixLoc = 3189 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3190 3191 // Make sure we're allowed user-defined literals here. 3192 if (!UDLScope) 3193 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3194 3195 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3196 // operator "" X (ch) 3197 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3198 Lit, Tok.getLocation()); 3199 } 3200 3201 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3202 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3203 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3204 Context.IntTy, Loc); 3205 } 3206 3207 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3208 QualType Ty, SourceLocation Loc) { 3209 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3210 3211 using llvm::APFloat; 3212 APFloat Val(Format); 3213 3214 APFloat::opStatus result = Literal.GetFloatValue(Val); 3215 3216 // Overflow is always an error, but underflow is only an error if 3217 // we underflowed to zero (APFloat reports denormals as underflow). 3218 if ((result & APFloat::opOverflow) || 3219 ((result & APFloat::opUnderflow) && Val.isZero())) { 3220 unsigned diagnostic; 3221 SmallString<20> buffer; 3222 if (result & APFloat::opOverflow) { 3223 diagnostic = diag::warn_float_overflow; 3224 APFloat::getLargest(Format).toString(buffer); 3225 } else { 3226 diagnostic = diag::warn_float_underflow; 3227 APFloat::getSmallest(Format).toString(buffer); 3228 } 3229 3230 S.Diag(Loc, diagnostic) 3231 << Ty 3232 << StringRef(buffer.data(), buffer.size()); 3233 } 3234 3235 bool isExact = (result == APFloat::opOK); 3236 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3237 } 3238 3239 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3240 assert(E && "Invalid expression"); 3241 3242 if (E->isValueDependent()) 3243 return false; 3244 3245 QualType QT = E->getType(); 3246 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3247 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3248 return true; 3249 } 3250 3251 llvm::APSInt ValueAPS; 3252 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3253 3254 if (R.isInvalid()) 3255 return true; 3256 3257 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3258 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3259 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3260 << ValueAPS.toString(10) << ValueIsPositive; 3261 return true; 3262 } 3263 3264 return false; 3265 } 3266 3267 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3268 // Fast path for a single digit (which is quite common). A single digit 3269 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3270 if (Tok.getLength() == 1) { 3271 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3272 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3273 } 3274 3275 SmallString<128> SpellingBuffer; 3276 // NumericLiteralParser wants to overread by one character. Add padding to 3277 // the buffer in case the token is copied to the buffer. If getSpelling() 3278 // returns a StringRef to the memory buffer, it should have a null char at 3279 // the EOF, so it is also safe. 3280 SpellingBuffer.resize(Tok.getLength() + 1); 3281 3282 // Get the spelling of the token, which eliminates trigraphs, etc. 3283 bool Invalid = false; 3284 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3285 if (Invalid) 3286 return ExprError(); 3287 3288 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3289 if (Literal.hadError) 3290 return ExprError(); 3291 3292 if (Literal.hasUDSuffix()) { 3293 // We're building a user-defined literal. 3294 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3295 SourceLocation UDSuffixLoc = 3296 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3297 3298 // Make sure we're allowed user-defined literals here. 3299 if (!UDLScope) 3300 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3301 3302 QualType CookedTy; 3303 if (Literal.isFloatingLiteral()) { 3304 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3305 // long double, the literal is treated as a call of the form 3306 // operator "" X (f L) 3307 CookedTy = Context.LongDoubleTy; 3308 } else { 3309 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3310 // unsigned long long, the literal is treated as a call of the form 3311 // operator "" X (n ULL) 3312 CookedTy = Context.UnsignedLongLongTy; 3313 } 3314 3315 DeclarationName OpName = 3316 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3317 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3318 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3319 3320 SourceLocation TokLoc = Tok.getLocation(); 3321 3322 // Perform literal operator lookup to determine if we're building a raw 3323 // literal or a cooked one. 3324 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3325 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3326 /*AllowRaw*/true, /*AllowTemplate*/true, 3327 /*AllowStringTemplate*/false)) { 3328 case LOLR_Error: 3329 return ExprError(); 3330 3331 case LOLR_Cooked: { 3332 Expr *Lit; 3333 if (Literal.isFloatingLiteral()) { 3334 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3335 } else { 3336 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3337 if (Literal.GetIntegerValue(ResultVal)) 3338 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3339 << /* Unsigned */ 1; 3340 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3341 Tok.getLocation()); 3342 } 3343 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3344 } 3345 3346 case LOLR_Raw: { 3347 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3348 // literal is treated as a call of the form 3349 // operator "" X ("n") 3350 unsigned Length = Literal.getUDSuffixOffset(); 3351 QualType StrTy = Context.getConstantArrayType( 3352 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3353 ArrayType::Normal, 0); 3354 Expr *Lit = StringLiteral::Create( 3355 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3356 /*Pascal*/false, StrTy, &TokLoc, 1); 3357 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3358 } 3359 3360 case LOLR_Template: { 3361 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3362 // template), L is treated as a call fo the form 3363 // operator "" X <'c1', 'c2', ... 'ck'>() 3364 // where n is the source character sequence c1 c2 ... ck. 3365 TemplateArgumentListInfo ExplicitArgs; 3366 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3367 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3368 llvm::APSInt Value(CharBits, CharIsUnsigned); 3369 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3370 Value = TokSpelling[I]; 3371 TemplateArgument Arg(Context, Value, Context.CharTy); 3372 TemplateArgumentLocInfo ArgInfo; 3373 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3374 } 3375 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3376 &ExplicitArgs); 3377 } 3378 case LOLR_StringTemplate: 3379 llvm_unreachable("unexpected literal operator lookup result"); 3380 } 3381 } 3382 3383 Expr *Res; 3384 3385 if (Literal.isFloatingLiteral()) { 3386 QualType Ty; 3387 if (Literal.isHalf){ 3388 if (getOpenCLOptions().cl_khr_fp16) 3389 Ty = Context.HalfTy; 3390 else { 3391 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3392 return ExprError(); 3393 } 3394 } else if (Literal.isFloat) 3395 Ty = Context.FloatTy; 3396 else if (Literal.isLong) 3397 Ty = Context.LongDoubleTy; 3398 else if (Literal.isFloat128) 3399 Ty = Context.Float128Ty; 3400 else 3401 Ty = Context.DoubleTy; 3402 3403 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3404 3405 if (Ty == Context.DoubleTy) { 3406 if (getLangOpts().SinglePrecisionConstants) { 3407 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3408 } else if (getLangOpts().OpenCL && 3409 !((getLangOpts().OpenCLVersion >= 120) || 3410 getOpenCLOptions().cl_khr_fp64)) { 3411 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3412 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3413 } 3414 } 3415 } else if (!Literal.isIntegerLiteral()) { 3416 return ExprError(); 3417 } else { 3418 QualType Ty; 3419 3420 // 'long long' is a C99 or C++11 feature. 3421 if (!getLangOpts().C99 && Literal.isLongLong) { 3422 if (getLangOpts().CPlusPlus) 3423 Diag(Tok.getLocation(), 3424 getLangOpts().CPlusPlus11 ? 3425 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3426 else 3427 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3428 } 3429 3430 // Get the value in the widest-possible width. 3431 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3432 llvm::APInt ResultVal(MaxWidth, 0); 3433 3434 if (Literal.GetIntegerValue(ResultVal)) { 3435 // If this value didn't fit into uintmax_t, error and force to ull. 3436 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3437 << /* Unsigned */ 1; 3438 Ty = Context.UnsignedLongLongTy; 3439 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3440 "long long is not intmax_t?"); 3441 } else { 3442 // If this value fits into a ULL, try to figure out what else it fits into 3443 // according to the rules of C99 6.4.4.1p5. 3444 3445 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3446 // be an unsigned int. 3447 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3448 3449 // Check from smallest to largest, picking the smallest type we can. 3450 unsigned Width = 0; 3451 3452 // Microsoft specific integer suffixes are explicitly sized. 3453 if (Literal.MicrosoftInteger) { 3454 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3455 Width = 8; 3456 Ty = Context.CharTy; 3457 } else { 3458 Width = Literal.MicrosoftInteger; 3459 Ty = Context.getIntTypeForBitwidth(Width, 3460 /*Signed=*/!Literal.isUnsigned); 3461 } 3462 } 3463 3464 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3465 // Are int/unsigned possibilities? 3466 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3467 3468 // Does it fit in a unsigned int? 3469 if (ResultVal.isIntN(IntSize)) { 3470 // Does it fit in a signed int? 3471 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3472 Ty = Context.IntTy; 3473 else if (AllowUnsigned) 3474 Ty = Context.UnsignedIntTy; 3475 Width = IntSize; 3476 } 3477 } 3478 3479 // Are long/unsigned long possibilities? 3480 if (Ty.isNull() && !Literal.isLongLong) { 3481 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3482 3483 // Does it fit in a unsigned long? 3484 if (ResultVal.isIntN(LongSize)) { 3485 // Does it fit in a signed long? 3486 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3487 Ty = Context.LongTy; 3488 else if (AllowUnsigned) 3489 Ty = Context.UnsignedLongTy; 3490 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3491 // is compatible. 3492 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3493 const unsigned LongLongSize = 3494 Context.getTargetInfo().getLongLongWidth(); 3495 Diag(Tok.getLocation(), 3496 getLangOpts().CPlusPlus 3497 ? Literal.isLong 3498 ? diag::warn_old_implicitly_unsigned_long_cxx 3499 : /*C++98 UB*/ diag:: 3500 ext_old_implicitly_unsigned_long_cxx 3501 : diag::warn_old_implicitly_unsigned_long) 3502 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3503 : /*will be ill-formed*/ 1); 3504 Ty = Context.UnsignedLongTy; 3505 } 3506 Width = LongSize; 3507 } 3508 } 3509 3510 // Check long long if needed. 3511 if (Ty.isNull()) { 3512 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3513 3514 // Does it fit in a unsigned long long? 3515 if (ResultVal.isIntN(LongLongSize)) { 3516 // Does it fit in a signed long long? 3517 // To be compatible with MSVC, hex integer literals ending with the 3518 // LL or i64 suffix are always signed in Microsoft mode. 3519 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3520 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3521 Ty = Context.LongLongTy; 3522 else if (AllowUnsigned) 3523 Ty = Context.UnsignedLongLongTy; 3524 Width = LongLongSize; 3525 } 3526 } 3527 3528 // If we still couldn't decide a type, we probably have something that 3529 // does not fit in a signed long long, but has no U suffix. 3530 if (Ty.isNull()) { 3531 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3532 Ty = Context.UnsignedLongLongTy; 3533 Width = Context.getTargetInfo().getLongLongWidth(); 3534 } 3535 3536 if (ResultVal.getBitWidth() != Width) 3537 ResultVal = ResultVal.trunc(Width); 3538 } 3539 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3540 } 3541 3542 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3543 if (Literal.isImaginary) 3544 Res = new (Context) ImaginaryLiteral(Res, 3545 Context.getComplexType(Res->getType())); 3546 3547 return Res; 3548 } 3549 3550 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3551 assert(E && "ActOnParenExpr() missing expr"); 3552 return new (Context) ParenExpr(L, R, E); 3553 } 3554 3555 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3556 SourceLocation Loc, 3557 SourceRange ArgRange) { 3558 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3559 // scalar or vector data type argument..." 3560 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3561 // type (C99 6.2.5p18) or void. 3562 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3563 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3564 << T << ArgRange; 3565 return true; 3566 } 3567 3568 assert((T->isVoidType() || !T->isIncompleteType()) && 3569 "Scalar types should always be complete"); 3570 return false; 3571 } 3572 3573 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3574 SourceLocation Loc, 3575 SourceRange ArgRange, 3576 UnaryExprOrTypeTrait TraitKind) { 3577 // Invalid types must be hard errors for SFINAE in C++. 3578 if (S.LangOpts.CPlusPlus) 3579 return true; 3580 3581 // C99 6.5.3.4p1: 3582 if (T->isFunctionType() && 3583 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3584 // sizeof(function)/alignof(function) is allowed as an extension. 3585 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3586 << TraitKind << ArgRange; 3587 return false; 3588 } 3589 3590 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3591 // this is an error (OpenCL v1.1 s6.3.k) 3592 if (T->isVoidType()) { 3593 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3594 : diag::ext_sizeof_alignof_void_type; 3595 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3596 return false; 3597 } 3598 3599 return true; 3600 } 3601 3602 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3603 SourceLocation Loc, 3604 SourceRange ArgRange, 3605 UnaryExprOrTypeTrait TraitKind) { 3606 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3607 // runtime doesn't allow it. 3608 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3609 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3610 << T << (TraitKind == UETT_SizeOf) 3611 << ArgRange; 3612 return true; 3613 } 3614 3615 return false; 3616 } 3617 3618 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3619 /// pointer type is equal to T) and emit a warning if it is. 3620 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3621 Expr *E) { 3622 // Don't warn if the operation changed the type. 3623 if (T != E->getType()) 3624 return; 3625 3626 // Now look for array decays. 3627 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3628 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3629 return; 3630 3631 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3632 << ICE->getType() 3633 << ICE->getSubExpr()->getType(); 3634 } 3635 3636 /// \brief Check the constraints on expression operands to unary type expression 3637 /// and type traits. 3638 /// 3639 /// Completes any types necessary and validates the constraints on the operand 3640 /// expression. The logic mostly mirrors the type-based overload, but may modify 3641 /// the expression as it completes the type for that expression through template 3642 /// instantiation, etc. 3643 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3644 UnaryExprOrTypeTrait ExprKind) { 3645 QualType ExprTy = E->getType(); 3646 assert(!ExprTy->isReferenceType()); 3647 3648 if (ExprKind == UETT_VecStep) 3649 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3650 E->getSourceRange()); 3651 3652 // Whitelist some types as extensions 3653 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3654 E->getSourceRange(), ExprKind)) 3655 return false; 3656 3657 // 'alignof' applied to an expression only requires the base element type of 3658 // the expression to be complete. 'sizeof' requires the expression's type to 3659 // be complete (and will attempt to complete it if it's an array of unknown 3660 // bound). 3661 if (ExprKind == UETT_AlignOf) { 3662 if (RequireCompleteType(E->getExprLoc(), 3663 Context.getBaseElementType(E->getType()), 3664 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3665 E->getSourceRange())) 3666 return true; 3667 } else { 3668 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3669 ExprKind, E->getSourceRange())) 3670 return true; 3671 } 3672 3673 // Completing the expression's type may have changed it. 3674 ExprTy = E->getType(); 3675 assert(!ExprTy->isReferenceType()); 3676 3677 if (ExprTy->isFunctionType()) { 3678 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3679 << ExprKind << E->getSourceRange(); 3680 return true; 3681 } 3682 3683 // The operand for sizeof and alignof is in an unevaluated expression context, 3684 // so side effects could result in unintended consequences. 3685 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3686 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3687 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3688 3689 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3690 E->getSourceRange(), ExprKind)) 3691 return true; 3692 3693 if (ExprKind == UETT_SizeOf) { 3694 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3695 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3696 QualType OType = PVD->getOriginalType(); 3697 QualType Type = PVD->getType(); 3698 if (Type->isPointerType() && OType->isArrayType()) { 3699 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3700 << Type << OType; 3701 Diag(PVD->getLocation(), diag::note_declared_at); 3702 } 3703 } 3704 } 3705 3706 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3707 // decays into a pointer and returns an unintended result. This is most 3708 // likely a typo for "sizeof(array) op x". 3709 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3710 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3711 BO->getLHS()); 3712 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3713 BO->getRHS()); 3714 } 3715 } 3716 3717 return false; 3718 } 3719 3720 /// \brief Check the constraints on operands to unary expression and type 3721 /// traits. 3722 /// 3723 /// This will complete any types necessary, and validate the various constraints 3724 /// on those operands. 3725 /// 3726 /// The UsualUnaryConversions() function is *not* called by this routine. 3727 /// C99 6.3.2.1p[2-4] all state: 3728 /// Except when it is the operand of the sizeof operator ... 3729 /// 3730 /// C++ [expr.sizeof]p4 3731 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3732 /// standard conversions are not applied to the operand of sizeof. 3733 /// 3734 /// This policy is followed for all of the unary trait expressions. 3735 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3736 SourceLocation OpLoc, 3737 SourceRange ExprRange, 3738 UnaryExprOrTypeTrait ExprKind) { 3739 if (ExprType->isDependentType()) 3740 return false; 3741 3742 // C++ [expr.sizeof]p2: 3743 // When applied to a reference or a reference type, the result 3744 // is the size of the referenced type. 3745 // C++11 [expr.alignof]p3: 3746 // When alignof is applied to a reference type, the result 3747 // shall be the alignment of the referenced type. 3748 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3749 ExprType = Ref->getPointeeType(); 3750 3751 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3752 // When alignof or _Alignof is applied to an array type, the result 3753 // is the alignment of the element type. 3754 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3755 ExprType = Context.getBaseElementType(ExprType); 3756 3757 if (ExprKind == UETT_VecStep) 3758 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3759 3760 // Whitelist some types as extensions 3761 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3762 ExprKind)) 3763 return false; 3764 3765 if (RequireCompleteType(OpLoc, ExprType, 3766 diag::err_sizeof_alignof_incomplete_type, 3767 ExprKind, ExprRange)) 3768 return true; 3769 3770 if (ExprType->isFunctionType()) { 3771 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3772 << ExprKind << ExprRange; 3773 return true; 3774 } 3775 3776 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3777 ExprKind)) 3778 return true; 3779 3780 return false; 3781 } 3782 3783 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3784 E = E->IgnoreParens(); 3785 3786 // Cannot know anything else if the expression is dependent. 3787 if (E->isTypeDependent()) 3788 return false; 3789 3790 if (E->getObjectKind() == OK_BitField) { 3791 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3792 << 1 << E->getSourceRange(); 3793 return true; 3794 } 3795 3796 ValueDecl *D = nullptr; 3797 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3798 D = DRE->getDecl(); 3799 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3800 D = ME->getMemberDecl(); 3801 } 3802 3803 // If it's a field, require the containing struct to have a 3804 // complete definition so that we can compute the layout. 3805 // 3806 // This can happen in C++11 onwards, either by naming the member 3807 // in a way that is not transformed into a member access expression 3808 // (in an unevaluated operand, for instance), or by naming the member 3809 // in a trailing-return-type. 3810 // 3811 // For the record, since __alignof__ on expressions is a GCC 3812 // extension, GCC seems to permit this but always gives the 3813 // nonsensical answer 0. 3814 // 3815 // We don't really need the layout here --- we could instead just 3816 // directly check for all the appropriate alignment-lowing 3817 // attributes --- but that would require duplicating a lot of 3818 // logic that just isn't worth duplicating for such a marginal 3819 // use-case. 3820 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3821 // Fast path this check, since we at least know the record has a 3822 // definition if we can find a member of it. 3823 if (!FD->getParent()->isCompleteDefinition()) { 3824 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3825 << E->getSourceRange(); 3826 return true; 3827 } 3828 3829 // Otherwise, if it's a field, and the field doesn't have 3830 // reference type, then it must have a complete type (or be a 3831 // flexible array member, which we explicitly want to 3832 // white-list anyway), which makes the following checks trivial. 3833 if (!FD->getType()->isReferenceType()) 3834 return false; 3835 } 3836 3837 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3838 } 3839 3840 bool Sema::CheckVecStepExpr(Expr *E) { 3841 E = E->IgnoreParens(); 3842 3843 // Cannot know anything else if the expression is dependent. 3844 if (E->isTypeDependent()) 3845 return false; 3846 3847 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3848 } 3849 3850 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3851 CapturingScopeInfo *CSI) { 3852 assert(T->isVariablyModifiedType()); 3853 assert(CSI != nullptr); 3854 3855 // We're going to walk down into the type and look for VLA expressions. 3856 do { 3857 const Type *Ty = T.getTypePtr(); 3858 switch (Ty->getTypeClass()) { 3859 #define TYPE(Class, Base) 3860 #define ABSTRACT_TYPE(Class, Base) 3861 #define NON_CANONICAL_TYPE(Class, Base) 3862 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3863 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3864 #include "clang/AST/TypeNodes.def" 3865 T = QualType(); 3866 break; 3867 // These types are never variably-modified. 3868 case Type::Builtin: 3869 case Type::Complex: 3870 case Type::Vector: 3871 case Type::ExtVector: 3872 case Type::Record: 3873 case Type::Enum: 3874 case Type::Elaborated: 3875 case Type::TemplateSpecialization: 3876 case Type::ObjCObject: 3877 case Type::ObjCInterface: 3878 case Type::ObjCObjectPointer: 3879 case Type::ObjCTypeParam: 3880 case Type::Pipe: 3881 llvm_unreachable("type class is never variably-modified!"); 3882 case Type::Adjusted: 3883 T = cast<AdjustedType>(Ty)->getOriginalType(); 3884 break; 3885 case Type::Decayed: 3886 T = cast<DecayedType>(Ty)->getPointeeType(); 3887 break; 3888 case Type::Pointer: 3889 T = cast<PointerType>(Ty)->getPointeeType(); 3890 break; 3891 case Type::BlockPointer: 3892 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3893 break; 3894 case Type::LValueReference: 3895 case Type::RValueReference: 3896 T = cast<ReferenceType>(Ty)->getPointeeType(); 3897 break; 3898 case Type::MemberPointer: 3899 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3900 break; 3901 case Type::ConstantArray: 3902 case Type::IncompleteArray: 3903 // Losing element qualification here is fine. 3904 T = cast<ArrayType>(Ty)->getElementType(); 3905 break; 3906 case Type::VariableArray: { 3907 // Losing element qualification here is fine. 3908 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3909 3910 // Unknown size indication requires no size computation. 3911 // Otherwise, evaluate and record it. 3912 if (auto Size = VAT->getSizeExpr()) { 3913 if (!CSI->isVLATypeCaptured(VAT)) { 3914 RecordDecl *CapRecord = nullptr; 3915 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3916 CapRecord = LSI->Lambda; 3917 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3918 CapRecord = CRSI->TheRecordDecl; 3919 } 3920 if (CapRecord) { 3921 auto ExprLoc = Size->getExprLoc(); 3922 auto SizeType = Context.getSizeType(); 3923 // Build the non-static data member. 3924 auto Field = 3925 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3926 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3927 /*BW*/ nullptr, /*Mutable*/ false, 3928 /*InitStyle*/ ICIS_NoInit); 3929 Field->setImplicit(true); 3930 Field->setAccess(AS_private); 3931 Field->setCapturedVLAType(VAT); 3932 CapRecord->addDecl(Field); 3933 3934 CSI->addVLATypeCapture(ExprLoc, SizeType); 3935 } 3936 } 3937 } 3938 T = VAT->getElementType(); 3939 break; 3940 } 3941 case Type::FunctionProto: 3942 case Type::FunctionNoProto: 3943 T = cast<FunctionType>(Ty)->getReturnType(); 3944 break; 3945 case Type::Paren: 3946 case Type::TypeOf: 3947 case Type::UnaryTransform: 3948 case Type::Attributed: 3949 case Type::SubstTemplateTypeParm: 3950 case Type::PackExpansion: 3951 // Keep walking after single level desugaring. 3952 T = T.getSingleStepDesugaredType(Context); 3953 break; 3954 case Type::Typedef: 3955 T = cast<TypedefType>(Ty)->desugar(); 3956 break; 3957 case Type::Decltype: 3958 T = cast<DecltypeType>(Ty)->desugar(); 3959 break; 3960 case Type::Auto: 3961 T = cast<AutoType>(Ty)->getDeducedType(); 3962 break; 3963 case Type::TypeOfExpr: 3964 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3965 break; 3966 case Type::Atomic: 3967 T = cast<AtomicType>(Ty)->getValueType(); 3968 break; 3969 } 3970 } while (!T.isNull() && T->isVariablyModifiedType()); 3971 } 3972 3973 /// \brief Build a sizeof or alignof expression given a type operand. 3974 ExprResult 3975 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3976 SourceLocation OpLoc, 3977 UnaryExprOrTypeTrait ExprKind, 3978 SourceRange R) { 3979 if (!TInfo) 3980 return ExprError(); 3981 3982 QualType T = TInfo->getType(); 3983 3984 if (!T->isDependentType() && 3985 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3986 return ExprError(); 3987 3988 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3989 if (auto *TT = T->getAs<TypedefType>()) { 3990 for (auto I = FunctionScopes.rbegin(), 3991 E = std::prev(FunctionScopes.rend()); 3992 I != E; ++I) { 3993 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3994 if (CSI == nullptr) 3995 break; 3996 DeclContext *DC = nullptr; 3997 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3998 DC = LSI->CallOperator; 3999 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4000 DC = CRSI->TheCapturedDecl; 4001 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4002 DC = BSI->TheDecl; 4003 if (DC) { 4004 if (DC->containsDecl(TT->getDecl())) 4005 break; 4006 captureVariablyModifiedType(Context, T, CSI); 4007 } 4008 } 4009 } 4010 } 4011 4012 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4013 return new (Context) UnaryExprOrTypeTraitExpr( 4014 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4015 } 4016 4017 /// \brief Build a sizeof or alignof expression given an expression 4018 /// operand. 4019 ExprResult 4020 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4021 UnaryExprOrTypeTrait ExprKind) { 4022 ExprResult PE = CheckPlaceholderExpr(E); 4023 if (PE.isInvalid()) 4024 return ExprError(); 4025 4026 E = PE.get(); 4027 4028 // Verify that the operand is valid. 4029 bool isInvalid = false; 4030 if (E->isTypeDependent()) { 4031 // Delay type-checking for type-dependent expressions. 4032 } else if (ExprKind == UETT_AlignOf) { 4033 isInvalid = CheckAlignOfExpr(*this, E); 4034 } else if (ExprKind == UETT_VecStep) { 4035 isInvalid = CheckVecStepExpr(E); 4036 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4037 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4038 isInvalid = true; 4039 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4040 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4041 isInvalid = true; 4042 } else { 4043 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4044 } 4045 4046 if (isInvalid) 4047 return ExprError(); 4048 4049 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4050 PE = TransformToPotentiallyEvaluated(E); 4051 if (PE.isInvalid()) return ExprError(); 4052 E = PE.get(); 4053 } 4054 4055 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4056 return new (Context) UnaryExprOrTypeTraitExpr( 4057 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4058 } 4059 4060 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4061 /// expr and the same for @c alignof and @c __alignof 4062 /// Note that the ArgRange is invalid if isType is false. 4063 ExprResult 4064 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4065 UnaryExprOrTypeTrait ExprKind, bool IsType, 4066 void *TyOrEx, SourceRange ArgRange) { 4067 // If error parsing type, ignore. 4068 if (!TyOrEx) return ExprError(); 4069 4070 if (IsType) { 4071 TypeSourceInfo *TInfo; 4072 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4073 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4074 } 4075 4076 Expr *ArgEx = (Expr *)TyOrEx; 4077 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4078 return Result; 4079 } 4080 4081 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4082 bool IsReal) { 4083 if (V.get()->isTypeDependent()) 4084 return S.Context.DependentTy; 4085 4086 // _Real and _Imag are only l-values for normal l-values. 4087 if (V.get()->getObjectKind() != OK_Ordinary) { 4088 V = S.DefaultLvalueConversion(V.get()); 4089 if (V.isInvalid()) 4090 return QualType(); 4091 } 4092 4093 // These operators return the element type of a complex type. 4094 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4095 return CT->getElementType(); 4096 4097 // Otherwise they pass through real integer and floating point types here. 4098 if (V.get()->getType()->isArithmeticType()) 4099 return V.get()->getType(); 4100 4101 // Test for placeholders. 4102 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4103 if (PR.isInvalid()) return QualType(); 4104 if (PR.get() != V.get()) { 4105 V = PR; 4106 return CheckRealImagOperand(S, V, Loc, IsReal); 4107 } 4108 4109 // Reject anything else. 4110 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4111 << (IsReal ? "__real" : "__imag"); 4112 return QualType(); 4113 } 4114 4115 4116 4117 ExprResult 4118 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4119 tok::TokenKind Kind, Expr *Input) { 4120 UnaryOperatorKind Opc; 4121 switch (Kind) { 4122 default: llvm_unreachable("Unknown unary op!"); 4123 case tok::plusplus: Opc = UO_PostInc; break; 4124 case tok::minusminus: Opc = UO_PostDec; break; 4125 } 4126 4127 // Since this might is a postfix expression, get rid of ParenListExprs. 4128 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4129 if (Result.isInvalid()) return ExprError(); 4130 Input = Result.get(); 4131 4132 return BuildUnaryOp(S, OpLoc, Opc, Input); 4133 } 4134 4135 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4136 /// 4137 /// \return true on error 4138 static bool checkArithmeticOnObjCPointer(Sema &S, 4139 SourceLocation opLoc, 4140 Expr *op) { 4141 assert(op->getType()->isObjCObjectPointerType()); 4142 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4143 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4144 return false; 4145 4146 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4147 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4148 << op->getSourceRange(); 4149 return true; 4150 } 4151 4152 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4153 auto *BaseNoParens = Base->IgnoreParens(); 4154 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4155 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4156 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4157 } 4158 4159 ExprResult 4160 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4161 Expr *idx, SourceLocation rbLoc) { 4162 if (base && !base->getType().isNull() && 4163 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4164 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4165 /*Length=*/nullptr, rbLoc); 4166 4167 // Since this might be a postfix expression, get rid of ParenListExprs. 4168 if (isa<ParenListExpr>(base)) { 4169 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4170 if (result.isInvalid()) return ExprError(); 4171 base = result.get(); 4172 } 4173 4174 // Handle any non-overload placeholder types in the base and index 4175 // expressions. We can't handle overloads here because the other 4176 // operand might be an overloadable type, in which case the overload 4177 // resolution for the operator overload should get the first crack 4178 // at the overload. 4179 bool IsMSPropertySubscript = false; 4180 if (base->getType()->isNonOverloadPlaceholderType()) { 4181 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4182 if (!IsMSPropertySubscript) { 4183 ExprResult result = CheckPlaceholderExpr(base); 4184 if (result.isInvalid()) 4185 return ExprError(); 4186 base = result.get(); 4187 } 4188 } 4189 if (idx->getType()->isNonOverloadPlaceholderType()) { 4190 ExprResult result = CheckPlaceholderExpr(idx); 4191 if (result.isInvalid()) return ExprError(); 4192 idx = result.get(); 4193 } 4194 4195 // Build an unanalyzed expression if either operand is type-dependent. 4196 if (getLangOpts().CPlusPlus && 4197 (base->isTypeDependent() || idx->isTypeDependent())) { 4198 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4199 VK_LValue, OK_Ordinary, rbLoc); 4200 } 4201 4202 // MSDN, property (C++) 4203 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4204 // This attribute can also be used in the declaration of an empty array in a 4205 // class or structure definition. For example: 4206 // __declspec(property(get=GetX, put=PutX)) int x[]; 4207 // The above statement indicates that x[] can be used with one or more array 4208 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4209 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4210 if (IsMSPropertySubscript) { 4211 // Build MS property subscript expression if base is MS property reference 4212 // or MS property subscript. 4213 return new (Context) MSPropertySubscriptExpr( 4214 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4215 } 4216 4217 // Use C++ overloaded-operator rules if either operand has record 4218 // type. The spec says to do this if either type is *overloadable*, 4219 // but enum types can't declare subscript operators or conversion 4220 // operators, so there's nothing interesting for overload resolution 4221 // to do if there aren't any record types involved. 4222 // 4223 // ObjC pointers have their own subscripting logic that is not tied 4224 // to overload resolution and so should not take this path. 4225 if (getLangOpts().CPlusPlus && 4226 (base->getType()->isRecordType() || 4227 (!base->getType()->isObjCObjectPointerType() && 4228 idx->getType()->isRecordType()))) { 4229 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4230 } 4231 4232 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4233 } 4234 4235 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4236 Expr *LowerBound, 4237 SourceLocation ColonLoc, Expr *Length, 4238 SourceLocation RBLoc) { 4239 if (Base->getType()->isPlaceholderType() && 4240 !Base->getType()->isSpecificPlaceholderType( 4241 BuiltinType::OMPArraySection)) { 4242 ExprResult Result = CheckPlaceholderExpr(Base); 4243 if (Result.isInvalid()) 4244 return ExprError(); 4245 Base = Result.get(); 4246 } 4247 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4248 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4249 if (Result.isInvalid()) 4250 return ExprError(); 4251 Result = DefaultLvalueConversion(Result.get()); 4252 if (Result.isInvalid()) 4253 return ExprError(); 4254 LowerBound = Result.get(); 4255 } 4256 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4257 ExprResult Result = CheckPlaceholderExpr(Length); 4258 if (Result.isInvalid()) 4259 return ExprError(); 4260 Result = DefaultLvalueConversion(Result.get()); 4261 if (Result.isInvalid()) 4262 return ExprError(); 4263 Length = Result.get(); 4264 } 4265 4266 // Build an unanalyzed expression if either operand is type-dependent. 4267 if (Base->isTypeDependent() || 4268 (LowerBound && 4269 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4270 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4271 return new (Context) 4272 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4273 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4274 } 4275 4276 // Perform default conversions. 4277 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4278 QualType ResultTy; 4279 if (OriginalTy->isAnyPointerType()) { 4280 ResultTy = OriginalTy->getPointeeType(); 4281 } else if (OriginalTy->isArrayType()) { 4282 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4283 } else { 4284 return ExprError( 4285 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4286 << Base->getSourceRange()); 4287 } 4288 // C99 6.5.2.1p1 4289 if (LowerBound) { 4290 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4291 LowerBound); 4292 if (Res.isInvalid()) 4293 return ExprError(Diag(LowerBound->getExprLoc(), 4294 diag::err_omp_typecheck_section_not_integer) 4295 << 0 << LowerBound->getSourceRange()); 4296 LowerBound = Res.get(); 4297 4298 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4299 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4300 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4301 << 0 << LowerBound->getSourceRange(); 4302 } 4303 if (Length) { 4304 auto Res = 4305 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4306 if (Res.isInvalid()) 4307 return ExprError(Diag(Length->getExprLoc(), 4308 diag::err_omp_typecheck_section_not_integer) 4309 << 1 << Length->getSourceRange()); 4310 Length = Res.get(); 4311 4312 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4313 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4314 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4315 << 1 << Length->getSourceRange(); 4316 } 4317 4318 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4319 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4320 // type. Note that functions are not objects, and that (in C99 parlance) 4321 // incomplete types are not object types. 4322 if (ResultTy->isFunctionType()) { 4323 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4324 << ResultTy << Base->getSourceRange(); 4325 return ExprError(); 4326 } 4327 4328 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4329 diag::err_omp_section_incomplete_type, Base)) 4330 return ExprError(); 4331 4332 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4333 llvm::APSInt LowerBoundValue; 4334 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4335 // OpenMP 4.5, [2.4 Array Sections] 4336 // The array section must be a subset of the original array. 4337 if (LowerBoundValue.isNegative()) { 4338 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4339 << LowerBound->getSourceRange(); 4340 return ExprError(); 4341 } 4342 } 4343 } 4344 4345 if (Length) { 4346 llvm::APSInt LengthValue; 4347 if (Length->EvaluateAsInt(LengthValue, Context)) { 4348 // OpenMP 4.5, [2.4 Array Sections] 4349 // The length must evaluate to non-negative integers. 4350 if (LengthValue.isNegative()) { 4351 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4352 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4353 << Length->getSourceRange(); 4354 return ExprError(); 4355 } 4356 } 4357 } else if (ColonLoc.isValid() && 4358 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4359 !OriginalTy->isVariableArrayType()))) { 4360 // OpenMP 4.5, [2.4 Array Sections] 4361 // When the size of the array dimension is not known, the length must be 4362 // specified explicitly. 4363 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4364 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4365 return ExprError(); 4366 } 4367 4368 if (!Base->getType()->isSpecificPlaceholderType( 4369 BuiltinType::OMPArraySection)) { 4370 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4371 if (Result.isInvalid()) 4372 return ExprError(); 4373 Base = Result.get(); 4374 } 4375 return new (Context) 4376 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4377 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4378 } 4379 4380 ExprResult 4381 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4382 Expr *Idx, SourceLocation RLoc) { 4383 Expr *LHSExp = Base; 4384 Expr *RHSExp = Idx; 4385 4386 // Perform default conversions. 4387 if (!LHSExp->getType()->getAs<VectorType>()) { 4388 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4389 if (Result.isInvalid()) 4390 return ExprError(); 4391 LHSExp = Result.get(); 4392 } 4393 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4394 if (Result.isInvalid()) 4395 return ExprError(); 4396 RHSExp = Result.get(); 4397 4398 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4399 ExprValueKind VK = VK_LValue; 4400 ExprObjectKind OK = OK_Ordinary; 4401 4402 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4403 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4404 // in the subscript position. As a result, we need to derive the array base 4405 // and index from the expression types. 4406 Expr *BaseExpr, *IndexExpr; 4407 QualType ResultType; 4408 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4409 BaseExpr = LHSExp; 4410 IndexExpr = RHSExp; 4411 ResultType = Context.DependentTy; 4412 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4413 BaseExpr = LHSExp; 4414 IndexExpr = RHSExp; 4415 ResultType = PTy->getPointeeType(); 4416 } else if (const ObjCObjectPointerType *PTy = 4417 LHSTy->getAs<ObjCObjectPointerType>()) { 4418 BaseExpr = LHSExp; 4419 IndexExpr = RHSExp; 4420 4421 // Use custom logic if this should be the pseudo-object subscript 4422 // expression. 4423 if (!LangOpts.isSubscriptPointerArithmetic()) 4424 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4425 nullptr); 4426 4427 ResultType = PTy->getPointeeType(); 4428 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4429 // Handle the uncommon case of "123[Ptr]". 4430 BaseExpr = RHSExp; 4431 IndexExpr = LHSExp; 4432 ResultType = PTy->getPointeeType(); 4433 } else if (const ObjCObjectPointerType *PTy = 4434 RHSTy->getAs<ObjCObjectPointerType>()) { 4435 // Handle the uncommon case of "123[Ptr]". 4436 BaseExpr = RHSExp; 4437 IndexExpr = LHSExp; 4438 ResultType = PTy->getPointeeType(); 4439 if (!LangOpts.isSubscriptPointerArithmetic()) { 4440 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4441 << ResultType << BaseExpr->getSourceRange(); 4442 return ExprError(); 4443 } 4444 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4445 BaseExpr = LHSExp; // vectors: V[123] 4446 IndexExpr = RHSExp; 4447 VK = LHSExp->getValueKind(); 4448 if (VK != VK_RValue) 4449 OK = OK_VectorComponent; 4450 4451 // FIXME: need to deal with const... 4452 ResultType = VTy->getElementType(); 4453 } else if (LHSTy->isArrayType()) { 4454 // If we see an array that wasn't promoted by 4455 // DefaultFunctionArrayLvalueConversion, it must be an array that 4456 // wasn't promoted because of the C90 rule that doesn't 4457 // allow promoting non-lvalue arrays. Warn, then 4458 // force the promotion here. 4459 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4460 LHSExp->getSourceRange(); 4461 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4462 CK_ArrayToPointerDecay).get(); 4463 LHSTy = LHSExp->getType(); 4464 4465 BaseExpr = LHSExp; 4466 IndexExpr = RHSExp; 4467 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4468 } else if (RHSTy->isArrayType()) { 4469 // Same as previous, except for 123[f().a] case 4470 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4471 RHSExp->getSourceRange(); 4472 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4473 CK_ArrayToPointerDecay).get(); 4474 RHSTy = RHSExp->getType(); 4475 4476 BaseExpr = RHSExp; 4477 IndexExpr = LHSExp; 4478 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4479 } else { 4480 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4481 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4482 } 4483 // C99 6.5.2.1p1 4484 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4485 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4486 << IndexExpr->getSourceRange()); 4487 4488 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4489 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4490 && !IndexExpr->isTypeDependent()) 4491 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4492 4493 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4494 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4495 // type. Note that Functions are not objects, and that (in C99 parlance) 4496 // incomplete types are not object types. 4497 if (ResultType->isFunctionType()) { 4498 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4499 << ResultType << BaseExpr->getSourceRange(); 4500 return ExprError(); 4501 } 4502 4503 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4504 // GNU extension: subscripting on pointer to void 4505 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4506 << BaseExpr->getSourceRange(); 4507 4508 // C forbids expressions of unqualified void type from being l-values. 4509 // See IsCForbiddenLValueType. 4510 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4511 } else if (!ResultType->isDependentType() && 4512 RequireCompleteType(LLoc, ResultType, 4513 diag::err_subscript_incomplete_type, BaseExpr)) 4514 return ExprError(); 4515 4516 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4517 !ResultType.isCForbiddenLValueType()); 4518 4519 return new (Context) 4520 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4521 } 4522 4523 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4524 FunctionDecl *FD, 4525 ParmVarDecl *Param) { 4526 if (Param->hasUnparsedDefaultArg()) { 4527 Diag(CallLoc, 4528 diag::err_use_of_default_argument_to_function_declared_later) << 4529 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4530 Diag(UnparsedDefaultArgLocs[Param], 4531 diag::note_default_argument_declared_here); 4532 return ExprError(); 4533 } 4534 4535 if (Param->hasUninstantiatedDefaultArg()) { 4536 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4537 4538 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4539 Param); 4540 4541 // Instantiate the expression. 4542 MultiLevelTemplateArgumentList MutiLevelArgList 4543 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4544 4545 InstantiatingTemplate Inst(*this, CallLoc, Param, 4546 MutiLevelArgList.getInnermost()); 4547 if (Inst.isInvalid()) 4548 return ExprError(); 4549 if (Inst.isAlreadyInstantiating()) { 4550 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4551 Param->setInvalidDecl(); 4552 return ExprError(); 4553 } 4554 4555 ExprResult Result; 4556 { 4557 // C++ [dcl.fct.default]p5: 4558 // The names in the [default argument] expression are bound, and 4559 // the semantic constraints are checked, at the point where the 4560 // default argument expression appears. 4561 ContextRAII SavedContext(*this, FD); 4562 LocalInstantiationScope Local(*this); 4563 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4564 } 4565 if (Result.isInvalid()) 4566 return ExprError(); 4567 4568 // Check the expression as an initializer for the parameter. 4569 InitializedEntity Entity 4570 = InitializedEntity::InitializeParameter(Context, Param); 4571 InitializationKind Kind 4572 = InitializationKind::CreateCopy(Param->getLocation(), 4573 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4574 Expr *ResultE = Result.getAs<Expr>(); 4575 4576 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4577 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4578 if (Result.isInvalid()) 4579 return ExprError(); 4580 4581 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4582 Param->getOuterLocStart()); 4583 if (Result.isInvalid()) 4584 return ExprError(); 4585 4586 // Remember the instantiated default argument. 4587 Param->setDefaultArg(Result.getAs<Expr>()); 4588 if (ASTMutationListener *L = getASTMutationListener()) { 4589 L->DefaultArgumentInstantiated(Param); 4590 } 4591 } 4592 4593 // If the default argument expression is not set yet, we are building it now. 4594 if (!Param->hasInit()) { 4595 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4596 Param->setInvalidDecl(); 4597 return ExprError(); 4598 } 4599 4600 // If the default expression creates temporaries, we need to 4601 // push them to the current stack of expression temporaries so they'll 4602 // be properly destroyed. 4603 // FIXME: We should really be rebuilding the default argument with new 4604 // bound temporaries; see the comment in PR5810. 4605 // We don't need to do that with block decls, though, because 4606 // blocks in default argument expression can never capture anything. 4607 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4608 // Set the "needs cleanups" bit regardless of whether there are 4609 // any explicit objects. 4610 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4611 4612 // Append all the objects to the cleanup list. Right now, this 4613 // should always be a no-op, because blocks in default argument 4614 // expressions should never be able to capture anything. 4615 assert(!Init->getNumObjects() && 4616 "default argument expression has capturing blocks?"); 4617 } 4618 4619 // We already type-checked the argument, so we know it works. 4620 // Just mark all of the declarations in this potentially-evaluated expression 4621 // as being "referenced". 4622 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4623 /*SkipLocalVariables=*/true); 4624 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4625 } 4626 4627 4628 Sema::VariadicCallType 4629 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4630 Expr *Fn) { 4631 if (Proto && Proto->isVariadic()) { 4632 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4633 return VariadicConstructor; 4634 else if (Fn && Fn->getType()->isBlockPointerType()) 4635 return VariadicBlock; 4636 else if (FDecl) { 4637 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4638 if (Method->isInstance()) 4639 return VariadicMethod; 4640 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4641 return VariadicMethod; 4642 return VariadicFunction; 4643 } 4644 return VariadicDoesNotApply; 4645 } 4646 4647 namespace { 4648 class FunctionCallCCC : public FunctionCallFilterCCC { 4649 public: 4650 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4651 unsigned NumArgs, MemberExpr *ME) 4652 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4653 FunctionName(FuncName) {} 4654 4655 bool ValidateCandidate(const TypoCorrection &candidate) override { 4656 if (!candidate.getCorrectionSpecifier() || 4657 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4658 return false; 4659 } 4660 4661 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4662 } 4663 4664 private: 4665 const IdentifierInfo *const FunctionName; 4666 }; 4667 } 4668 4669 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4670 FunctionDecl *FDecl, 4671 ArrayRef<Expr *> Args) { 4672 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4673 DeclarationName FuncName = FDecl->getDeclName(); 4674 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4675 4676 if (TypoCorrection Corrected = S.CorrectTypo( 4677 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4678 S.getScopeForContext(S.CurContext), nullptr, 4679 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4680 Args.size(), ME), 4681 Sema::CTK_ErrorRecovery)) { 4682 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4683 if (Corrected.isOverloaded()) { 4684 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4685 OverloadCandidateSet::iterator Best; 4686 for (NamedDecl *CD : Corrected) { 4687 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4688 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4689 OCS); 4690 } 4691 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4692 case OR_Success: 4693 ND = Best->FoundDecl; 4694 Corrected.setCorrectionDecl(ND); 4695 break; 4696 default: 4697 break; 4698 } 4699 } 4700 ND = ND->getUnderlyingDecl(); 4701 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4702 return Corrected; 4703 } 4704 } 4705 return TypoCorrection(); 4706 } 4707 4708 /// ConvertArgumentsForCall - Converts the arguments specified in 4709 /// Args/NumArgs to the parameter types of the function FDecl with 4710 /// function prototype Proto. Call is the call expression itself, and 4711 /// Fn is the function expression. For a C++ member function, this 4712 /// routine does not attempt to convert the object argument. Returns 4713 /// true if the call is ill-formed. 4714 bool 4715 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4716 FunctionDecl *FDecl, 4717 const FunctionProtoType *Proto, 4718 ArrayRef<Expr *> Args, 4719 SourceLocation RParenLoc, 4720 bool IsExecConfig) { 4721 // Bail out early if calling a builtin with custom typechecking. 4722 if (FDecl) 4723 if (unsigned ID = FDecl->getBuiltinID()) 4724 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4725 return false; 4726 4727 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4728 // assignment, to the types of the corresponding parameter, ... 4729 unsigned NumParams = Proto->getNumParams(); 4730 bool Invalid = false; 4731 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4732 unsigned FnKind = Fn->getType()->isBlockPointerType() 4733 ? 1 /* block */ 4734 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4735 : 0 /* function */); 4736 4737 // If too few arguments are available (and we don't have default 4738 // arguments for the remaining parameters), don't make the call. 4739 if (Args.size() < NumParams) { 4740 if (Args.size() < MinArgs) { 4741 TypoCorrection TC; 4742 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4743 unsigned diag_id = 4744 MinArgs == NumParams && !Proto->isVariadic() 4745 ? diag::err_typecheck_call_too_few_args_suggest 4746 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4747 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4748 << static_cast<unsigned>(Args.size()) 4749 << TC.getCorrectionRange()); 4750 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4751 Diag(RParenLoc, 4752 MinArgs == NumParams && !Proto->isVariadic() 4753 ? diag::err_typecheck_call_too_few_args_one 4754 : diag::err_typecheck_call_too_few_args_at_least_one) 4755 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4756 else 4757 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4758 ? diag::err_typecheck_call_too_few_args 4759 : diag::err_typecheck_call_too_few_args_at_least) 4760 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4761 << Fn->getSourceRange(); 4762 4763 // Emit the location of the prototype. 4764 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4765 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4766 << FDecl; 4767 4768 return true; 4769 } 4770 Call->setNumArgs(Context, NumParams); 4771 } 4772 4773 // If too many are passed and not variadic, error on the extras and drop 4774 // them. 4775 if (Args.size() > NumParams) { 4776 if (!Proto->isVariadic()) { 4777 TypoCorrection TC; 4778 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4779 unsigned diag_id = 4780 MinArgs == NumParams && !Proto->isVariadic() 4781 ? diag::err_typecheck_call_too_many_args_suggest 4782 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4783 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4784 << static_cast<unsigned>(Args.size()) 4785 << TC.getCorrectionRange()); 4786 } else if (NumParams == 1 && FDecl && 4787 FDecl->getParamDecl(0)->getDeclName()) 4788 Diag(Args[NumParams]->getLocStart(), 4789 MinArgs == NumParams 4790 ? diag::err_typecheck_call_too_many_args_one 4791 : diag::err_typecheck_call_too_many_args_at_most_one) 4792 << FnKind << FDecl->getParamDecl(0) 4793 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4794 << SourceRange(Args[NumParams]->getLocStart(), 4795 Args.back()->getLocEnd()); 4796 else 4797 Diag(Args[NumParams]->getLocStart(), 4798 MinArgs == NumParams 4799 ? diag::err_typecheck_call_too_many_args 4800 : diag::err_typecheck_call_too_many_args_at_most) 4801 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4802 << Fn->getSourceRange() 4803 << SourceRange(Args[NumParams]->getLocStart(), 4804 Args.back()->getLocEnd()); 4805 4806 // Emit the location of the prototype. 4807 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4808 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4809 << FDecl; 4810 4811 // This deletes the extra arguments. 4812 Call->setNumArgs(Context, NumParams); 4813 return true; 4814 } 4815 } 4816 SmallVector<Expr *, 8> AllArgs; 4817 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4818 4819 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4820 Proto, 0, Args, AllArgs, CallType); 4821 if (Invalid) 4822 return true; 4823 unsigned TotalNumArgs = AllArgs.size(); 4824 for (unsigned i = 0; i < TotalNumArgs; ++i) 4825 Call->setArg(i, AllArgs[i]); 4826 4827 return false; 4828 } 4829 4830 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4831 const FunctionProtoType *Proto, 4832 unsigned FirstParam, ArrayRef<Expr *> Args, 4833 SmallVectorImpl<Expr *> &AllArgs, 4834 VariadicCallType CallType, bool AllowExplicit, 4835 bool IsListInitialization) { 4836 unsigned NumParams = Proto->getNumParams(); 4837 bool Invalid = false; 4838 size_t ArgIx = 0; 4839 // Continue to check argument types (even if we have too few/many args). 4840 for (unsigned i = FirstParam; i < NumParams; i++) { 4841 QualType ProtoArgType = Proto->getParamType(i); 4842 4843 Expr *Arg; 4844 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4845 if (ArgIx < Args.size()) { 4846 Arg = Args[ArgIx++]; 4847 4848 if (RequireCompleteType(Arg->getLocStart(), 4849 ProtoArgType, 4850 diag::err_call_incomplete_argument, Arg)) 4851 return true; 4852 4853 // Strip the unbridged-cast placeholder expression off, if applicable. 4854 bool CFAudited = false; 4855 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4856 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4857 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4858 Arg = stripARCUnbridgedCast(Arg); 4859 else if (getLangOpts().ObjCAutoRefCount && 4860 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4861 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4862 CFAudited = true; 4863 4864 InitializedEntity Entity = 4865 Param ? InitializedEntity::InitializeParameter(Context, Param, 4866 ProtoArgType) 4867 : InitializedEntity::InitializeParameter( 4868 Context, ProtoArgType, Proto->isParamConsumed(i)); 4869 4870 // Remember that parameter belongs to a CF audited API. 4871 if (CFAudited) 4872 Entity.setParameterCFAudited(); 4873 4874 ExprResult ArgE = PerformCopyInitialization( 4875 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4876 if (ArgE.isInvalid()) 4877 return true; 4878 4879 Arg = ArgE.getAs<Expr>(); 4880 } else { 4881 assert(Param && "can't use default arguments without a known callee"); 4882 4883 ExprResult ArgExpr = 4884 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4885 if (ArgExpr.isInvalid()) 4886 return true; 4887 4888 Arg = ArgExpr.getAs<Expr>(); 4889 } 4890 4891 // Check for array bounds violations for each argument to the call. This 4892 // check only triggers warnings when the argument isn't a more complex Expr 4893 // with its own checking, such as a BinaryOperator. 4894 CheckArrayAccess(Arg); 4895 4896 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4897 CheckStaticArrayArgument(CallLoc, Param, Arg); 4898 4899 AllArgs.push_back(Arg); 4900 } 4901 4902 // If this is a variadic call, handle args passed through "...". 4903 if (CallType != VariadicDoesNotApply) { 4904 // Assume that extern "C" functions with variadic arguments that 4905 // return __unknown_anytype aren't *really* variadic. 4906 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4907 FDecl->isExternC()) { 4908 for (Expr *A : Args.slice(ArgIx)) { 4909 QualType paramType; // ignored 4910 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4911 Invalid |= arg.isInvalid(); 4912 AllArgs.push_back(arg.get()); 4913 } 4914 4915 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4916 } else { 4917 for (Expr *A : Args.slice(ArgIx)) { 4918 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4919 Invalid |= Arg.isInvalid(); 4920 AllArgs.push_back(Arg.get()); 4921 } 4922 } 4923 4924 // Check for array bounds violations. 4925 for (Expr *A : Args.slice(ArgIx)) 4926 CheckArrayAccess(A); 4927 } 4928 return Invalid; 4929 } 4930 4931 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4932 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4933 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4934 TL = DTL.getOriginalLoc(); 4935 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4936 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4937 << ATL.getLocalSourceRange(); 4938 } 4939 4940 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4941 /// array parameter, check that it is non-null, and that if it is formed by 4942 /// array-to-pointer decay, the underlying array is sufficiently large. 4943 /// 4944 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4945 /// array type derivation, then for each call to the function, the value of the 4946 /// corresponding actual argument shall provide access to the first element of 4947 /// an array with at least as many elements as specified by the size expression. 4948 void 4949 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4950 ParmVarDecl *Param, 4951 const Expr *ArgExpr) { 4952 // Static array parameters are not supported in C++. 4953 if (!Param || getLangOpts().CPlusPlus) 4954 return; 4955 4956 QualType OrigTy = Param->getOriginalType(); 4957 4958 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4959 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4960 return; 4961 4962 if (ArgExpr->isNullPointerConstant(Context, 4963 Expr::NPC_NeverValueDependent)) { 4964 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4965 DiagnoseCalleeStaticArrayParam(*this, Param); 4966 return; 4967 } 4968 4969 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4970 if (!CAT) 4971 return; 4972 4973 const ConstantArrayType *ArgCAT = 4974 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4975 if (!ArgCAT) 4976 return; 4977 4978 if (ArgCAT->getSize().ult(CAT->getSize())) { 4979 Diag(CallLoc, diag::warn_static_array_too_small) 4980 << ArgExpr->getSourceRange() 4981 << (unsigned) ArgCAT->getSize().getZExtValue() 4982 << (unsigned) CAT->getSize().getZExtValue(); 4983 DiagnoseCalleeStaticArrayParam(*this, Param); 4984 } 4985 } 4986 4987 /// Given a function expression of unknown-any type, try to rebuild it 4988 /// to have a function type. 4989 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4990 4991 /// Is the given type a placeholder that we need to lower out 4992 /// immediately during argument processing? 4993 static bool isPlaceholderToRemoveAsArg(QualType type) { 4994 // Placeholders are never sugared. 4995 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4996 if (!placeholder) return false; 4997 4998 switch (placeholder->getKind()) { 4999 // Ignore all the non-placeholder types. 5000 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5001 case BuiltinType::Id: 5002 #include "clang/Basic/OpenCLImageTypes.def" 5003 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5004 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5005 #include "clang/AST/BuiltinTypes.def" 5006 return false; 5007 5008 // We cannot lower out overload sets; they might validly be resolved 5009 // by the call machinery. 5010 case BuiltinType::Overload: 5011 return false; 5012 5013 // Unbridged casts in ARC can be handled in some call positions and 5014 // should be left in place. 5015 case BuiltinType::ARCUnbridgedCast: 5016 return false; 5017 5018 // Pseudo-objects should be converted as soon as possible. 5019 case BuiltinType::PseudoObject: 5020 return true; 5021 5022 // The debugger mode could theoretically but currently does not try 5023 // to resolve unknown-typed arguments based on known parameter types. 5024 case BuiltinType::UnknownAny: 5025 return true; 5026 5027 // These are always invalid as call arguments and should be reported. 5028 case BuiltinType::BoundMember: 5029 case BuiltinType::BuiltinFn: 5030 case BuiltinType::OMPArraySection: 5031 return true; 5032 5033 } 5034 llvm_unreachable("bad builtin type kind"); 5035 } 5036 5037 /// Check an argument list for placeholders that we won't try to 5038 /// handle later. 5039 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5040 // Apply this processing to all the arguments at once instead of 5041 // dying at the first failure. 5042 bool hasInvalid = false; 5043 for (size_t i = 0, e = args.size(); i != e; i++) { 5044 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5045 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5046 if (result.isInvalid()) hasInvalid = true; 5047 else args[i] = result.get(); 5048 } else if (hasInvalid) { 5049 (void)S.CorrectDelayedTyposInExpr(args[i]); 5050 } 5051 } 5052 return hasInvalid; 5053 } 5054 5055 /// If a builtin function has a pointer argument with no explicit address 5056 /// space, then it should be able to accept a pointer to any address 5057 /// space as input. In order to do this, we need to replace the 5058 /// standard builtin declaration with one that uses the same address space 5059 /// as the call. 5060 /// 5061 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5062 /// it does not contain any pointer arguments without 5063 /// an address space qualifer. Otherwise the rewritten 5064 /// FunctionDecl is returned. 5065 /// TODO: Handle pointer return types. 5066 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5067 const FunctionDecl *FDecl, 5068 MultiExprArg ArgExprs) { 5069 5070 QualType DeclType = FDecl->getType(); 5071 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5072 5073 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5074 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5075 return nullptr; 5076 5077 bool NeedsNewDecl = false; 5078 unsigned i = 0; 5079 SmallVector<QualType, 8> OverloadParams; 5080 5081 for (QualType ParamType : FT->param_types()) { 5082 5083 // Convert array arguments to pointer to simplify type lookup. 5084 ExprResult ArgRes = 5085 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5086 if (ArgRes.isInvalid()) 5087 return nullptr; 5088 Expr *Arg = ArgRes.get(); 5089 QualType ArgType = Arg->getType(); 5090 if (!ParamType->isPointerType() || 5091 ParamType.getQualifiers().hasAddressSpace() || 5092 !ArgType->isPointerType() || 5093 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5094 OverloadParams.push_back(ParamType); 5095 continue; 5096 } 5097 5098 NeedsNewDecl = true; 5099 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5100 5101 QualType PointeeType = ParamType->getPointeeType(); 5102 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5103 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5104 } 5105 5106 if (!NeedsNewDecl) 5107 return nullptr; 5108 5109 FunctionProtoType::ExtProtoInfo EPI; 5110 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5111 OverloadParams, EPI); 5112 DeclContext *Parent = Context.getTranslationUnitDecl(); 5113 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5114 FDecl->getLocation(), 5115 FDecl->getLocation(), 5116 FDecl->getIdentifier(), 5117 OverloadTy, 5118 /*TInfo=*/nullptr, 5119 SC_Extern, false, 5120 /*hasPrototype=*/true); 5121 SmallVector<ParmVarDecl*, 16> Params; 5122 FT = cast<FunctionProtoType>(OverloadTy); 5123 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5124 QualType ParamType = FT->getParamType(i); 5125 ParmVarDecl *Parm = 5126 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5127 SourceLocation(), nullptr, ParamType, 5128 /*TInfo=*/nullptr, SC_None, nullptr); 5129 Parm->setScopeInfo(0, i); 5130 Params.push_back(Parm); 5131 } 5132 OverloadDecl->setParams(Params); 5133 return OverloadDecl; 5134 } 5135 5136 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5137 std::size_t NumArgs) { 5138 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5139 /*PartialOverloading=*/false)) 5140 return Callee->isVariadic(); 5141 return Callee->getMinRequiredArguments() <= NumArgs; 5142 } 5143 5144 static ExprResult ActOnCallExprImpl(Sema &S, Scope *Scope, Expr *Fn, 5145 SourceLocation LParenLoc, 5146 MultiExprArg ArgExprs, 5147 SourceLocation RParenLoc, Expr *ExecConfig, 5148 bool IsExecConfig) { 5149 // Since this might be a postfix expression, get rid of ParenListExprs. 5150 ExprResult Result = S.MaybeConvertParenListExprToParenExpr(Scope, Fn); 5151 if (Result.isInvalid()) return ExprError(); 5152 Fn = Result.get(); 5153 5154 if (checkArgsForPlaceholders(S, ArgExprs)) 5155 return ExprError(); 5156 5157 if (S.getLangOpts().CPlusPlus) { 5158 // If this is a pseudo-destructor expression, build the call immediately. 5159 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5160 if (!ArgExprs.empty()) { 5161 // Pseudo-destructor calls should not have any arguments. 5162 S.Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5163 << FixItHint::CreateRemoval( 5164 SourceRange(ArgExprs.front()->getLocStart(), 5165 ArgExprs.back()->getLocEnd())); 5166 } 5167 5168 return new (S.Context) 5169 CallExpr(S.Context, Fn, None, S.Context.VoidTy, VK_RValue, RParenLoc); 5170 } 5171 if (Fn->getType() == S.Context.PseudoObjectTy) { 5172 ExprResult result = S.CheckPlaceholderExpr(Fn); 5173 if (result.isInvalid()) return ExprError(); 5174 Fn = result.get(); 5175 } 5176 5177 // Determine whether this is a dependent call inside a C++ template, 5178 // in which case we won't do any semantic analysis now. 5179 bool Dependent = false; 5180 if (Fn->isTypeDependent()) 5181 Dependent = true; 5182 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5183 Dependent = true; 5184 5185 if (Dependent) { 5186 if (ExecConfig) { 5187 return new (S.Context) CUDAKernelCallExpr( 5188 S.Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5189 S.Context.DependentTy, VK_RValue, RParenLoc); 5190 } else { 5191 return new (S.Context) 5192 CallExpr(S.Context, Fn, ArgExprs, S.Context.DependentTy, VK_RValue, 5193 RParenLoc); 5194 } 5195 } 5196 5197 // Determine whether this is a call to an object (C++ [over.call.object]). 5198 if (Fn->getType()->isRecordType()) 5199 return S.BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5200 RParenLoc); 5201 5202 if (Fn->getType() == S.Context.UnknownAnyTy) { 5203 ExprResult result = rebuildUnknownAnyFunction(S, Fn); 5204 if (result.isInvalid()) return ExprError(); 5205 Fn = result.get(); 5206 } 5207 5208 if (Fn->getType() == S.Context.BoundMemberTy) { 5209 return S.BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5210 RParenLoc); 5211 } 5212 } 5213 5214 // Check for overloaded calls. This can happen even in C due to extensions. 5215 if (Fn->getType() == S.Context.OverloadTy) { 5216 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5217 5218 // We aren't supposed to apply this logic for if there'Scope an '&' 5219 // involved. 5220 if (!find.HasFormOfMemberPointer) { 5221 OverloadExpr *ovl = find.Expression; 5222 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5223 return S.BuildOverloadedCallExpr( 5224 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5225 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5226 return S.BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5227 RParenLoc); 5228 } 5229 } 5230 5231 // If we're directly calling a function, get the appropriate declaration. 5232 if (Fn->getType() == S.Context.UnknownAnyTy) { 5233 ExprResult result = rebuildUnknownAnyFunction(S, Fn); 5234 if (result.isInvalid()) return ExprError(); 5235 Fn = result.get(); 5236 } 5237 5238 Expr *NakedFn = Fn->IgnoreParens(); 5239 5240 bool CallingNDeclIndirectly = false; 5241 NamedDecl *NDecl = nullptr; 5242 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5243 if (UnOp->getOpcode() == UO_AddrOf) { 5244 CallingNDeclIndirectly = true; 5245 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5246 } 5247 } 5248 5249 if (isa<DeclRefExpr>(NakedFn)) { 5250 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5251 5252 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5253 if (FDecl && FDecl->getBuiltinID()) { 5254 // Rewrite the function decl for this builtin by replacing parameters 5255 // with no explicit address space with the address space of the arguments 5256 // in ArgExprs. 5257 if ((FDecl = 5258 rewriteBuiltinFunctionDecl(&S, S.Context, FDecl, ArgExprs))) { 5259 NDecl = FDecl; 5260 Fn = DeclRefExpr::Create( 5261 S.Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5262 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5263 } 5264 } 5265 } else if (isa<MemberExpr>(NakedFn)) 5266 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5267 5268 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5269 if (CallingNDeclIndirectly && 5270 !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5271 Fn->getLocStart())) 5272 return ExprError(); 5273 5274 // CheckEnableIf assumes that the we're passing in a sane number of args for 5275 // FD, but that doesn't always hold true here. This is because, in some 5276 // cases, we'll emit a diag about an ill-formed function call, but then 5277 // we'll continue on as if the function call wasn't ill-formed. So, if the 5278 // number of args looks incorrect, don't do enable_if checks; we should've 5279 // already emitted an error about the bad call. 5280 if (FD->hasAttr<EnableIfAttr>() && 5281 isNumberOfArgsValidForCall(S, FD, ArgExprs.size())) { 5282 if (const EnableIfAttr *Attr = S.CheckEnableIf(FD, ArgExprs, true)) { 5283 S.Diag(Fn->getLocStart(), 5284 isa<CXXMethodDecl>(FD) 5285 ? diag::err_ovl_no_viable_member_function_in_call 5286 : diag::err_ovl_no_viable_function_in_call) 5287 << FD << FD->getSourceRange(); 5288 S.Diag(FD->getLocation(), 5289 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5290 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5291 } 5292 } 5293 } 5294 5295 return S.BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5296 ExecConfig, IsExecConfig); 5297 } 5298 5299 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5300 /// This provides the location of the left/right parens and a list of comma 5301 /// locations. 5302 ExprResult Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5303 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5304 Expr *ExecConfig, bool IsExecConfig) { 5305 ExprResult Ret = ActOnCallExprImpl(*this, S, Fn, LParenLoc, ArgExprs, 5306 RParenLoc, ExecConfig, IsExecConfig); 5307 5308 // If appropriate, check that this is a valid CUDA call (and emit an error if 5309 // the call is not allowed). 5310 if (getLangOpts().CUDA && Ret.isUsable()) 5311 if (auto *Call = dyn_cast<CallExpr>(Ret.get())) 5312 if (auto *FD = Call->getDirectCallee()) 5313 if (!CheckCUDACall(Call->getLocStart(), FD)) 5314 return ExprError(); 5315 5316 return Ret; 5317 } 5318 5319 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5320 /// 5321 /// __builtin_astype( value, dst type ) 5322 /// 5323 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5324 SourceLocation BuiltinLoc, 5325 SourceLocation RParenLoc) { 5326 ExprValueKind VK = VK_RValue; 5327 ExprObjectKind OK = OK_Ordinary; 5328 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5329 QualType SrcTy = E->getType(); 5330 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5331 return ExprError(Diag(BuiltinLoc, 5332 diag::err_invalid_astype_of_different_size) 5333 << DstTy 5334 << SrcTy 5335 << E->getSourceRange()); 5336 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5337 } 5338 5339 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5340 /// provided arguments. 5341 /// 5342 /// __builtin_convertvector( value, dst type ) 5343 /// 5344 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5345 SourceLocation BuiltinLoc, 5346 SourceLocation RParenLoc) { 5347 TypeSourceInfo *TInfo; 5348 GetTypeFromParser(ParsedDestTy, &TInfo); 5349 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5350 } 5351 5352 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5353 /// i.e. an expression not of \p OverloadTy. The expression should 5354 /// unary-convert to an expression of function-pointer or 5355 /// block-pointer type. 5356 /// 5357 /// \param NDecl the declaration being called, if available 5358 ExprResult 5359 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5360 SourceLocation LParenLoc, 5361 ArrayRef<Expr *> Args, 5362 SourceLocation RParenLoc, 5363 Expr *Config, bool IsExecConfig) { 5364 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5365 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5366 5367 // Functions with 'interrupt' attribute cannot be called directly. 5368 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5369 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5370 return ExprError(); 5371 } 5372 5373 // Promote the function operand. 5374 // We special-case function promotion here because we only allow promoting 5375 // builtin functions to function pointers in the callee of a call. 5376 ExprResult Result; 5377 if (BuiltinID && 5378 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5379 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5380 CK_BuiltinFnToFnPtr).get(); 5381 } else { 5382 Result = CallExprUnaryConversions(Fn); 5383 } 5384 if (Result.isInvalid()) 5385 return ExprError(); 5386 Fn = Result.get(); 5387 5388 // Make the call expr early, before semantic checks. This guarantees cleanup 5389 // of arguments and function on error. 5390 CallExpr *TheCall; 5391 if (Config) 5392 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5393 cast<CallExpr>(Config), Args, 5394 Context.BoolTy, VK_RValue, 5395 RParenLoc); 5396 else 5397 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5398 VK_RValue, RParenLoc); 5399 5400 if (!getLangOpts().CPlusPlus) { 5401 // C cannot always handle TypoExpr nodes in builtin calls and direct 5402 // function calls as their argument checking don't necessarily handle 5403 // dependent types properly, so make sure any TypoExprs have been 5404 // dealt with. 5405 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5406 if (!Result.isUsable()) return ExprError(); 5407 TheCall = dyn_cast<CallExpr>(Result.get()); 5408 if (!TheCall) return Result; 5409 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5410 } 5411 5412 // Bail out early if calling a builtin with custom typechecking. 5413 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5414 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5415 5416 retry: 5417 const FunctionType *FuncT; 5418 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5419 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5420 // have type pointer to function". 5421 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5422 if (!FuncT) 5423 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5424 << Fn->getType() << Fn->getSourceRange()); 5425 } else if (const BlockPointerType *BPT = 5426 Fn->getType()->getAs<BlockPointerType>()) { 5427 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5428 } else { 5429 // Handle calls to expressions of unknown-any type. 5430 if (Fn->getType() == Context.UnknownAnyTy) { 5431 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5432 if (rewrite.isInvalid()) return ExprError(); 5433 Fn = rewrite.get(); 5434 TheCall->setCallee(Fn); 5435 goto retry; 5436 } 5437 5438 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5439 << Fn->getType() << Fn->getSourceRange()); 5440 } 5441 5442 if (getLangOpts().CUDA) { 5443 if (Config) { 5444 // CUDA: Kernel calls must be to global functions 5445 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5446 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5447 << FDecl->getName() << Fn->getSourceRange()); 5448 5449 // CUDA: Kernel function must have 'void' return type 5450 if (!FuncT->getReturnType()->isVoidType()) 5451 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5452 << Fn->getType() << Fn->getSourceRange()); 5453 } else { 5454 // CUDA: Calls to global functions must be configured 5455 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5456 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5457 << FDecl->getName() << Fn->getSourceRange()); 5458 } 5459 } 5460 5461 // Check for a valid return type 5462 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5463 FDecl)) 5464 return ExprError(); 5465 5466 // We know the result type of the call, set it. 5467 TheCall->setType(FuncT->getCallResultType(Context)); 5468 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5469 5470 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5471 if (Proto) { 5472 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5473 IsExecConfig)) 5474 return ExprError(); 5475 } else { 5476 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5477 5478 if (FDecl) { 5479 // Check if we have too few/too many template arguments, based 5480 // on our knowledge of the function definition. 5481 const FunctionDecl *Def = nullptr; 5482 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5483 Proto = Def->getType()->getAs<FunctionProtoType>(); 5484 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5485 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5486 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5487 } 5488 5489 // If the function we're calling isn't a function prototype, but we have 5490 // a function prototype from a prior declaratiom, use that prototype. 5491 if (!FDecl->hasPrototype()) 5492 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5493 } 5494 5495 // Promote the arguments (C99 6.5.2.2p6). 5496 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5497 Expr *Arg = Args[i]; 5498 5499 if (Proto && i < Proto->getNumParams()) { 5500 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5501 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5502 ExprResult ArgE = 5503 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5504 if (ArgE.isInvalid()) 5505 return true; 5506 5507 Arg = ArgE.getAs<Expr>(); 5508 5509 } else { 5510 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5511 5512 if (ArgE.isInvalid()) 5513 return true; 5514 5515 Arg = ArgE.getAs<Expr>(); 5516 } 5517 5518 if (RequireCompleteType(Arg->getLocStart(), 5519 Arg->getType(), 5520 diag::err_call_incomplete_argument, Arg)) 5521 return ExprError(); 5522 5523 TheCall->setArg(i, Arg); 5524 } 5525 } 5526 5527 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5528 if (!Method->isStatic()) 5529 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5530 << Fn->getSourceRange()); 5531 5532 // Check for sentinels 5533 if (NDecl) 5534 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5535 5536 // Do special checking on direct calls to functions. 5537 if (FDecl) { 5538 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5539 return ExprError(); 5540 5541 if (BuiltinID) 5542 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5543 } else if (NDecl) { 5544 if (CheckPointerCall(NDecl, TheCall, Proto)) 5545 return ExprError(); 5546 } else { 5547 if (CheckOtherCall(TheCall, Proto)) 5548 return ExprError(); 5549 } 5550 5551 return MaybeBindToTemporary(TheCall); 5552 } 5553 5554 ExprResult 5555 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5556 SourceLocation RParenLoc, Expr *InitExpr) { 5557 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5558 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5559 5560 TypeSourceInfo *TInfo; 5561 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5562 if (!TInfo) 5563 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5564 5565 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5566 } 5567 5568 ExprResult 5569 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5570 SourceLocation RParenLoc, Expr *LiteralExpr) { 5571 QualType literalType = TInfo->getType(); 5572 5573 if (literalType->isArrayType()) { 5574 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5575 diag::err_illegal_decl_array_incomplete_type, 5576 SourceRange(LParenLoc, 5577 LiteralExpr->getSourceRange().getEnd()))) 5578 return ExprError(); 5579 if (literalType->isVariableArrayType()) 5580 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5581 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5582 } else if (!literalType->isDependentType() && 5583 RequireCompleteType(LParenLoc, literalType, 5584 diag::err_typecheck_decl_incomplete_type, 5585 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5586 return ExprError(); 5587 5588 InitializedEntity Entity 5589 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5590 InitializationKind Kind 5591 = InitializationKind::CreateCStyleCast(LParenLoc, 5592 SourceRange(LParenLoc, RParenLoc), 5593 /*InitList=*/true); 5594 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5595 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5596 &literalType); 5597 if (Result.isInvalid()) 5598 return ExprError(); 5599 LiteralExpr = Result.get(); 5600 5601 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5602 if (isFileScope && 5603 !LiteralExpr->isTypeDependent() && 5604 !LiteralExpr->isValueDependent() && 5605 !literalType->isDependentType()) { // 6.5.2.5p3 5606 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5607 return ExprError(); 5608 } 5609 5610 // In C, compound literals are l-values for some reason. 5611 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5612 5613 return MaybeBindToTemporary( 5614 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5615 VK, LiteralExpr, isFileScope)); 5616 } 5617 5618 ExprResult 5619 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5620 SourceLocation RBraceLoc) { 5621 // Immediately handle non-overload placeholders. Overloads can be 5622 // resolved contextually, but everything else here can't. 5623 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5624 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5625 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5626 5627 // Ignore failures; dropping the entire initializer list because 5628 // of one failure would be terrible for indexing/etc. 5629 if (result.isInvalid()) continue; 5630 5631 InitArgList[I] = result.get(); 5632 } 5633 } 5634 5635 // Semantic analysis for initializers is done by ActOnDeclarator() and 5636 // CheckInitializer() - it requires knowledge of the object being intialized. 5637 5638 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5639 RBraceLoc); 5640 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5641 return E; 5642 } 5643 5644 /// Do an explicit extend of the given block pointer if we're in ARC. 5645 void Sema::maybeExtendBlockObject(ExprResult &E) { 5646 assert(E.get()->getType()->isBlockPointerType()); 5647 assert(E.get()->isRValue()); 5648 5649 // Only do this in an r-value context. 5650 if (!getLangOpts().ObjCAutoRefCount) return; 5651 5652 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5653 CK_ARCExtendBlockObject, E.get(), 5654 /*base path*/ nullptr, VK_RValue); 5655 Cleanup.setExprNeedsCleanups(true); 5656 } 5657 5658 /// Prepare a conversion of the given expression to an ObjC object 5659 /// pointer type. 5660 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5661 QualType type = E.get()->getType(); 5662 if (type->isObjCObjectPointerType()) { 5663 return CK_BitCast; 5664 } else if (type->isBlockPointerType()) { 5665 maybeExtendBlockObject(E); 5666 return CK_BlockPointerToObjCPointerCast; 5667 } else { 5668 assert(type->isPointerType()); 5669 return CK_CPointerToObjCPointerCast; 5670 } 5671 } 5672 5673 /// Prepares for a scalar cast, performing all the necessary stages 5674 /// except the final cast and returning the kind required. 5675 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5676 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5677 // Also, callers should have filtered out the invalid cases with 5678 // pointers. Everything else should be possible. 5679 5680 QualType SrcTy = Src.get()->getType(); 5681 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5682 return CK_NoOp; 5683 5684 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5685 case Type::STK_MemberPointer: 5686 llvm_unreachable("member pointer type in C"); 5687 5688 case Type::STK_CPointer: 5689 case Type::STK_BlockPointer: 5690 case Type::STK_ObjCObjectPointer: 5691 switch (DestTy->getScalarTypeKind()) { 5692 case Type::STK_CPointer: { 5693 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5694 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5695 if (SrcAS != DestAS) 5696 return CK_AddressSpaceConversion; 5697 return CK_BitCast; 5698 } 5699 case Type::STK_BlockPointer: 5700 return (SrcKind == Type::STK_BlockPointer 5701 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5702 case Type::STK_ObjCObjectPointer: 5703 if (SrcKind == Type::STK_ObjCObjectPointer) 5704 return CK_BitCast; 5705 if (SrcKind == Type::STK_CPointer) 5706 return CK_CPointerToObjCPointerCast; 5707 maybeExtendBlockObject(Src); 5708 return CK_BlockPointerToObjCPointerCast; 5709 case Type::STK_Bool: 5710 return CK_PointerToBoolean; 5711 case Type::STK_Integral: 5712 return CK_PointerToIntegral; 5713 case Type::STK_Floating: 5714 case Type::STK_FloatingComplex: 5715 case Type::STK_IntegralComplex: 5716 case Type::STK_MemberPointer: 5717 llvm_unreachable("illegal cast from pointer"); 5718 } 5719 llvm_unreachable("Should have returned before this"); 5720 5721 case Type::STK_Bool: // casting from bool is like casting from an integer 5722 case Type::STK_Integral: 5723 switch (DestTy->getScalarTypeKind()) { 5724 case Type::STK_CPointer: 5725 case Type::STK_ObjCObjectPointer: 5726 case Type::STK_BlockPointer: 5727 if (Src.get()->isNullPointerConstant(Context, 5728 Expr::NPC_ValueDependentIsNull)) 5729 return CK_NullToPointer; 5730 return CK_IntegralToPointer; 5731 case Type::STK_Bool: 5732 return CK_IntegralToBoolean; 5733 case Type::STK_Integral: 5734 return CK_IntegralCast; 5735 case Type::STK_Floating: 5736 return CK_IntegralToFloating; 5737 case Type::STK_IntegralComplex: 5738 Src = ImpCastExprToType(Src.get(), 5739 DestTy->castAs<ComplexType>()->getElementType(), 5740 CK_IntegralCast); 5741 return CK_IntegralRealToComplex; 5742 case Type::STK_FloatingComplex: 5743 Src = ImpCastExprToType(Src.get(), 5744 DestTy->castAs<ComplexType>()->getElementType(), 5745 CK_IntegralToFloating); 5746 return CK_FloatingRealToComplex; 5747 case Type::STK_MemberPointer: 5748 llvm_unreachable("member pointer type in C"); 5749 } 5750 llvm_unreachable("Should have returned before this"); 5751 5752 case Type::STK_Floating: 5753 switch (DestTy->getScalarTypeKind()) { 5754 case Type::STK_Floating: 5755 return CK_FloatingCast; 5756 case Type::STK_Bool: 5757 return CK_FloatingToBoolean; 5758 case Type::STK_Integral: 5759 return CK_FloatingToIntegral; 5760 case Type::STK_FloatingComplex: 5761 Src = ImpCastExprToType(Src.get(), 5762 DestTy->castAs<ComplexType>()->getElementType(), 5763 CK_FloatingCast); 5764 return CK_FloatingRealToComplex; 5765 case Type::STK_IntegralComplex: 5766 Src = ImpCastExprToType(Src.get(), 5767 DestTy->castAs<ComplexType>()->getElementType(), 5768 CK_FloatingToIntegral); 5769 return CK_IntegralRealToComplex; 5770 case Type::STK_CPointer: 5771 case Type::STK_ObjCObjectPointer: 5772 case Type::STK_BlockPointer: 5773 llvm_unreachable("valid float->pointer cast?"); 5774 case Type::STK_MemberPointer: 5775 llvm_unreachable("member pointer type in C"); 5776 } 5777 llvm_unreachable("Should have returned before this"); 5778 5779 case Type::STK_FloatingComplex: 5780 switch (DestTy->getScalarTypeKind()) { 5781 case Type::STK_FloatingComplex: 5782 return CK_FloatingComplexCast; 5783 case Type::STK_IntegralComplex: 5784 return CK_FloatingComplexToIntegralComplex; 5785 case Type::STK_Floating: { 5786 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5787 if (Context.hasSameType(ET, DestTy)) 5788 return CK_FloatingComplexToReal; 5789 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5790 return CK_FloatingCast; 5791 } 5792 case Type::STK_Bool: 5793 return CK_FloatingComplexToBoolean; 5794 case Type::STK_Integral: 5795 Src = ImpCastExprToType(Src.get(), 5796 SrcTy->castAs<ComplexType>()->getElementType(), 5797 CK_FloatingComplexToReal); 5798 return CK_FloatingToIntegral; 5799 case Type::STK_CPointer: 5800 case Type::STK_ObjCObjectPointer: 5801 case Type::STK_BlockPointer: 5802 llvm_unreachable("valid complex float->pointer cast?"); 5803 case Type::STK_MemberPointer: 5804 llvm_unreachable("member pointer type in C"); 5805 } 5806 llvm_unreachable("Should have returned before this"); 5807 5808 case Type::STK_IntegralComplex: 5809 switch (DestTy->getScalarTypeKind()) { 5810 case Type::STK_FloatingComplex: 5811 return CK_IntegralComplexToFloatingComplex; 5812 case Type::STK_IntegralComplex: 5813 return CK_IntegralComplexCast; 5814 case Type::STK_Integral: { 5815 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5816 if (Context.hasSameType(ET, DestTy)) 5817 return CK_IntegralComplexToReal; 5818 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5819 return CK_IntegralCast; 5820 } 5821 case Type::STK_Bool: 5822 return CK_IntegralComplexToBoolean; 5823 case Type::STK_Floating: 5824 Src = ImpCastExprToType(Src.get(), 5825 SrcTy->castAs<ComplexType>()->getElementType(), 5826 CK_IntegralComplexToReal); 5827 return CK_IntegralToFloating; 5828 case Type::STK_CPointer: 5829 case Type::STK_ObjCObjectPointer: 5830 case Type::STK_BlockPointer: 5831 llvm_unreachable("valid complex int->pointer cast?"); 5832 case Type::STK_MemberPointer: 5833 llvm_unreachable("member pointer type in C"); 5834 } 5835 llvm_unreachable("Should have returned before this"); 5836 } 5837 5838 llvm_unreachable("Unhandled scalar cast"); 5839 } 5840 5841 static bool breakDownVectorType(QualType type, uint64_t &len, 5842 QualType &eltType) { 5843 // Vectors are simple. 5844 if (const VectorType *vecType = type->getAs<VectorType>()) { 5845 len = vecType->getNumElements(); 5846 eltType = vecType->getElementType(); 5847 assert(eltType->isScalarType()); 5848 return true; 5849 } 5850 5851 // We allow lax conversion to and from non-vector types, but only if 5852 // they're real types (i.e. non-complex, non-pointer scalar types). 5853 if (!type->isRealType()) return false; 5854 5855 len = 1; 5856 eltType = type; 5857 return true; 5858 } 5859 5860 /// Are the two types lax-compatible vector types? That is, given 5861 /// that one of them is a vector, do they have equal storage sizes, 5862 /// where the storage size is the number of elements times the element 5863 /// size? 5864 /// 5865 /// This will also return false if either of the types is neither a 5866 /// vector nor a real type. 5867 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5868 assert(destTy->isVectorType() || srcTy->isVectorType()); 5869 5870 // Disallow lax conversions between scalars and ExtVectors (these 5871 // conversions are allowed for other vector types because common headers 5872 // depend on them). Most scalar OP ExtVector cases are handled by the 5873 // splat path anyway, which does what we want (convert, not bitcast). 5874 // What this rules out for ExtVectors is crazy things like char4*float. 5875 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5876 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5877 5878 uint64_t srcLen, destLen; 5879 QualType srcEltTy, destEltTy; 5880 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5881 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5882 5883 // ASTContext::getTypeSize will return the size rounded up to a 5884 // power of 2, so instead of using that, we need to use the raw 5885 // element size multiplied by the element count. 5886 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5887 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5888 5889 return (srcLen * srcEltSize == destLen * destEltSize); 5890 } 5891 5892 /// Is this a legal conversion between two types, one of which is 5893 /// known to be a vector type? 5894 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5895 assert(destTy->isVectorType() || srcTy->isVectorType()); 5896 5897 if (!Context.getLangOpts().LaxVectorConversions) 5898 return false; 5899 return areLaxCompatibleVectorTypes(srcTy, destTy); 5900 } 5901 5902 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5903 CastKind &Kind) { 5904 assert(VectorTy->isVectorType() && "Not a vector type!"); 5905 5906 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5907 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5908 return Diag(R.getBegin(), 5909 Ty->isVectorType() ? 5910 diag::err_invalid_conversion_between_vectors : 5911 diag::err_invalid_conversion_between_vector_and_integer) 5912 << VectorTy << Ty << R; 5913 } else 5914 return Diag(R.getBegin(), 5915 diag::err_invalid_conversion_between_vector_and_scalar) 5916 << VectorTy << Ty << R; 5917 5918 Kind = CK_BitCast; 5919 return false; 5920 } 5921 5922 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5923 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5924 5925 if (DestElemTy == SplattedExpr->getType()) 5926 return SplattedExpr; 5927 5928 assert(DestElemTy->isFloatingType() || 5929 DestElemTy->isIntegralOrEnumerationType()); 5930 5931 CastKind CK; 5932 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5933 // OpenCL requires that we convert `true` boolean expressions to -1, but 5934 // only when splatting vectors. 5935 if (DestElemTy->isFloatingType()) { 5936 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5937 // in two steps: boolean to signed integral, then to floating. 5938 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5939 CK_BooleanToSignedIntegral); 5940 SplattedExpr = CastExprRes.get(); 5941 CK = CK_IntegralToFloating; 5942 } else { 5943 CK = CK_BooleanToSignedIntegral; 5944 } 5945 } else { 5946 ExprResult CastExprRes = SplattedExpr; 5947 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5948 if (CastExprRes.isInvalid()) 5949 return ExprError(); 5950 SplattedExpr = CastExprRes.get(); 5951 } 5952 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5953 } 5954 5955 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5956 Expr *CastExpr, CastKind &Kind) { 5957 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5958 5959 QualType SrcTy = CastExpr->getType(); 5960 5961 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5962 // an ExtVectorType. 5963 // In OpenCL, casts between vectors of different types are not allowed. 5964 // (See OpenCL 6.2). 5965 if (SrcTy->isVectorType()) { 5966 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5967 || (getLangOpts().OpenCL && 5968 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5969 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5970 << DestTy << SrcTy << R; 5971 return ExprError(); 5972 } 5973 Kind = CK_BitCast; 5974 return CastExpr; 5975 } 5976 5977 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5978 // conversion will take place first from scalar to elt type, and then 5979 // splat from elt type to vector. 5980 if (SrcTy->isPointerType()) 5981 return Diag(R.getBegin(), 5982 diag::err_invalid_conversion_between_vector_and_scalar) 5983 << DestTy << SrcTy << R; 5984 5985 Kind = CK_VectorSplat; 5986 return prepareVectorSplat(DestTy, CastExpr); 5987 } 5988 5989 ExprResult 5990 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5991 Declarator &D, ParsedType &Ty, 5992 SourceLocation RParenLoc, Expr *CastExpr) { 5993 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5994 "ActOnCastExpr(): missing type or expr"); 5995 5996 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5997 if (D.isInvalidType()) 5998 return ExprError(); 5999 6000 if (getLangOpts().CPlusPlus) { 6001 // Check that there are no default arguments (C++ only). 6002 CheckExtraCXXDefaultArguments(D); 6003 } else { 6004 // Make sure any TypoExprs have been dealt with. 6005 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6006 if (!Res.isUsable()) 6007 return ExprError(); 6008 CastExpr = Res.get(); 6009 } 6010 6011 checkUnusedDeclAttributes(D); 6012 6013 QualType castType = castTInfo->getType(); 6014 Ty = CreateParsedType(castType, castTInfo); 6015 6016 bool isVectorLiteral = false; 6017 6018 // Check for an altivec or OpenCL literal, 6019 // i.e. all the elements are integer constants. 6020 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6021 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6022 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6023 && castType->isVectorType() && (PE || PLE)) { 6024 if (PLE && PLE->getNumExprs() == 0) { 6025 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6026 return ExprError(); 6027 } 6028 if (PE || PLE->getNumExprs() == 1) { 6029 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6030 if (!E->getType()->isVectorType()) 6031 isVectorLiteral = true; 6032 } 6033 else 6034 isVectorLiteral = true; 6035 } 6036 6037 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6038 // then handle it as such. 6039 if (isVectorLiteral) 6040 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6041 6042 // If the Expr being casted is a ParenListExpr, handle it specially. 6043 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6044 // sequence of BinOp comma operators. 6045 if (isa<ParenListExpr>(CastExpr)) { 6046 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6047 if (Result.isInvalid()) return ExprError(); 6048 CastExpr = Result.get(); 6049 } 6050 6051 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6052 !getSourceManager().isInSystemMacro(LParenLoc)) 6053 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6054 6055 CheckTollFreeBridgeCast(castType, CastExpr); 6056 6057 CheckObjCBridgeRelatedCast(castType, CastExpr); 6058 6059 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6060 6061 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6062 } 6063 6064 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6065 SourceLocation RParenLoc, Expr *E, 6066 TypeSourceInfo *TInfo) { 6067 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6068 "Expected paren or paren list expression"); 6069 6070 Expr **exprs; 6071 unsigned numExprs; 6072 Expr *subExpr; 6073 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6074 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6075 LiteralLParenLoc = PE->getLParenLoc(); 6076 LiteralRParenLoc = PE->getRParenLoc(); 6077 exprs = PE->getExprs(); 6078 numExprs = PE->getNumExprs(); 6079 } else { // isa<ParenExpr> by assertion at function entrance 6080 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6081 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6082 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6083 exprs = &subExpr; 6084 numExprs = 1; 6085 } 6086 6087 QualType Ty = TInfo->getType(); 6088 assert(Ty->isVectorType() && "Expected vector type"); 6089 6090 SmallVector<Expr *, 8> initExprs; 6091 const VectorType *VTy = Ty->getAs<VectorType>(); 6092 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6093 6094 // '(...)' form of vector initialization in AltiVec: the number of 6095 // initializers must be one or must match the size of the vector. 6096 // If a single value is specified in the initializer then it will be 6097 // replicated to all the components of the vector 6098 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6099 // The number of initializers must be one or must match the size of the 6100 // vector. If a single value is specified in the initializer then it will 6101 // be replicated to all the components of the vector 6102 if (numExprs == 1) { 6103 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6104 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6105 if (Literal.isInvalid()) 6106 return ExprError(); 6107 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6108 PrepareScalarCast(Literal, ElemTy)); 6109 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6110 } 6111 else if (numExprs < numElems) { 6112 Diag(E->getExprLoc(), 6113 diag::err_incorrect_number_of_vector_initializers); 6114 return ExprError(); 6115 } 6116 else 6117 initExprs.append(exprs, exprs + numExprs); 6118 } 6119 else { 6120 // For OpenCL, when the number of initializers is a single value, 6121 // it will be replicated to all components of the vector. 6122 if (getLangOpts().OpenCL && 6123 VTy->getVectorKind() == VectorType::GenericVector && 6124 numExprs == 1) { 6125 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6126 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6127 if (Literal.isInvalid()) 6128 return ExprError(); 6129 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6130 PrepareScalarCast(Literal, ElemTy)); 6131 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6132 } 6133 6134 initExprs.append(exprs, exprs + numExprs); 6135 } 6136 // FIXME: This means that pretty-printing the final AST will produce curly 6137 // braces instead of the original commas. 6138 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6139 initExprs, LiteralRParenLoc); 6140 initE->setType(Ty); 6141 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6142 } 6143 6144 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6145 /// the ParenListExpr into a sequence of comma binary operators. 6146 ExprResult 6147 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6148 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6149 if (!E) 6150 return OrigExpr; 6151 6152 ExprResult Result(E->getExpr(0)); 6153 6154 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6155 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6156 E->getExpr(i)); 6157 6158 if (Result.isInvalid()) return ExprError(); 6159 6160 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6161 } 6162 6163 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6164 SourceLocation R, 6165 MultiExprArg Val) { 6166 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6167 return expr; 6168 } 6169 6170 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6171 /// constant and the other is not a pointer. Returns true if a diagnostic is 6172 /// emitted. 6173 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6174 SourceLocation QuestionLoc) { 6175 Expr *NullExpr = LHSExpr; 6176 Expr *NonPointerExpr = RHSExpr; 6177 Expr::NullPointerConstantKind NullKind = 6178 NullExpr->isNullPointerConstant(Context, 6179 Expr::NPC_ValueDependentIsNotNull); 6180 6181 if (NullKind == Expr::NPCK_NotNull) { 6182 NullExpr = RHSExpr; 6183 NonPointerExpr = LHSExpr; 6184 NullKind = 6185 NullExpr->isNullPointerConstant(Context, 6186 Expr::NPC_ValueDependentIsNotNull); 6187 } 6188 6189 if (NullKind == Expr::NPCK_NotNull) 6190 return false; 6191 6192 if (NullKind == Expr::NPCK_ZeroExpression) 6193 return false; 6194 6195 if (NullKind == Expr::NPCK_ZeroLiteral) { 6196 // In this case, check to make sure that we got here from a "NULL" 6197 // string in the source code. 6198 NullExpr = NullExpr->IgnoreParenImpCasts(); 6199 SourceLocation loc = NullExpr->getExprLoc(); 6200 if (!findMacroSpelling(loc, "NULL")) 6201 return false; 6202 } 6203 6204 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6205 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6206 << NonPointerExpr->getType() << DiagType 6207 << NonPointerExpr->getSourceRange(); 6208 return true; 6209 } 6210 6211 /// \brief Return false if the condition expression is valid, true otherwise. 6212 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6213 QualType CondTy = Cond->getType(); 6214 6215 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6216 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6217 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6218 << CondTy << Cond->getSourceRange(); 6219 return true; 6220 } 6221 6222 // C99 6.5.15p2 6223 if (CondTy->isScalarType()) return false; 6224 6225 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6226 << CondTy << Cond->getSourceRange(); 6227 return true; 6228 } 6229 6230 /// \brief Handle when one or both operands are void type. 6231 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6232 ExprResult &RHS) { 6233 Expr *LHSExpr = LHS.get(); 6234 Expr *RHSExpr = RHS.get(); 6235 6236 if (!LHSExpr->getType()->isVoidType()) 6237 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6238 << RHSExpr->getSourceRange(); 6239 if (!RHSExpr->getType()->isVoidType()) 6240 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6241 << LHSExpr->getSourceRange(); 6242 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6243 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6244 return S.Context.VoidTy; 6245 } 6246 6247 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6248 /// true otherwise. 6249 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6250 QualType PointerTy) { 6251 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6252 !NullExpr.get()->isNullPointerConstant(S.Context, 6253 Expr::NPC_ValueDependentIsNull)) 6254 return true; 6255 6256 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6257 return false; 6258 } 6259 6260 /// \brief Checks compatibility between two pointers and return the resulting 6261 /// type. 6262 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6263 ExprResult &RHS, 6264 SourceLocation Loc) { 6265 QualType LHSTy = LHS.get()->getType(); 6266 QualType RHSTy = RHS.get()->getType(); 6267 6268 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6269 // Two identical pointers types are always compatible. 6270 return LHSTy; 6271 } 6272 6273 QualType lhptee, rhptee; 6274 6275 // Get the pointee types. 6276 bool IsBlockPointer = false; 6277 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6278 lhptee = LHSBTy->getPointeeType(); 6279 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6280 IsBlockPointer = true; 6281 } else { 6282 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6283 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6284 } 6285 6286 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6287 // differently qualified versions of compatible types, the result type is 6288 // a pointer to an appropriately qualified version of the composite 6289 // type. 6290 6291 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6292 // clause doesn't make sense for our extensions. E.g. address space 2 should 6293 // be incompatible with address space 3: they may live on different devices or 6294 // anything. 6295 Qualifiers lhQual = lhptee.getQualifiers(); 6296 Qualifiers rhQual = rhptee.getQualifiers(); 6297 6298 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6299 lhQual.removeCVRQualifiers(); 6300 rhQual.removeCVRQualifiers(); 6301 6302 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6303 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6304 6305 // For OpenCL: 6306 // 1. If LHS and RHS types match exactly and: 6307 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6308 // (b) AS overlap => generate addrspacecast 6309 // (c) AS don't overlap => give an error 6310 // 2. if LHS and RHS types don't match: 6311 // (a) AS match => use standard C rules, generate bitcast 6312 // (b) AS overlap => generate addrspacecast instead of bitcast 6313 // (c) AS don't overlap => give an error 6314 6315 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6316 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6317 6318 // OpenCL cases 1c, 2a, 2b, and 2c. 6319 if (CompositeTy.isNull()) { 6320 // In this situation, we assume void* type. No especially good 6321 // reason, but this is what gcc does, and we do have to pick 6322 // to get a consistent AST. 6323 QualType incompatTy; 6324 if (S.getLangOpts().OpenCL) { 6325 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6326 // spaces is disallowed. 6327 unsigned ResultAddrSpace; 6328 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6329 // Cases 2a and 2b. 6330 ResultAddrSpace = lhQual.getAddressSpace(); 6331 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6332 // Cases 2a and 2b. 6333 ResultAddrSpace = rhQual.getAddressSpace(); 6334 } else { 6335 // Cases 1c and 2c. 6336 S.Diag(Loc, 6337 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6338 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6339 << RHS.get()->getSourceRange(); 6340 return QualType(); 6341 } 6342 6343 // Continue handling cases 2a and 2b. 6344 incompatTy = S.Context.getPointerType( 6345 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6346 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6347 (lhQual.getAddressSpace() != ResultAddrSpace) 6348 ? CK_AddressSpaceConversion /* 2b */ 6349 : CK_BitCast /* 2a */); 6350 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6351 (rhQual.getAddressSpace() != ResultAddrSpace) 6352 ? CK_AddressSpaceConversion /* 2b */ 6353 : CK_BitCast /* 2a */); 6354 } else { 6355 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6356 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6357 << RHS.get()->getSourceRange(); 6358 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6359 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6360 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6361 } 6362 return incompatTy; 6363 } 6364 6365 // The pointer types are compatible. 6366 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6367 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6368 if (IsBlockPointer) 6369 ResultTy = S.Context.getBlockPointerType(ResultTy); 6370 else { 6371 // Cases 1a and 1b for OpenCL. 6372 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6373 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6374 ? CK_BitCast /* 1a */ 6375 : CK_AddressSpaceConversion /* 1b */; 6376 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6377 ? CK_BitCast /* 1a */ 6378 : CK_AddressSpaceConversion /* 1b */; 6379 ResultTy = S.Context.getPointerType(ResultTy); 6380 } 6381 6382 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6383 // if the target type does not change. 6384 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6385 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6386 return ResultTy; 6387 } 6388 6389 /// \brief Return the resulting type when the operands are both block pointers. 6390 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6391 ExprResult &LHS, 6392 ExprResult &RHS, 6393 SourceLocation Loc) { 6394 QualType LHSTy = LHS.get()->getType(); 6395 QualType RHSTy = RHS.get()->getType(); 6396 6397 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6398 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6399 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6400 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6401 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6402 return destType; 6403 } 6404 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6405 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6406 << RHS.get()->getSourceRange(); 6407 return QualType(); 6408 } 6409 6410 // We have 2 block pointer types. 6411 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6412 } 6413 6414 /// \brief Return the resulting type when the operands are both pointers. 6415 static QualType 6416 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6417 ExprResult &RHS, 6418 SourceLocation Loc) { 6419 // get the pointer types 6420 QualType LHSTy = LHS.get()->getType(); 6421 QualType RHSTy = RHS.get()->getType(); 6422 6423 // get the "pointed to" types 6424 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6425 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6426 6427 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6428 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6429 // Figure out necessary qualifiers (C99 6.5.15p6) 6430 QualType destPointee 6431 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6432 QualType destType = S.Context.getPointerType(destPointee); 6433 // Add qualifiers if necessary. 6434 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6435 // Promote to void*. 6436 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6437 return destType; 6438 } 6439 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6440 QualType destPointee 6441 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6442 QualType destType = S.Context.getPointerType(destPointee); 6443 // Add qualifiers if necessary. 6444 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6445 // Promote to void*. 6446 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6447 return destType; 6448 } 6449 6450 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6451 } 6452 6453 /// \brief Return false if the first expression is not an integer and the second 6454 /// expression is not a pointer, true otherwise. 6455 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6456 Expr* PointerExpr, SourceLocation Loc, 6457 bool IsIntFirstExpr) { 6458 if (!PointerExpr->getType()->isPointerType() || 6459 !Int.get()->getType()->isIntegerType()) 6460 return false; 6461 6462 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6463 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6464 6465 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6466 << Expr1->getType() << Expr2->getType() 6467 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6468 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6469 CK_IntegralToPointer); 6470 return true; 6471 } 6472 6473 /// \brief Simple conversion between integer and floating point types. 6474 /// 6475 /// Used when handling the OpenCL conditional operator where the 6476 /// condition is a vector while the other operands are scalar. 6477 /// 6478 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6479 /// types are either integer or floating type. Between the two 6480 /// operands, the type with the higher rank is defined as the "result 6481 /// type". The other operand needs to be promoted to the same type. No 6482 /// other type promotion is allowed. We cannot use 6483 /// UsualArithmeticConversions() for this purpose, since it always 6484 /// promotes promotable types. 6485 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6486 ExprResult &RHS, 6487 SourceLocation QuestionLoc) { 6488 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6489 if (LHS.isInvalid()) 6490 return QualType(); 6491 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6492 if (RHS.isInvalid()) 6493 return QualType(); 6494 6495 // For conversion purposes, we ignore any qualifiers. 6496 // For example, "const float" and "float" are equivalent. 6497 QualType LHSType = 6498 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6499 QualType RHSType = 6500 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6501 6502 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6503 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6504 << LHSType << LHS.get()->getSourceRange(); 6505 return QualType(); 6506 } 6507 6508 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6509 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6510 << RHSType << RHS.get()->getSourceRange(); 6511 return QualType(); 6512 } 6513 6514 // If both types are identical, no conversion is needed. 6515 if (LHSType == RHSType) 6516 return LHSType; 6517 6518 // Now handle "real" floating types (i.e. float, double, long double). 6519 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6520 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6521 /*IsCompAssign = */ false); 6522 6523 // Finally, we have two differing integer types. 6524 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6525 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6526 } 6527 6528 /// \brief Convert scalar operands to a vector that matches the 6529 /// condition in length. 6530 /// 6531 /// Used when handling the OpenCL conditional operator where the 6532 /// condition is a vector while the other operands are scalar. 6533 /// 6534 /// We first compute the "result type" for the scalar operands 6535 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6536 /// into a vector of that type where the length matches the condition 6537 /// vector type. s6.11.6 requires that the element types of the result 6538 /// and the condition must have the same number of bits. 6539 static QualType 6540 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6541 QualType CondTy, SourceLocation QuestionLoc) { 6542 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6543 if (ResTy.isNull()) return QualType(); 6544 6545 const VectorType *CV = CondTy->getAs<VectorType>(); 6546 assert(CV); 6547 6548 // Determine the vector result type 6549 unsigned NumElements = CV->getNumElements(); 6550 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6551 6552 // Ensure that all types have the same number of bits 6553 if (S.Context.getTypeSize(CV->getElementType()) 6554 != S.Context.getTypeSize(ResTy)) { 6555 // Since VectorTy is created internally, it does not pretty print 6556 // with an OpenCL name. Instead, we just print a description. 6557 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6558 SmallString<64> Str; 6559 llvm::raw_svector_ostream OS(Str); 6560 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6561 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6562 << CondTy << OS.str(); 6563 return QualType(); 6564 } 6565 6566 // Convert operands to the vector result type 6567 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6568 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6569 6570 return VectorTy; 6571 } 6572 6573 /// \brief Return false if this is a valid OpenCL condition vector 6574 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6575 SourceLocation QuestionLoc) { 6576 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6577 // integral type. 6578 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6579 assert(CondTy); 6580 QualType EleTy = CondTy->getElementType(); 6581 if (EleTy->isIntegerType()) return false; 6582 6583 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6584 << Cond->getType() << Cond->getSourceRange(); 6585 return true; 6586 } 6587 6588 /// \brief Return false if the vector condition type and the vector 6589 /// result type are compatible. 6590 /// 6591 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6592 /// number of elements, and their element types have the same number 6593 /// of bits. 6594 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6595 SourceLocation QuestionLoc) { 6596 const VectorType *CV = CondTy->getAs<VectorType>(); 6597 const VectorType *RV = VecResTy->getAs<VectorType>(); 6598 assert(CV && RV); 6599 6600 if (CV->getNumElements() != RV->getNumElements()) { 6601 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6602 << CondTy << VecResTy; 6603 return true; 6604 } 6605 6606 QualType CVE = CV->getElementType(); 6607 QualType RVE = RV->getElementType(); 6608 6609 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6610 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6611 << CondTy << VecResTy; 6612 return true; 6613 } 6614 6615 return false; 6616 } 6617 6618 /// \brief Return the resulting type for the conditional operator in 6619 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6620 /// s6.3.i) when the condition is a vector type. 6621 static QualType 6622 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6623 ExprResult &LHS, ExprResult &RHS, 6624 SourceLocation QuestionLoc) { 6625 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6626 if (Cond.isInvalid()) 6627 return QualType(); 6628 QualType CondTy = Cond.get()->getType(); 6629 6630 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6631 return QualType(); 6632 6633 // If either operand is a vector then find the vector type of the 6634 // result as specified in OpenCL v1.1 s6.3.i. 6635 if (LHS.get()->getType()->isVectorType() || 6636 RHS.get()->getType()->isVectorType()) { 6637 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6638 /*isCompAssign*/false, 6639 /*AllowBothBool*/true, 6640 /*AllowBoolConversions*/false); 6641 if (VecResTy.isNull()) return QualType(); 6642 // The result type must match the condition type as specified in 6643 // OpenCL v1.1 s6.11.6. 6644 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6645 return QualType(); 6646 return VecResTy; 6647 } 6648 6649 // Both operands are scalar. 6650 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6651 } 6652 6653 /// \brief Return true if the Expr is block type 6654 static bool checkBlockType(Sema &S, const Expr *E) { 6655 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6656 QualType Ty = CE->getCallee()->getType(); 6657 if (Ty->isBlockPointerType()) { 6658 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6659 return true; 6660 } 6661 } 6662 return false; 6663 } 6664 6665 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6666 /// In that case, LHS = cond. 6667 /// C99 6.5.15 6668 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6669 ExprResult &RHS, ExprValueKind &VK, 6670 ExprObjectKind &OK, 6671 SourceLocation QuestionLoc) { 6672 6673 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6674 if (!LHSResult.isUsable()) return QualType(); 6675 LHS = LHSResult; 6676 6677 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6678 if (!RHSResult.isUsable()) return QualType(); 6679 RHS = RHSResult; 6680 6681 // C++ is sufficiently different to merit its own checker. 6682 if (getLangOpts().CPlusPlus) 6683 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6684 6685 VK = VK_RValue; 6686 OK = OK_Ordinary; 6687 6688 // The OpenCL operator with a vector condition is sufficiently 6689 // different to merit its own checker. 6690 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6691 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6692 6693 // First, check the condition. 6694 Cond = UsualUnaryConversions(Cond.get()); 6695 if (Cond.isInvalid()) 6696 return QualType(); 6697 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6698 return QualType(); 6699 6700 // Now check the two expressions. 6701 if (LHS.get()->getType()->isVectorType() || 6702 RHS.get()->getType()->isVectorType()) 6703 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6704 /*AllowBothBool*/true, 6705 /*AllowBoolConversions*/false); 6706 6707 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6708 if (LHS.isInvalid() || RHS.isInvalid()) 6709 return QualType(); 6710 6711 QualType LHSTy = LHS.get()->getType(); 6712 QualType RHSTy = RHS.get()->getType(); 6713 6714 // Diagnose attempts to convert between __float128 and long double where 6715 // such conversions currently can't be handled. 6716 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6717 Diag(QuestionLoc, 6718 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6720 return QualType(); 6721 } 6722 6723 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6724 // selection operator (?:). 6725 if (getLangOpts().OpenCL && 6726 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6727 return QualType(); 6728 } 6729 6730 // If both operands have arithmetic type, do the usual arithmetic conversions 6731 // to find a common type: C99 6.5.15p3,5. 6732 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6733 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6734 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6735 6736 return ResTy; 6737 } 6738 6739 // If both operands are the same structure or union type, the result is that 6740 // type. 6741 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6742 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6743 if (LHSRT->getDecl() == RHSRT->getDecl()) 6744 // "If both the operands have structure or union type, the result has 6745 // that type." This implies that CV qualifiers are dropped. 6746 return LHSTy.getUnqualifiedType(); 6747 // FIXME: Type of conditional expression must be complete in C mode. 6748 } 6749 6750 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6751 // The following || allows only one side to be void (a GCC-ism). 6752 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6753 return checkConditionalVoidType(*this, LHS, RHS); 6754 } 6755 6756 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6757 // the type of the other operand." 6758 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6759 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6760 6761 // All objective-c pointer type analysis is done here. 6762 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6763 QuestionLoc); 6764 if (LHS.isInvalid() || RHS.isInvalid()) 6765 return QualType(); 6766 if (!compositeType.isNull()) 6767 return compositeType; 6768 6769 6770 // Handle block pointer types. 6771 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6772 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6773 QuestionLoc); 6774 6775 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6776 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6777 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6778 QuestionLoc); 6779 6780 // GCC compatibility: soften pointer/integer mismatch. Note that 6781 // null pointers have been filtered out by this point. 6782 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6783 /*isIntFirstExpr=*/true)) 6784 return RHSTy; 6785 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6786 /*isIntFirstExpr=*/false)) 6787 return LHSTy; 6788 6789 // Emit a better diagnostic if one of the expressions is a null pointer 6790 // constant and the other is not a pointer type. In this case, the user most 6791 // likely forgot to take the address of the other expression. 6792 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6793 return QualType(); 6794 6795 // Otherwise, the operands are not compatible. 6796 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6797 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6798 << RHS.get()->getSourceRange(); 6799 return QualType(); 6800 } 6801 6802 /// FindCompositeObjCPointerType - Helper method to find composite type of 6803 /// two objective-c pointer types of the two input expressions. 6804 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6805 SourceLocation QuestionLoc) { 6806 QualType LHSTy = LHS.get()->getType(); 6807 QualType RHSTy = RHS.get()->getType(); 6808 6809 // Handle things like Class and struct objc_class*. Here we case the result 6810 // to the pseudo-builtin, because that will be implicitly cast back to the 6811 // redefinition type if an attempt is made to access its fields. 6812 if (LHSTy->isObjCClassType() && 6813 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6814 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6815 return LHSTy; 6816 } 6817 if (RHSTy->isObjCClassType() && 6818 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6819 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6820 return RHSTy; 6821 } 6822 // And the same for struct objc_object* / id 6823 if (LHSTy->isObjCIdType() && 6824 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6825 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6826 return LHSTy; 6827 } 6828 if (RHSTy->isObjCIdType() && 6829 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6830 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6831 return RHSTy; 6832 } 6833 // And the same for struct objc_selector* / SEL 6834 if (Context.isObjCSelType(LHSTy) && 6835 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6836 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6837 return LHSTy; 6838 } 6839 if (Context.isObjCSelType(RHSTy) && 6840 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6841 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6842 return RHSTy; 6843 } 6844 // Check constraints for Objective-C object pointers types. 6845 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6846 6847 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6848 // Two identical object pointer types are always compatible. 6849 return LHSTy; 6850 } 6851 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6852 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6853 QualType compositeType = LHSTy; 6854 6855 // If both operands are interfaces and either operand can be 6856 // assigned to the other, use that type as the composite 6857 // type. This allows 6858 // xxx ? (A*) a : (B*) b 6859 // where B is a subclass of A. 6860 // 6861 // Additionally, as for assignment, if either type is 'id' 6862 // allow silent coercion. Finally, if the types are 6863 // incompatible then make sure to use 'id' as the composite 6864 // type so the result is acceptable for sending messages to. 6865 6866 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6867 // It could return the composite type. 6868 if (!(compositeType = 6869 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6870 // Nothing more to do. 6871 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6872 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6873 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6874 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6875 } else if ((LHSTy->isObjCQualifiedIdType() || 6876 RHSTy->isObjCQualifiedIdType()) && 6877 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6878 // Need to handle "id<xx>" explicitly. 6879 // GCC allows qualified id and any Objective-C type to devolve to 6880 // id. Currently localizing to here until clear this should be 6881 // part of ObjCQualifiedIdTypesAreCompatible. 6882 compositeType = Context.getObjCIdType(); 6883 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6884 compositeType = Context.getObjCIdType(); 6885 } else { 6886 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6887 << LHSTy << RHSTy 6888 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6889 QualType incompatTy = Context.getObjCIdType(); 6890 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6891 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6892 return incompatTy; 6893 } 6894 // The object pointer types are compatible. 6895 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6896 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6897 return compositeType; 6898 } 6899 // Check Objective-C object pointer types and 'void *' 6900 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6901 if (getLangOpts().ObjCAutoRefCount) { 6902 // ARC forbids the implicit conversion of object pointers to 'void *', 6903 // so these types are not compatible. 6904 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6905 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6906 LHS = RHS = true; 6907 return QualType(); 6908 } 6909 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6910 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6911 QualType destPointee 6912 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6913 QualType destType = Context.getPointerType(destPointee); 6914 // Add qualifiers if necessary. 6915 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6916 // Promote to void*. 6917 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6918 return destType; 6919 } 6920 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6921 if (getLangOpts().ObjCAutoRefCount) { 6922 // ARC forbids the implicit conversion of object pointers to 'void *', 6923 // so these types are not compatible. 6924 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6925 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6926 LHS = RHS = true; 6927 return QualType(); 6928 } 6929 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6930 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6931 QualType destPointee 6932 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6933 QualType destType = Context.getPointerType(destPointee); 6934 // Add qualifiers if necessary. 6935 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6936 // Promote to void*. 6937 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6938 return destType; 6939 } 6940 return QualType(); 6941 } 6942 6943 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6944 /// ParenRange in parentheses. 6945 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6946 const PartialDiagnostic &Note, 6947 SourceRange ParenRange) { 6948 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6949 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6950 EndLoc.isValid()) { 6951 Self.Diag(Loc, Note) 6952 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6953 << FixItHint::CreateInsertion(EndLoc, ")"); 6954 } else { 6955 // We can't display the parentheses, so just show the bare note. 6956 Self.Diag(Loc, Note) << ParenRange; 6957 } 6958 } 6959 6960 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6961 return BinaryOperator::isAdditiveOp(Opc) || 6962 BinaryOperator::isMultiplicativeOp(Opc) || 6963 BinaryOperator::isShiftOp(Opc); 6964 } 6965 6966 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6967 /// expression, either using a built-in or overloaded operator, 6968 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6969 /// expression. 6970 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6971 Expr **RHSExprs) { 6972 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6973 E = E->IgnoreImpCasts(); 6974 E = E->IgnoreConversionOperator(); 6975 E = E->IgnoreImpCasts(); 6976 6977 // Built-in binary operator. 6978 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6979 if (IsArithmeticOp(OP->getOpcode())) { 6980 *Opcode = OP->getOpcode(); 6981 *RHSExprs = OP->getRHS(); 6982 return true; 6983 } 6984 } 6985 6986 // Overloaded operator. 6987 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6988 if (Call->getNumArgs() != 2) 6989 return false; 6990 6991 // Make sure this is really a binary operator that is safe to pass into 6992 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6993 OverloadedOperatorKind OO = Call->getOperator(); 6994 if (OO < OO_Plus || OO > OO_Arrow || 6995 OO == OO_PlusPlus || OO == OO_MinusMinus) 6996 return false; 6997 6998 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6999 if (IsArithmeticOp(OpKind)) { 7000 *Opcode = OpKind; 7001 *RHSExprs = Call->getArg(1); 7002 return true; 7003 } 7004 } 7005 7006 return false; 7007 } 7008 7009 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7010 /// or is a logical expression such as (x==y) which has int type, but is 7011 /// commonly interpreted as boolean. 7012 static bool ExprLooksBoolean(Expr *E) { 7013 E = E->IgnoreParenImpCasts(); 7014 7015 if (E->getType()->isBooleanType()) 7016 return true; 7017 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7018 return OP->isComparisonOp() || OP->isLogicalOp(); 7019 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7020 return OP->getOpcode() == UO_LNot; 7021 if (E->getType()->isPointerType()) 7022 return true; 7023 7024 return false; 7025 } 7026 7027 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7028 /// and binary operator are mixed in a way that suggests the programmer assumed 7029 /// the conditional operator has higher precedence, for example: 7030 /// "int x = a + someBinaryCondition ? 1 : 2". 7031 static void DiagnoseConditionalPrecedence(Sema &Self, 7032 SourceLocation OpLoc, 7033 Expr *Condition, 7034 Expr *LHSExpr, 7035 Expr *RHSExpr) { 7036 BinaryOperatorKind CondOpcode; 7037 Expr *CondRHS; 7038 7039 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7040 return; 7041 if (!ExprLooksBoolean(CondRHS)) 7042 return; 7043 7044 // The condition is an arithmetic binary expression, with a right- 7045 // hand side that looks boolean, so warn. 7046 7047 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7048 << Condition->getSourceRange() 7049 << BinaryOperator::getOpcodeStr(CondOpcode); 7050 7051 SuggestParentheses(Self, OpLoc, 7052 Self.PDiag(diag::note_precedence_silence) 7053 << BinaryOperator::getOpcodeStr(CondOpcode), 7054 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7055 7056 SuggestParentheses(Self, OpLoc, 7057 Self.PDiag(diag::note_precedence_conditional_first), 7058 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7059 } 7060 7061 /// Compute the nullability of a conditional expression. 7062 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7063 QualType LHSTy, QualType RHSTy, 7064 ASTContext &Ctx) { 7065 if (!ResTy->isAnyPointerType()) 7066 return ResTy; 7067 7068 auto GetNullability = [&Ctx](QualType Ty) { 7069 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7070 if (Kind) 7071 return *Kind; 7072 return NullabilityKind::Unspecified; 7073 }; 7074 7075 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7076 NullabilityKind MergedKind; 7077 7078 // Compute nullability of a binary conditional expression. 7079 if (IsBin) { 7080 if (LHSKind == NullabilityKind::NonNull) 7081 MergedKind = NullabilityKind::NonNull; 7082 else 7083 MergedKind = RHSKind; 7084 // Compute nullability of a normal conditional expression. 7085 } else { 7086 if (LHSKind == NullabilityKind::Nullable || 7087 RHSKind == NullabilityKind::Nullable) 7088 MergedKind = NullabilityKind::Nullable; 7089 else if (LHSKind == NullabilityKind::NonNull) 7090 MergedKind = RHSKind; 7091 else if (RHSKind == NullabilityKind::NonNull) 7092 MergedKind = LHSKind; 7093 else 7094 MergedKind = NullabilityKind::Unspecified; 7095 } 7096 7097 // Return if ResTy already has the correct nullability. 7098 if (GetNullability(ResTy) == MergedKind) 7099 return ResTy; 7100 7101 // Strip all nullability from ResTy. 7102 while (ResTy->getNullability(Ctx)) 7103 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7104 7105 // Create a new AttributedType with the new nullability kind. 7106 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7107 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7108 } 7109 7110 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7111 /// in the case of a the GNU conditional expr extension. 7112 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7113 SourceLocation ColonLoc, 7114 Expr *CondExpr, Expr *LHSExpr, 7115 Expr *RHSExpr) { 7116 if (!getLangOpts().CPlusPlus) { 7117 // C cannot handle TypoExpr nodes in the condition because it 7118 // doesn't handle dependent types properly, so make sure any TypoExprs have 7119 // been dealt with before checking the operands. 7120 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7121 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7122 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7123 7124 if (!CondResult.isUsable()) 7125 return ExprError(); 7126 7127 if (LHSExpr) { 7128 if (!LHSResult.isUsable()) 7129 return ExprError(); 7130 } 7131 7132 if (!RHSResult.isUsable()) 7133 return ExprError(); 7134 7135 CondExpr = CondResult.get(); 7136 LHSExpr = LHSResult.get(); 7137 RHSExpr = RHSResult.get(); 7138 } 7139 7140 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7141 // was the condition. 7142 OpaqueValueExpr *opaqueValue = nullptr; 7143 Expr *commonExpr = nullptr; 7144 if (!LHSExpr) { 7145 commonExpr = CondExpr; 7146 // Lower out placeholder types first. This is important so that we don't 7147 // try to capture a placeholder. This happens in few cases in C++; such 7148 // as Objective-C++'s dictionary subscripting syntax. 7149 if (commonExpr->hasPlaceholderType()) { 7150 ExprResult result = CheckPlaceholderExpr(commonExpr); 7151 if (!result.isUsable()) return ExprError(); 7152 commonExpr = result.get(); 7153 } 7154 // We usually want to apply unary conversions *before* saving, except 7155 // in the special case of a C++ l-value conditional. 7156 if (!(getLangOpts().CPlusPlus 7157 && !commonExpr->isTypeDependent() 7158 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7159 && commonExpr->isGLValue() 7160 && commonExpr->isOrdinaryOrBitFieldObject() 7161 && RHSExpr->isOrdinaryOrBitFieldObject() 7162 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7163 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7164 if (commonRes.isInvalid()) 7165 return ExprError(); 7166 commonExpr = commonRes.get(); 7167 } 7168 7169 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7170 commonExpr->getType(), 7171 commonExpr->getValueKind(), 7172 commonExpr->getObjectKind(), 7173 commonExpr); 7174 LHSExpr = CondExpr = opaqueValue; 7175 } 7176 7177 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7178 ExprValueKind VK = VK_RValue; 7179 ExprObjectKind OK = OK_Ordinary; 7180 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7181 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7182 VK, OK, QuestionLoc); 7183 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7184 RHS.isInvalid()) 7185 return ExprError(); 7186 7187 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7188 RHS.get()); 7189 7190 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7191 7192 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7193 Context); 7194 7195 if (!commonExpr) 7196 return new (Context) 7197 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7198 RHS.get(), result, VK, OK); 7199 7200 return new (Context) BinaryConditionalOperator( 7201 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7202 ColonLoc, result, VK, OK); 7203 } 7204 7205 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7206 // being closely modeled after the C99 spec:-). The odd characteristic of this 7207 // routine is it effectively iqnores the qualifiers on the top level pointee. 7208 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7209 // FIXME: add a couple examples in this comment. 7210 static Sema::AssignConvertType 7211 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7212 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7213 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7214 7215 // get the "pointed to" type (ignoring qualifiers at the top level) 7216 const Type *lhptee, *rhptee; 7217 Qualifiers lhq, rhq; 7218 std::tie(lhptee, lhq) = 7219 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7220 std::tie(rhptee, rhq) = 7221 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7222 7223 Sema::AssignConvertType ConvTy = Sema::Compatible; 7224 7225 // C99 6.5.16.1p1: This following citation is common to constraints 7226 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7227 // qualifiers of the type *pointed to* by the right; 7228 7229 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7230 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7231 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7232 // Ignore lifetime for further calculation. 7233 lhq.removeObjCLifetime(); 7234 rhq.removeObjCLifetime(); 7235 } 7236 7237 if (!lhq.compatiblyIncludes(rhq)) { 7238 // Treat address-space mismatches as fatal. TODO: address subspaces 7239 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7240 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7241 7242 // It's okay to add or remove GC or lifetime qualifiers when converting to 7243 // and from void*. 7244 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7245 .compatiblyIncludes( 7246 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7247 && (lhptee->isVoidType() || rhptee->isVoidType())) 7248 ; // keep old 7249 7250 // Treat lifetime mismatches as fatal. 7251 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7252 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7253 7254 // For GCC/MS compatibility, other qualifier mismatches are treated 7255 // as still compatible in C. 7256 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7257 } 7258 7259 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7260 // incomplete type and the other is a pointer to a qualified or unqualified 7261 // version of void... 7262 if (lhptee->isVoidType()) { 7263 if (rhptee->isIncompleteOrObjectType()) 7264 return ConvTy; 7265 7266 // As an extension, we allow cast to/from void* to function pointer. 7267 assert(rhptee->isFunctionType()); 7268 return Sema::FunctionVoidPointer; 7269 } 7270 7271 if (rhptee->isVoidType()) { 7272 if (lhptee->isIncompleteOrObjectType()) 7273 return ConvTy; 7274 7275 // As an extension, we allow cast to/from void* to function pointer. 7276 assert(lhptee->isFunctionType()); 7277 return Sema::FunctionVoidPointer; 7278 } 7279 7280 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7281 // unqualified versions of compatible types, ... 7282 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7283 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7284 // Check if the pointee types are compatible ignoring the sign. 7285 // We explicitly check for char so that we catch "char" vs 7286 // "unsigned char" on systems where "char" is unsigned. 7287 if (lhptee->isCharType()) 7288 ltrans = S.Context.UnsignedCharTy; 7289 else if (lhptee->hasSignedIntegerRepresentation()) 7290 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7291 7292 if (rhptee->isCharType()) 7293 rtrans = S.Context.UnsignedCharTy; 7294 else if (rhptee->hasSignedIntegerRepresentation()) 7295 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7296 7297 if (ltrans == rtrans) { 7298 // Types are compatible ignoring the sign. Qualifier incompatibility 7299 // takes priority over sign incompatibility because the sign 7300 // warning can be disabled. 7301 if (ConvTy != Sema::Compatible) 7302 return ConvTy; 7303 7304 return Sema::IncompatiblePointerSign; 7305 } 7306 7307 // If we are a multi-level pointer, it's possible that our issue is simply 7308 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7309 // the eventual target type is the same and the pointers have the same 7310 // level of indirection, this must be the issue. 7311 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7312 do { 7313 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7314 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7315 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7316 7317 if (lhptee == rhptee) 7318 return Sema::IncompatibleNestedPointerQualifiers; 7319 } 7320 7321 // General pointer incompatibility takes priority over qualifiers. 7322 return Sema::IncompatiblePointer; 7323 } 7324 if (!S.getLangOpts().CPlusPlus && 7325 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7326 return Sema::IncompatiblePointer; 7327 return ConvTy; 7328 } 7329 7330 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7331 /// block pointer types are compatible or whether a block and normal pointer 7332 /// are compatible. It is more restrict than comparing two function pointer 7333 // types. 7334 static Sema::AssignConvertType 7335 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7336 QualType RHSType) { 7337 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7338 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7339 7340 QualType lhptee, rhptee; 7341 7342 // get the "pointed to" type (ignoring qualifiers at the top level) 7343 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7344 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7345 7346 // In C++, the types have to match exactly. 7347 if (S.getLangOpts().CPlusPlus) 7348 return Sema::IncompatibleBlockPointer; 7349 7350 Sema::AssignConvertType ConvTy = Sema::Compatible; 7351 7352 // For blocks we enforce that qualifiers are identical. 7353 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7354 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7355 7356 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7357 return Sema::IncompatibleBlockPointer; 7358 7359 return ConvTy; 7360 } 7361 7362 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7363 /// for assignment compatibility. 7364 static Sema::AssignConvertType 7365 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7366 QualType RHSType) { 7367 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7368 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7369 7370 if (LHSType->isObjCBuiltinType()) { 7371 // Class is not compatible with ObjC object pointers. 7372 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7373 !RHSType->isObjCQualifiedClassType()) 7374 return Sema::IncompatiblePointer; 7375 return Sema::Compatible; 7376 } 7377 if (RHSType->isObjCBuiltinType()) { 7378 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7379 !LHSType->isObjCQualifiedClassType()) 7380 return Sema::IncompatiblePointer; 7381 return Sema::Compatible; 7382 } 7383 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7384 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7385 7386 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7387 // make an exception for id<P> 7388 !LHSType->isObjCQualifiedIdType()) 7389 return Sema::CompatiblePointerDiscardsQualifiers; 7390 7391 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7392 return Sema::Compatible; 7393 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7394 return Sema::IncompatibleObjCQualifiedId; 7395 return Sema::IncompatiblePointer; 7396 } 7397 7398 Sema::AssignConvertType 7399 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7400 QualType LHSType, QualType RHSType) { 7401 // Fake up an opaque expression. We don't actually care about what 7402 // cast operations are required, so if CheckAssignmentConstraints 7403 // adds casts to this they'll be wasted, but fortunately that doesn't 7404 // usually happen on valid code. 7405 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7406 ExprResult RHSPtr = &RHSExpr; 7407 CastKind K = CK_Invalid; 7408 7409 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7410 } 7411 7412 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7413 /// has code to accommodate several GCC extensions when type checking 7414 /// pointers. Here are some objectionable examples that GCC considers warnings: 7415 /// 7416 /// int a, *pint; 7417 /// short *pshort; 7418 /// struct foo *pfoo; 7419 /// 7420 /// pint = pshort; // warning: assignment from incompatible pointer type 7421 /// a = pint; // warning: assignment makes integer from pointer without a cast 7422 /// pint = a; // warning: assignment makes pointer from integer without a cast 7423 /// pint = pfoo; // warning: assignment from incompatible pointer type 7424 /// 7425 /// As a result, the code for dealing with pointers is more complex than the 7426 /// C99 spec dictates. 7427 /// 7428 /// Sets 'Kind' for any result kind except Incompatible. 7429 Sema::AssignConvertType 7430 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7431 CastKind &Kind, bool ConvertRHS) { 7432 QualType RHSType = RHS.get()->getType(); 7433 QualType OrigLHSType = LHSType; 7434 7435 // Get canonical types. We're not formatting these types, just comparing 7436 // them. 7437 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7438 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7439 7440 // Common case: no conversion required. 7441 if (LHSType == RHSType) { 7442 Kind = CK_NoOp; 7443 return Compatible; 7444 } 7445 7446 // If we have an atomic type, try a non-atomic assignment, then just add an 7447 // atomic qualification step. 7448 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7449 Sema::AssignConvertType result = 7450 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7451 if (result != Compatible) 7452 return result; 7453 if (Kind != CK_NoOp && ConvertRHS) 7454 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7455 Kind = CK_NonAtomicToAtomic; 7456 return Compatible; 7457 } 7458 7459 // If the left-hand side is a reference type, then we are in a 7460 // (rare!) case where we've allowed the use of references in C, 7461 // e.g., as a parameter type in a built-in function. In this case, 7462 // just make sure that the type referenced is compatible with the 7463 // right-hand side type. The caller is responsible for adjusting 7464 // LHSType so that the resulting expression does not have reference 7465 // type. 7466 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7467 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7468 Kind = CK_LValueBitCast; 7469 return Compatible; 7470 } 7471 return Incompatible; 7472 } 7473 7474 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7475 // to the same ExtVector type. 7476 if (LHSType->isExtVectorType()) { 7477 if (RHSType->isExtVectorType()) 7478 return Incompatible; 7479 if (RHSType->isArithmeticType()) { 7480 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7481 if (ConvertRHS) 7482 RHS = prepareVectorSplat(LHSType, RHS.get()); 7483 Kind = CK_VectorSplat; 7484 return Compatible; 7485 } 7486 } 7487 7488 // Conversions to or from vector type. 7489 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7490 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7491 // Allow assignments of an AltiVec vector type to an equivalent GCC 7492 // vector type and vice versa 7493 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7494 Kind = CK_BitCast; 7495 return Compatible; 7496 } 7497 7498 // If we are allowing lax vector conversions, and LHS and RHS are both 7499 // vectors, the total size only needs to be the same. This is a bitcast; 7500 // no bits are changed but the result type is different. 7501 if (isLaxVectorConversion(RHSType, LHSType)) { 7502 Kind = CK_BitCast; 7503 return IncompatibleVectors; 7504 } 7505 } 7506 7507 // When the RHS comes from another lax conversion (e.g. binops between 7508 // scalars and vectors) the result is canonicalized as a vector. When the 7509 // LHS is also a vector, the lax is allowed by the condition above. Handle 7510 // the case where LHS is a scalar. 7511 if (LHSType->isScalarType()) { 7512 const VectorType *VecType = RHSType->getAs<VectorType>(); 7513 if (VecType && VecType->getNumElements() == 1 && 7514 isLaxVectorConversion(RHSType, LHSType)) { 7515 ExprResult *VecExpr = &RHS; 7516 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7517 Kind = CK_BitCast; 7518 return Compatible; 7519 } 7520 } 7521 7522 return Incompatible; 7523 } 7524 7525 // Diagnose attempts to convert between __float128 and long double where 7526 // such conversions currently can't be handled. 7527 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7528 return Incompatible; 7529 7530 // Arithmetic conversions. 7531 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7532 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7533 if (ConvertRHS) 7534 Kind = PrepareScalarCast(RHS, LHSType); 7535 return Compatible; 7536 } 7537 7538 // Conversions to normal pointers. 7539 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7540 // U* -> T* 7541 if (isa<PointerType>(RHSType)) { 7542 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7543 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7544 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7545 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7546 } 7547 7548 // int -> T* 7549 if (RHSType->isIntegerType()) { 7550 Kind = CK_IntegralToPointer; // FIXME: null? 7551 return IntToPointer; 7552 } 7553 7554 // C pointers are not compatible with ObjC object pointers, 7555 // with two exceptions: 7556 if (isa<ObjCObjectPointerType>(RHSType)) { 7557 // - conversions to void* 7558 if (LHSPointer->getPointeeType()->isVoidType()) { 7559 Kind = CK_BitCast; 7560 return Compatible; 7561 } 7562 7563 // - conversions from 'Class' to the redefinition type 7564 if (RHSType->isObjCClassType() && 7565 Context.hasSameType(LHSType, 7566 Context.getObjCClassRedefinitionType())) { 7567 Kind = CK_BitCast; 7568 return Compatible; 7569 } 7570 7571 Kind = CK_BitCast; 7572 return IncompatiblePointer; 7573 } 7574 7575 // U^ -> void* 7576 if (RHSType->getAs<BlockPointerType>()) { 7577 if (LHSPointer->getPointeeType()->isVoidType()) { 7578 Kind = CK_BitCast; 7579 return Compatible; 7580 } 7581 } 7582 7583 return Incompatible; 7584 } 7585 7586 // Conversions to block pointers. 7587 if (isa<BlockPointerType>(LHSType)) { 7588 // U^ -> T^ 7589 if (RHSType->isBlockPointerType()) { 7590 Kind = CK_BitCast; 7591 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7592 } 7593 7594 // int or null -> T^ 7595 if (RHSType->isIntegerType()) { 7596 Kind = CK_IntegralToPointer; // FIXME: null 7597 return IntToBlockPointer; 7598 } 7599 7600 // id -> T^ 7601 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7602 Kind = CK_AnyPointerToBlockPointerCast; 7603 return Compatible; 7604 } 7605 7606 // void* -> T^ 7607 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7608 if (RHSPT->getPointeeType()->isVoidType()) { 7609 Kind = CK_AnyPointerToBlockPointerCast; 7610 return Compatible; 7611 } 7612 7613 return Incompatible; 7614 } 7615 7616 // Conversions to Objective-C pointers. 7617 if (isa<ObjCObjectPointerType>(LHSType)) { 7618 // A* -> B* 7619 if (RHSType->isObjCObjectPointerType()) { 7620 Kind = CK_BitCast; 7621 Sema::AssignConvertType result = 7622 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7623 if (getLangOpts().ObjCAutoRefCount && 7624 result == Compatible && 7625 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7626 result = IncompatibleObjCWeakRef; 7627 return result; 7628 } 7629 7630 // int or null -> A* 7631 if (RHSType->isIntegerType()) { 7632 Kind = CK_IntegralToPointer; // FIXME: null 7633 return IntToPointer; 7634 } 7635 7636 // In general, C pointers are not compatible with ObjC object pointers, 7637 // with two exceptions: 7638 if (isa<PointerType>(RHSType)) { 7639 Kind = CK_CPointerToObjCPointerCast; 7640 7641 // - conversions from 'void*' 7642 if (RHSType->isVoidPointerType()) { 7643 return Compatible; 7644 } 7645 7646 // - conversions to 'Class' from its redefinition type 7647 if (LHSType->isObjCClassType() && 7648 Context.hasSameType(RHSType, 7649 Context.getObjCClassRedefinitionType())) { 7650 return Compatible; 7651 } 7652 7653 return IncompatiblePointer; 7654 } 7655 7656 // Only under strict condition T^ is compatible with an Objective-C pointer. 7657 if (RHSType->isBlockPointerType() && 7658 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7659 if (ConvertRHS) 7660 maybeExtendBlockObject(RHS); 7661 Kind = CK_BlockPointerToObjCPointerCast; 7662 return Compatible; 7663 } 7664 7665 return Incompatible; 7666 } 7667 7668 // Conversions from pointers that are not covered by the above. 7669 if (isa<PointerType>(RHSType)) { 7670 // T* -> _Bool 7671 if (LHSType == Context.BoolTy) { 7672 Kind = CK_PointerToBoolean; 7673 return Compatible; 7674 } 7675 7676 // T* -> int 7677 if (LHSType->isIntegerType()) { 7678 Kind = CK_PointerToIntegral; 7679 return PointerToInt; 7680 } 7681 7682 return Incompatible; 7683 } 7684 7685 // Conversions from Objective-C pointers that are not covered by the above. 7686 if (isa<ObjCObjectPointerType>(RHSType)) { 7687 // T* -> _Bool 7688 if (LHSType == Context.BoolTy) { 7689 Kind = CK_PointerToBoolean; 7690 return Compatible; 7691 } 7692 7693 // T* -> int 7694 if (LHSType->isIntegerType()) { 7695 Kind = CK_PointerToIntegral; 7696 return PointerToInt; 7697 } 7698 7699 return Incompatible; 7700 } 7701 7702 // struct A -> struct B 7703 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7704 if (Context.typesAreCompatible(LHSType, RHSType)) { 7705 Kind = CK_NoOp; 7706 return Compatible; 7707 } 7708 } 7709 7710 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7711 Kind = CK_IntToOCLSampler; 7712 return Compatible; 7713 } 7714 7715 return Incompatible; 7716 } 7717 7718 /// \brief Constructs a transparent union from an expression that is 7719 /// used to initialize the transparent union. 7720 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7721 ExprResult &EResult, QualType UnionType, 7722 FieldDecl *Field) { 7723 // Build an initializer list that designates the appropriate member 7724 // of the transparent union. 7725 Expr *E = EResult.get(); 7726 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7727 E, SourceLocation()); 7728 Initializer->setType(UnionType); 7729 Initializer->setInitializedFieldInUnion(Field); 7730 7731 // Build a compound literal constructing a value of the transparent 7732 // union type from this initializer list. 7733 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7734 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7735 VK_RValue, Initializer, false); 7736 } 7737 7738 Sema::AssignConvertType 7739 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7740 ExprResult &RHS) { 7741 QualType RHSType = RHS.get()->getType(); 7742 7743 // If the ArgType is a Union type, we want to handle a potential 7744 // transparent_union GCC extension. 7745 const RecordType *UT = ArgType->getAsUnionType(); 7746 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7747 return Incompatible; 7748 7749 // The field to initialize within the transparent union. 7750 RecordDecl *UD = UT->getDecl(); 7751 FieldDecl *InitField = nullptr; 7752 // It's compatible if the expression matches any of the fields. 7753 for (auto *it : UD->fields()) { 7754 if (it->getType()->isPointerType()) { 7755 // If the transparent union contains a pointer type, we allow: 7756 // 1) void pointer 7757 // 2) null pointer constant 7758 if (RHSType->isPointerType()) 7759 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7760 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7761 InitField = it; 7762 break; 7763 } 7764 7765 if (RHS.get()->isNullPointerConstant(Context, 7766 Expr::NPC_ValueDependentIsNull)) { 7767 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7768 CK_NullToPointer); 7769 InitField = it; 7770 break; 7771 } 7772 } 7773 7774 CastKind Kind = CK_Invalid; 7775 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7776 == Compatible) { 7777 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7778 InitField = it; 7779 break; 7780 } 7781 } 7782 7783 if (!InitField) 7784 return Incompatible; 7785 7786 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7787 return Compatible; 7788 } 7789 7790 Sema::AssignConvertType 7791 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7792 bool Diagnose, 7793 bool DiagnoseCFAudited, 7794 bool ConvertRHS) { 7795 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7796 // we can't avoid *all* modifications at the moment, so we need some somewhere 7797 // to put the updated value. 7798 ExprResult LocalRHS = CallerRHS; 7799 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7800 7801 if (getLangOpts().CPlusPlus) { 7802 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7803 // C++ 5.17p3: If the left operand is not of class type, the 7804 // expression is implicitly converted (C++ 4) to the 7805 // cv-unqualified type of the left operand. 7806 ExprResult Res; 7807 if (Diagnose) { 7808 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7809 AA_Assigning); 7810 } else { 7811 ImplicitConversionSequence ICS = 7812 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7813 /*SuppressUserConversions=*/false, 7814 /*AllowExplicit=*/false, 7815 /*InOverloadResolution=*/false, 7816 /*CStyle=*/false, 7817 /*AllowObjCWritebackConversion=*/false); 7818 if (ICS.isFailure()) 7819 return Incompatible; 7820 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7821 ICS, AA_Assigning); 7822 } 7823 if (Res.isInvalid()) 7824 return Incompatible; 7825 Sema::AssignConvertType result = Compatible; 7826 if (getLangOpts().ObjCAutoRefCount && 7827 !CheckObjCARCUnavailableWeakConversion(LHSType, 7828 RHS.get()->getType())) 7829 result = IncompatibleObjCWeakRef; 7830 RHS = Res; 7831 return result; 7832 } 7833 7834 // FIXME: Currently, we fall through and treat C++ classes like C 7835 // structures. 7836 // FIXME: We also fall through for atomics; not sure what should 7837 // happen there, though. 7838 } else if (RHS.get()->getType() == Context.OverloadTy) { 7839 // As a set of extensions to C, we support overloading on functions. These 7840 // functions need to be resolved here. 7841 DeclAccessPair DAP; 7842 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7843 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7844 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7845 else 7846 return Incompatible; 7847 } 7848 7849 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7850 // a null pointer constant. 7851 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7852 LHSType->isBlockPointerType()) && 7853 RHS.get()->isNullPointerConstant(Context, 7854 Expr::NPC_ValueDependentIsNull)) { 7855 if (Diagnose || ConvertRHS) { 7856 CastKind Kind; 7857 CXXCastPath Path; 7858 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7859 /*IgnoreBaseAccess=*/false, Diagnose); 7860 if (ConvertRHS) 7861 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7862 } 7863 return Compatible; 7864 } 7865 7866 // This check seems unnatural, however it is necessary to ensure the proper 7867 // conversion of functions/arrays. If the conversion were done for all 7868 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7869 // expressions that suppress this implicit conversion (&, sizeof). 7870 // 7871 // Suppress this for references: C++ 8.5.3p5. 7872 if (!LHSType->isReferenceType()) { 7873 // FIXME: We potentially allocate here even if ConvertRHS is false. 7874 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7875 if (RHS.isInvalid()) 7876 return Incompatible; 7877 } 7878 7879 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7880 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7881 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7882 if (PDecl && !PDecl->hasDefinition()) { 7883 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7884 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7885 } 7886 } 7887 7888 CastKind Kind = CK_Invalid; 7889 Sema::AssignConvertType result = 7890 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7891 7892 // C99 6.5.16.1p2: The value of the right operand is converted to the 7893 // type of the assignment expression. 7894 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7895 // so that we can use references in built-in functions even in C. 7896 // The getNonReferenceType() call makes sure that the resulting expression 7897 // does not have reference type. 7898 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7899 QualType Ty = LHSType.getNonLValueExprType(Context); 7900 Expr *E = RHS.get(); 7901 7902 // Check for various Objective-C errors. If we are not reporting 7903 // diagnostics and just checking for errors, e.g., during overload 7904 // resolution, return Incompatible to indicate the failure. 7905 if (getLangOpts().ObjCAutoRefCount && 7906 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7907 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7908 if (!Diagnose) 7909 return Incompatible; 7910 } 7911 if (getLangOpts().ObjC1 && 7912 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7913 E->getType(), E, Diagnose) || 7914 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7915 if (!Diagnose) 7916 return Incompatible; 7917 // Replace the expression with a corrected version and continue so we 7918 // can find further errors. 7919 RHS = E; 7920 return Compatible; 7921 } 7922 7923 if (ConvertRHS) 7924 RHS = ImpCastExprToType(E, Ty, Kind); 7925 } 7926 return result; 7927 } 7928 7929 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7930 ExprResult &RHS) { 7931 Diag(Loc, diag::err_typecheck_invalid_operands) 7932 << LHS.get()->getType() << RHS.get()->getType() 7933 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7934 return QualType(); 7935 } 7936 7937 /// Try to convert a value of non-vector type to a vector type by converting 7938 /// the type to the element type of the vector and then performing a splat. 7939 /// If the language is OpenCL, we only use conversions that promote scalar 7940 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7941 /// for float->int. 7942 /// 7943 /// \param scalar - if non-null, actually perform the conversions 7944 /// \return true if the operation fails (but without diagnosing the failure) 7945 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7946 QualType scalarTy, 7947 QualType vectorEltTy, 7948 QualType vectorTy) { 7949 // The conversion to apply to the scalar before splatting it, 7950 // if necessary. 7951 CastKind scalarCast = CK_Invalid; 7952 7953 if (vectorEltTy->isIntegralType(S.Context)) { 7954 if (!scalarTy->isIntegralType(S.Context)) 7955 return true; 7956 if (S.getLangOpts().OpenCL && 7957 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7958 return true; 7959 scalarCast = CK_IntegralCast; 7960 } else if (vectorEltTy->isRealFloatingType()) { 7961 if (scalarTy->isRealFloatingType()) { 7962 if (S.getLangOpts().OpenCL && 7963 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7964 return true; 7965 scalarCast = CK_FloatingCast; 7966 } 7967 else if (scalarTy->isIntegralType(S.Context)) 7968 scalarCast = CK_IntegralToFloating; 7969 else 7970 return true; 7971 } else { 7972 return true; 7973 } 7974 7975 // Adjust scalar if desired. 7976 if (scalar) { 7977 if (scalarCast != CK_Invalid) 7978 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7979 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7980 } 7981 return false; 7982 } 7983 7984 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7985 SourceLocation Loc, bool IsCompAssign, 7986 bool AllowBothBool, 7987 bool AllowBoolConversions) { 7988 if (!IsCompAssign) { 7989 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7990 if (LHS.isInvalid()) 7991 return QualType(); 7992 } 7993 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7994 if (RHS.isInvalid()) 7995 return QualType(); 7996 7997 // For conversion purposes, we ignore any qualifiers. 7998 // For example, "const float" and "float" are equivalent. 7999 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8000 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8001 8002 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8003 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8004 assert(LHSVecType || RHSVecType); 8005 8006 // AltiVec-style "vector bool op vector bool" combinations are allowed 8007 // for some operators but not others. 8008 if (!AllowBothBool && 8009 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8010 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8011 return InvalidOperands(Loc, LHS, RHS); 8012 8013 // If the vector types are identical, return. 8014 if (Context.hasSameType(LHSType, RHSType)) 8015 return LHSType; 8016 8017 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8018 if (LHSVecType && RHSVecType && 8019 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8020 if (isa<ExtVectorType>(LHSVecType)) { 8021 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8022 return LHSType; 8023 } 8024 8025 if (!IsCompAssign) 8026 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8027 return RHSType; 8028 } 8029 8030 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8031 // can be mixed, with the result being the non-bool type. The non-bool 8032 // operand must have integer element type. 8033 if (AllowBoolConversions && LHSVecType && RHSVecType && 8034 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8035 (Context.getTypeSize(LHSVecType->getElementType()) == 8036 Context.getTypeSize(RHSVecType->getElementType()))) { 8037 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8038 LHSVecType->getElementType()->isIntegerType() && 8039 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8040 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8041 return LHSType; 8042 } 8043 if (!IsCompAssign && 8044 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8045 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8046 RHSVecType->getElementType()->isIntegerType()) { 8047 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8048 return RHSType; 8049 } 8050 } 8051 8052 // If there's an ext-vector type and a scalar, try to convert the scalar to 8053 // the vector element type and splat. 8054 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8055 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8056 LHSVecType->getElementType(), LHSType)) 8057 return LHSType; 8058 } 8059 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8060 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8061 LHSType, RHSVecType->getElementType(), 8062 RHSType)) 8063 return RHSType; 8064 } 8065 8066 // If we're allowing lax vector conversions, only the total (data) size needs 8067 // to be the same. If one of the types is scalar, the result is always the 8068 // vector type. Don't allow this if the scalar operand is an lvalue. 8069 QualType VecType = LHSVecType ? LHSType : RHSType; 8070 QualType ScalarType = LHSVecType ? RHSType : LHSType; 8071 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS; 8072 if (isLaxVectorConversion(ScalarType, VecType) && 8073 !ScalarExpr->get()->isLValue()) { 8074 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast); 8075 return VecType; 8076 } 8077 8078 // Okay, the expression is invalid. 8079 8080 // If there's a non-vector, non-real operand, diagnose that. 8081 if ((!RHSVecType && !RHSType->isRealType()) || 8082 (!LHSVecType && !LHSType->isRealType())) { 8083 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8084 << LHSType << RHSType 8085 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8086 return QualType(); 8087 } 8088 8089 // OpenCL V1.1 6.2.6.p1: 8090 // If the operands are of more than one vector type, then an error shall 8091 // occur. Implicit conversions between vector types are not permitted, per 8092 // section 6.2.1. 8093 if (getLangOpts().OpenCL && 8094 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8095 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8096 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8097 << RHSType; 8098 return QualType(); 8099 } 8100 8101 // Otherwise, use the generic diagnostic. 8102 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8103 << LHSType << RHSType 8104 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8105 return QualType(); 8106 } 8107 8108 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8109 // expression. These are mainly cases where the null pointer is used as an 8110 // integer instead of a pointer. 8111 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8112 SourceLocation Loc, bool IsCompare) { 8113 // The canonical way to check for a GNU null is with isNullPointerConstant, 8114 // but we use a bit of a hack here for speed; this is a relatively 8115 // hot path, and isNullPointerConstant is slow. 8116 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8117 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8118 8119 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8120 8121 // Avoid analyzing cases where the result will either be invalid (and 8122 // diagnosed as such) or entirely valid and not something to warn about. 8123 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8124 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8125 return; 8126 8127 // Comparison operations would not make sense with a null pointer no matter 8128 // what the other expression is. 8129 if (!IsCompare) { 8130 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8131 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8132 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8133 return; 8134 } 8135 8136 // The rest of the operations only make sense with a null pointer 8137 // if the other expression is a pointer. 8138 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8139 NonNullType->canDecayToPointerType()) 8140 return; 8141 8142 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8143 << LHSNull /* LHS is NULL */ << NonNullType 8144 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8145 } 8146 8147 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8148 ExprResult &RHS, 8149 SourceLocation Loc, bool IsDiv) { 8150 // Check for division/remainder by zero. 8151 llvm::APSInt RHSValue; 8152 if (!RHS.get()->isValueDependent() && 8153 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8154 S.DiagRuntimeBehavior(Loc, RHS.get(), 8155 S.PDiag(diag::warn_remainder_division_by_zero) 8156 << IsDiv << RHS.get()->getSourceRange()); 8157 } 8158 8159 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8160 SourceLocation Loc, 8161 bool IsCompAssign, bool IsDiv) { 8162 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8163 8164 if (LHS.get()->getType()->isVectorType() || 8165 RHS.get()->getType()->isVectorType()) 8166 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8167 /*AllowBothBool*/getLangOpts().AltiVec, 8168 /*AllowBoolConversions*/false); 8169 8170 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8171 if (LHS.isInvalid() || RHS.isInvalid()) 8172 return QualType(); 8173 8174 8175 if (compType.isNull() || !compType->isArithmeticType()) 8176 return InvalidOperands(Loc, LHS, RHS); 8177 if (IsDiv) 8178 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8179 return compType; 8180 } 8181 8182 QualType Sema::CheckRemainderOperands( 8183 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8184 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8185 8186 if (LHS.get()->getType()->isVectorType() || 8187 RHS.get()->getType()->isVectorType()) { 8188 if (LHS.get()->getType()->hasIntegerRepresentation() && 8189 RHS.get()->getType()->hasIntegerRepresentation()) 8190 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8191 /*AllowBothBool*/getLangOpts().AltiVec, 8192 /*AllowBoolConversions*/false); 8193 return InvalidOperands(Loc, LHS, RHS); 8194 } 8195 8196 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8197 if (LHS.isInvalid() || RHS.isInvalid()) 8198 return QualType(); 8199 8200 if (compType.isNull() || !compType->isIntegerType()) 8201 return InvalidOperands(Loc, LHS, RHS); 8202 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8203 return compType; 8204 } 8205 8206 /// \brief Diagnose invalid arithmetic on two void pointers. 8207 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8208 Expr *LHSExpr, Expr *RHSExpr) { 8209 S.Diag(Loc, S.getLangOpts().CPlusPlus 8210 ? diag::err_typecheck_pointer_arith_void_type 8211 : diag::ext_gnu_void_ptr) 8212 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8213 << RHSExpr->getSourceRange(); 8214 } 8215 8216 /// \brief Diagnose invalid arithmetic on a void pointer. 8217 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8218 Expr *Pointer) { 8219 S.Diag(Loc, S.getLangOpts().CPlusPlus 8220 ? diag::err_typecheck_pointer_arith_void_type 8221 : diag::ext_gnu_void_ptr) 8222 << 0 /* one pointer */ << Pointer->getSourceRange(); 8223 } 8224 8225 /// \brief Diagnose invalid arithmetic on two function pointers. 8226 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8227 Expr *LHS, Expr *RHS) { 8228 assert(LHS->getType()->isAnyPointerType()); 8229 assert(RHS->getType()->isAnyPointerType()); 8230 S.Diag(Loc, S.getLangOpts().CPlusPlus 8231 ? diag::err_typecheck_pointer_arith_function_type 8232 : diag::ext_gnu_ptr_func_arith) 8233 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8234 // We only show the second type if it differs from the first. 8235 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8236 RHS->getType()) 8237 << RHS->getType()->getPointeeType() 8238 << LHS->getSourceRange() << RHS->getSourceRange(); 8239 } 8240 8241 /// \brief Diagnose invalid arithmetic on a function pointer. 8242 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8243 Expr *Pointer) { 8244 assert(Pointer->getType()->isAnyPointerType()); 8245 S.Diag(Loc, S.getLangOpts().CPlusPlus 8246 ? diag::err_typecheck_pointer_arith_function_type 8247 : diag::ext_gnu_ptr_func_arith) 8248 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8249 << 0 /* one pointer, so only one type */ 8250 << Pointer->getSourceRange(); 8251 } 8252 8253 /// \brief Emit error if Operand is incomplete pointer type 8254 /// 8255 /// \returns True if pointer has incomplete type 8256 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8257 Expr *Operand) { 8258 QualType ResType = Operand->getType(); 8259 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8260 ResType = ResAtomicType->getValueType(); 8261 8262 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8263 QualType PointeeTy = ResType->getPointeeType(); 8264 return S.RequireCompleteType(Loc, PointeeTy, 8265 diag::err_typecheck_arithmetic_incomplete_type, 8266 PointeeTy, Operand->getSourceRange()); 8267 } 8268 8269 /// \brief Check the validity of an arithmetic pointer operand. 8270 /// 8271 /// If the operand has pointer type, this code will check for pointer types 8272 /// which are invalid in arithmetic operations. These will be diagnosed 8273 /// appropriately, including whether or not the use is supported as an 8274 /// extension. 8275 /// 8276 /// \returns True when the operand is valid to use (even if as an extension). 8277 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8278 Expr *Operand) { 8279 QualType ResType = Operand->getType(); 8280 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8281 ResType = ResAtomicType->getValueType(); 8282 8283 if (!ResType->isAnyPointerType()) return true; 8284 8285 QualType PointeeTy = ResType->getPointeeType(); 8286 if (PointeeTy->isVoidType()) { 8287 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8288 return !S.getLangOpts().CPlusPlus; 8289 } 8290 if (PointeeTy->isFunctionType()) { 8291 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8292 return !S.getLangOpts().CPlusPlus; 8293 } 8294 8295 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8296 8297 return true; 8298 } 8299 8300 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8301 /// operands. 8302 /// 8303 /// This routine will diagnose any invalid arithmetic on pointer operands much 8304 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8305 /// for emitting a single diagnostic even for operations where both LHS and RHS 8306 /// are (potentially problematic) pointers. 8307 /// 8308 /// \returns True when the operand is valid to use (even if as an extension). 8309 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8310 Expr *LHSExpr, Expr *RHSExpr) { 8311 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8312 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8313 if (!isLHSPointer && !isRHSPointer) return true; 8314 8315 QualType LHSPointeeTy, RHSPointeeTy; 8316 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8317 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8318 8319 // if both are pointers check if operation is valid wrt address spaces 8320 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8321 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8322 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8323 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8324 S.Diag(Loc, 8325 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8326 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8327 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8328 return false; 8329 } 8330 } 8331 8332 // Check for arithmetic on pointers to incomplete types. 8333 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8334 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8335 if (isLHSVoidPtr || isRHSVoidPtr) { 8336 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8337 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8338 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8339 8340 return !S.getLangOpts().CPlusPlus; 8341 } 8342 8343 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8344 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8345 if (isLHSFuncPtr || isRHSFuncPtr) { 8346 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8347 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8348 RHSExpr); 8349 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8350 8351 return !S.getLangOpts().CPlusPlus; 8352 } 8353 8354 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8355 return false; 8356 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8357 return false; 8358 8359 return true; 8360 } 8361 8362 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8363 /// literal. 8364 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8365 Expr *LHSExpr, Expr *RHSExpr) { 8366 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8367 Expr* IndexExpr = RHSExpr; 8368 if (!StrExpr) { 8369 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8370 IndexExpr = LHSExpr; 8371 } 8372 8373 bool IsStringPlusInt = StrExpr && 8374 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8375 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8376 return; 8377 8378 llvm::APSInt index; 8379 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8380 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8381 if (index.isNonNegative() && 8382 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8383 index.isUnsigned())) 8384 return; 8385 } 8386 8387 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8388 Self.Diag(OpLoc, diag::warn_string_plus_int) 8389 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8390 8391 // Only print a fixit for "str" + int, not for int + "str". 8392 if (IndexExpr == RHSExpr) { 8393 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8394 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8395 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8396 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8397 << FixItHint::CreateInsertion(EndLoc, "]"); 8398 } else 8399 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8400 } 8401 8402 /// \brief Emit a warning when adding a char literal to a string. 8403 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8404 Expr *LHSExpr, Expr *RHSExpr) { 8405 const Expr *StringRefExpr = LHSExpr; 8406 const CharacterLiteral *CharExpr = 8407 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8408 8409 if (!CharExpr) { 8410 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8411 StringRefExpr = RHSExpr; 8412 } 8413 8414 if (!CharExpr || !StringRefExpr) 8415 return; 8416 8417 const QualType StringType = StringRefExpr->getType(); 8418 8419 // Return if not a PointerType. 8420 if (!StringType->isAnyPointerType()) 8421 return; 8422 8423 // Return if not a CharacterType. 8424 if (!StringType->getPointeeType()->isAnyCharacterType()) 8425 return; 8426 8427 ASTContext &Ctx = Self.getASTContext(); 8428 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8429 8430 const QualType CharType = CharExpr->getType(); 8431 if (!CharType->isAnyCharacterType() && 8432 CharType->isIntegerType() && 8433 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8434 Self.Diag(OpLoc, diag::warn_string_plus_char) 8435 << DiagRange << Ctx.CharTy; 8436 } else { 8437 Self.Diag(OpLoc, diag::warn_string_plus_char) 8438 << DiagRange << CharExpr->getType(); 8439 } 8440 8441 // Only print a fixit for str + char, not for char + str. 8442 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8443 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8444 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8445 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8446 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8447 << FixItHint::CreateInsertion(EndLoc, "]"); 8448 } else { 8449 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8450 } 8451 } 8452 8453 /// \brief Emit error when two pointers are incompatible. 8454 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8455 Expr *LHSExpr, Expr *RHSExpr) { 8456 assert(LHSExpr->getType()->isAnyPointerType()); 8457 assert(RHSExpr->getType()->isAnyPointerType()); 8458 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8459 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8460 << RHSExpr->getSourceRange(); 8461 } 8462 8463 // C99 6.5.6 8464 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8465 SourceLocation Loc, BinaryOperatorKind Opc, 8466 QualType* CompLHSTy) { 8467 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8468 8469 if (LHS.get()->getType()->isVectorType() || 8470 RHS.get()->getType()->isVectorType()) { 8471 QualType compType = CheckVectorOperands( 8472 LHS, RHS, Loc, CompLHSTy, 8473 /*AllowBothBool*/getLangOpts().AltiVec, 8474 /*AllowBoolConversions*/getLangOpts().ZVector); 8475 if (CompLHSTy) *CompLHSTy = compType; 8476 return compType; 8477 } 8478 8479 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8480 if (LHS.isInvalid() || RHS.isInvalid()) 8481 return QualType(); 8482 8483 // Diagnose "string literal" '+' int and string '+' "char literal". 8484 if (Opc == BO_Add) { 8485 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8486 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8487 } 8488 8489 // handle the common case first (both operands are arithmetic). 8490 if (!compType.isNull() && compType->isArithmeticType()) { 8491 if (CompLHSTy) *CompLHSTy = compType; 8492 return compType; 8493 } 8494 8495 // Type-checking. Ultimately the pointer's going to be in PExp; 8496 // note that we bias towards the LHS being the pointer. 8497 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8498 8499 bool isObjCPointer; 8500 if (PExp->getType()->isPointerType()) { 8501 isObjCPointer = false; 8502 } else if (PExp->getType()->isObjCObjectPointerType()) { 8503 isObjCPointer = true; 8504 } else { 8505 std::swap(PExp, IExp); 8506 if (PExp->getType()->isPointerType()) { 8507 isObjCPointer = false; 8508 } else if (PExp->getType()->isObjCObjectPointerType()) { 8509 isObjCPointer = true; 8510 } else { 8511 return InvalidOperands(Loc, LHS, RHS); 8512 } 8513 } 8514 assert(PExp->getType()->isAnyPointerType()); 8515 8516 if (!IExp->getType()->isIntegerType()) 8517 return InvalidOperands(Loc, LHS, RHS); 8518 8519 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8520 return QualType(); 8521 8522 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8523 return QualType(); 8524 8525 // Check array bounds for pointer arithemtic 8526 CheckArrayAccess(PExp, IExp); 8527 8528 if (CompLHSTy) { 8529 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8530 if (LHSTy.isNull()) { 8531 LHSTy = LHS.get()->getType(); 8532 if (LHSTy->isPromotableIntegerType()) 8533 LHSTy = Context.getPromotedIntegerType(LHSTy); 8534 } 8535 *CompLHSTy = LHSTy; 8536 } 8537 8538 return PExp->getType(); 8539 } 8540 8541 // C99 6.5.6 8542 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8543 SourceLocation Loc, 8544 QualType* CompLHSTy) { 8545 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8546 8547 if (LHS.get()->getType()->isVectorType() || 8548 RHS.get()->getType()->isVectorType()) { 8549 QualType compType = CheckVectorOperands( 8550 LHS, RHS, Loc, CompLHSTy, 8551 /*AllowBothBool*/getLangOpts().AltiVec, 8552 /*AllowBoolConversions*/getLangOpts().ZVector); 8553 if (CompLHSTy) *CompLHSTy = compType; 8554 return compType; 8555 } 8556 8557 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8558 if (LHS.isInvalid() || RHS.isInvalid()) 8559 return QualType(); 8560 8561 // Enforce type constraints: C99 6.5.6p3. 8562 8563 // Handle the common case first (both operands are arithmetic). 8564 if (!compType.isNull() && compType->isArithmeticType()) { 8565 if (CompLHSTy) *CompLHSTy = compType; 8566 return compType; 8567 } 8568 8569 // Either ptr - int or ptr - ptr. 8570 if (LHS.get()->getType()->isAnyPointerType()) { 8571 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8572 8573 // Diagnose bad cases where we step over interface counts. 8574 if (LHS.get()->getType()->isObjCObjectPointerType() && 8575 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8576 return QualType(); 8577 8578 // The result type of a pointer-int computation is the pointer type. 8579 if (RHS.get()->getType()->isIntegerType()) { 8580 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8581 return QualType(); 8582 8583 // Check array bounds for pointer arithemtic 8584 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8585 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8586 8587 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8588 return LHS.get()->getType(); 8589 } 8590 8591 // Handle pointer-pointer subtractions. 8592 if (const PointerType *RHSPTy 8593 = RHS.get()->getType()->getAs<PointerType>()) { 8594 QualType rpointee = RHSPTy->getPointeeType(); 8595 8596 if (getLangOpts().CPlusPlus) { 8597 // Pointee types must be the same: C++ [expr.add] 8598 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8599 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8600 } 8601 } else { 8602 // Pointee types must be compatible C99 6.5.6p3 8603 if (!Context.typesAreCompatible( 8604 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8605 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8606 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8607 return QualType(); 8608 } 8609 } 8610 8611 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8612 LHS.get(), RHS.get())) 8613 return QualType(); 8614 8615 // The pointee type may have zero size. As an extension, a structure or 8616 // union may have zero size or an array may have zero length. In this 8617 // case subtraction does not make sense. 8618 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8619 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8620 if (ElementSize.isZero()) { 8621 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8622 << rpointee.getUnqualifiedType() 8623 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8624 } 8625 } 8626 8627 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8628 return Context.getPointerDiffType(); 8629 } 8630 } 8631 8632 return InvalidOperands(Loc, LHS, RHS); 8633 } 8634 8635 static bool isScopedEnumerationType(QualType T) { 8636 if (const EnumType *ET = T->getAs<EnumType>()) 8637 return ET->getDecl()->isScoped(); 8638 return false; 8639 } 8640 8641 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8642 SourceLocation Loc, BinaryOperatorKind Opc, 8643 QualType LHSType) { 8644 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8645 // so skip remaining warnings as we don't want to modify values within Sema. 8646 if (S.getLangOpts().OpenCL) 8647 return; 8648 8649 llvm::APSInt Right; 8650 // Check right/shifter operand 8651 if (RHS.get()->isValueDependent() || 8652 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8653 return; 8654 8655 if (Right.isNegative()) { 8656 S.DiagRuntimeBehavior(Loc, RHS.get(), 8657 S.PDiag(diag::warn_shift_negative) 8658 << RHS.get()->getSourceRange()); 8659 return; 8660 } 8661 llvm::APInt LeftBits(Right.getBitWidth(), 8662 S.Context.getTypeSize(LHS.get()->getType())); 8663 if (Right.uge(LeftBits)) { 8664 S.DiagRuntimeBehavior(Loc, RHS.get(), 8665 S.PDiag(diag::warn_shift_gt_typewidth) 8666 << RHS.get()->getSourceRange()); 8667 return; 8668 } 8669 if (Opc != BO_Shl) 8670 return; 8671 8672 // When left shifting an ICE which is signed, we can check for overflow which 8673 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8674 // integers have defined behavior modulo one more than the maximum value 8675 // representable in the result type, so never warn for those. 8676 llvm::APSInt Left; 8677 if (LHS.get()->isValueDependent() || 8678 LHSType->hasUnsignedIntegerRepresentation() || 8679 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8680 return; 8681 8682 // If LHS does not have a signed type and non-negative value 8683 // then, the behavior is undefined. Warn about it. 8684 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8685 S.DiagRuntimeBehavior(Loc, LHS.get(), 8686 S.PDiag(diag::warn_shift_lhs_negative) 8687 << LHS.get()->getSourceRange()); 8688 return; 8689 } 8690 8691 llvm::APInt ResultBits = 8692 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8693 if (LeftBits.uge(ResultBits)) 8694 return; 8695 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8696 Result = Result.shl(Right); 8697 8698 // Print the bit representation of the signed integer as an unsigned 8699 // hexadecimal number. 8700 SmallString<40> HexResult; 8701 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8702 8703 // If we are only missing a sign bit, this is less likely to result in actual 8704 // bugs -- if the result is cast back to an unsigned type, it will have the 8705 // expected value. Thus we place this behind a different warning that can be 8706 // turned off separately if needed. 8707 if (LeftBits == ResultBits - 1) { 8708 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8709 << HexResult << LHSType 8710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8711 return; 8712 } 8713 8714 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8715 << HexResult.str() << Result.getMinSignedBits() << LHSType 8716 << Left.getBitWidth() << LHS.get()->getSourceRange() 8717 << RHS.get()->getSourceRange(); 8718 } 8719 8720 /// \brief Return the resulting type when a vector is shifted 8721 /// by a scalar or vector shift amount. 8722 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8723 SourceLocation Loc, bool IsCompAssign) { 8724 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8725 if (!LHS.get()->getType()->isVectorType()) { 8726 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8727 << RHS.get()->getType() << LHS.get()->getType() 8728 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8729 return QualType(); 8730 } 8731 8732 if (!IsCompAssign) { 8733 LHS = S.UsualUnaryConversions(LHS.get()); 8734 if (LHS.isInvalid()) return QualType(); 8735 } 8736 8737 RHS = S.UsualUnaryConversions(RHS.get()); 8738 if (RHS.isInvalid()) return QualType(); 8739 8740 QualType LHSType = LHS.get()->getType(); 8741 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8742 QualType LHSEleType = LHSVecTy->getElementType(); 8743 8744 // Note that RHS might not be a vector. 8745 QualType RHSType = RHS.get()->getType(); 8746 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8747 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8748 8749 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8750 if (!LHSEleType->isIntegerType()) { 8751 S.Diag(Loc, diag::err_typecheck_expect_int) 8752 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8753 return QualType(); 8754 } 8755 8756 if (!RHSEleType->isIntegerType()) { 8757 S.Diag(Loc, diag::err_typecheck_expect_int) 8758 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8759 return QualType(); 8760 } 8761 8762 if (RHSVecTy) { 8763 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8764 // are applied component-wise. So if RHS is a vector, then ensure 8765 // that the number of elements is the same as LHS... 8766 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8767 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8768 << LHS.get()->getType() << RHS.get()->getType() 8769 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8770 return QualType(); 8771 } 8772 } else { 8773 // ...else expand RHS to match the number of elements in LHS. 8774 QualType VecTy = 8775 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8776 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8777 } 8778 8779 return LHSType; 8780 } 8781 8782 // C99 6.5.7 8783 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8784 SourceLocation Loc, BinaryOperatorKind Opc, 8785 bool IsCompAssign) { 8786 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8787 8788 // Vector shifts promote their scalar inputs to vector type. 8789 if (LHS.get()->getType()->isVectorType() || 8790 RHS.get()->getType()->isVectorType()) { 8791 if (LangOpts.ZVector) { 8792 // The shift operators for the z vector extensions work basically 8793 // like general shifts, except that neither the LHS nor the RHS is 8794 // allowed to be a "vector bool". 8795 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8796 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8797 return InvalidOperands(Loc, LHS, RHS); 8798 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8799 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8800 return InvalidOperands(Loc, LHS, RHS); 8801 } 8802 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8803 } 8804 8805 // Shifts don't perform usual arithmetic conversions, they just do integer 8806 // promotions on each operand. C99 6.5.7p3 8807 8808 // For the LHS, do usual unary conversions, but then reset them away 8809 // if this is a compound assignment. 8810 ExprResult OldLHS = LHS; 8811 LHS = UsualUnaryConversions(LHS.get()); 8812 if (LHS.isInvalid()) 8813 return QualType(); 8814 QualType LHSType = LHS.get()->getType(); 8815 if (IsCompAssign) LHS = OldLHS; 8816 8817 // The RHS is simpler. 8818 RHS = UsualUnaryConversions(RHS.get()); 8819 if (RHS.isInvalid()) 8820 return QualType(); 8821 QualType RHSType = RHS.get()->getType(); 8822 8823 // C99 6.5.7p2: Each of the operands shall have integer type. 8824 if (!LHSType->hasIntegerRepresentation() || 8825 !RHSType->hasIntegerRepresentation()) 8826 return InvalidOperands(Loc, LHS, RHS); 8827 8828 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8829 // hasIntegerRepresentation() above instead of this. 8830 if (isScopedEnumerationType(LHSType) || 8831 isScopedEnumerationType(RHSType)) { 8832 return InvalidOperands(Loc, LHS, RHS); 8833 } 8834 // Sanity-check shift operands 8835 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8836 8837 // "The type of the result is that of the promoted left operand." 8838 return LHSType; 8839 } 8840 8841 static bool IsWithinTemplateSpecialization(Decl *D) { 8842 if (DeclContext *DC = D->getDeclContext()) { 8843 if (isa<ClassTemplateSpecializationDecl>(DC)) 8844 return true; 8845 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8846 return FD->isFunctionTemplateSpecialization(); 8847 } 8848 return false; 8849 } 8850 8851 /// If two different enums are compared, raise a warning. 8852 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8853 Expr *RHS) { 8854 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8855 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8856 8857 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8858 if (!LHSEnumType) 8859 return; 8860 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8861 if (!RHSEnumType) 8862 return; 8863 8864 // Ignore anonymous enums. 8865 if (!LHSEnumType->getDecl()->getIdentifier()) 8866 return; 8867 if (!RHSEnumType->getDecl()->getIdentifier()) 8868 return; 8869 8870 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8871 return; 8872 8873 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8874 << LHSStrippedType << RHSStrippedType 8875 << LHS->getSourceRange() << RHS->getSourceRange(); 8876 } 8877 8878 /// \brief Diagnose bad pointer comparisons. 8879 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8880 ExprResult &LHS, ExprResult &RHS, 8881 bool IsError) { 8882 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8883 : diag::ext_typecheck_comparison_of_distinct_pointers) 8884 << LHS.get()->getType() << RHS.get()->getType() 8885 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8886 } 8887 8888 /// \brief Returns false if the pointers are converted to a composite type, 8889 /// true otherwise. 8890 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8891 ExprResult &LHS, ExprResult &RHS) { 8892 // C++ [expr.rel]p2: 8893 // [...] Pointer conversions (4.10) and qualification 8894 // conversions (4.4) are performed on pointer operands (or on 8895 // a pointer operand and a null pointer constant) to bring 8896 // them to their composite pointer type. [...] 8897 // 8898 // C++ [expr.eq]p1 uses the same notion for (in)equality 8899 // comparisons of pointers. 8900 8901 // C++ [expr.eq]p2: 8902 // In addition, pointers to members can be compared, or a pointer to 8903 // member and a null pointer constant. Pointer to member conversions 8904 // (4.11) and qualification conversions (4.4) are performed to bring 8905 // them to a common type. If one operand is a null pointer constant, 8906 // the common type is the type of the other operand. Otherwise, the 8907 // common type is a pointer to member type similar (4.4) to the type 8908 // of one of the operands, with a cv-qualification signature (4.4) 8909 // that is the union of the cv-qualification signatures of the operand 8910 // types. 8911 8912 QualType LHSType = LHS.get()->getType(); 8913 QualType RHSType = RHS.get()->getType(); 8914 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8915 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8916 8917 bool NonStandardCompositeType = false; 8918 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8919 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8920 if (T.isNull()) { 8921 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8922 return true; 8923 } 8924 8925 if (NonStandardCompositeType) 8926 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8927 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8928 << RHS.get()->getSourceRange(); 8929 8930 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8931 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8932 return false; 8933 } 8934 8935 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8936 ExprResult &LHS, 8937 ExprResult &RHS, 8938 bool IsError) { 8939 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8940 : diag::ext_typecheck_comparison_of_fptr_to_void) 8941 << LHS.get()->getType() << RHS.get()->getType() 8942 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8943 } 8944 8945 static bool isObjCObjectLiteral(ExprResult &E) { 8946 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8947 case Stmt::ObjCArrayLiteralClass: 8948 case Stmt::ObjCDictionaryLiteralClass: 8949 case Stmt::ObjCStringLiteralClass: 8950 case Stmt::ObjCBoxedExprClass: 8951 return true; 8952 default: 8953 // Note that ObjCBoolLiteral is NOT an object literal! 8954 return false; 8955 } 8956 } 8957 8958 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8959 const ObjCObjectPointerType *Type = 8960 LHS->getType()->getAs<ObjCObjectPointerType>(); 8961 8962 // If this is not actually an Objective-C object, bail out. 8963 if (!Type) 8964 return false; 8965 8966 // Get the LHS object's interface type. 8967 QualType InterfaceType = Type->getPointeeType(); 8968 8969 // If the RHS isn't an Objective-C object, bail out. 8970 if (!RHS->getType()->isObjCObjectPointerType()) 8971 return false; 8972 8973 // Try to find the -isEqual: method. 8974 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8975 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8976 InterfaceType, 8977 /*instance=*/true); 8978 if (!Method) { 8979 if (Type->isObjCIdType()) { 8980 // For 'id', just check the global pool. 8981 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8982 /*receiverId=*/true); 8983 } else { 8984 // Check protocols. 8985 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8986 /*instance=*/true); 8987 } 8988 } 8989 8990 if (!Method) 8991 return false; 8992 8993 QualType T = Method->parameters()[0]->getType(); 8994 if (!T->isObjCObjectPointerType()) 8995 return false; 8996 8997 QualType R = Method->getReturnType(); 8998 if (!R->isScalarType()) 8999 return false; 9000 9001 return true; 9002 } 9003 9004 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9005 FromE = FromE->IgnoreParenImpCasts(); 9006 switch (FromE->getStmtClass()) { 9007 default: 9008 break; 9009 case Stmt::ObjCStringLiteralClass: 9010 // "string literal" 9011 return LK_String; 9012 case Stmt::ObjCArrayLiteralClass: 9013 // "array literal" 9014 return LK_Array; 9015 case Stmt::ObjCDictionaryLiteralClass: 9016 // "dictionary literal" 9017 return LK_Dictionary; 9018 case Stmt::BlockExprClass: 9019 return LK_Block; 9020 case Stmt::ObjCBoxedExprClass: { 9021 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9022 switch (Inner->getStmtClass()) { 9023 case Stmt::IntegerLiteralClass: 9024 case Stmt::FloatingLiteralClass: 9025 case Stmt::CharacterLiteralClass: 9026 case Stmt::ObjCBoolLiteralExprClass: 9027 case Stmt::CXXBoolLiteralExprClass: 9028 // "numeric literal" 9029 return LK_Numeric; 9030 case Stmt::ImplicitCastExprClass: { 9031 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9032 // Boolean literals can be represented by implicit casts. 9033 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9034 return LK_Numeric; 9035 break; 9036 } 9037 default: 9038 break; 9039 } 9040 return LK_Boxed; 9041 } 9042 } 9043 return LK_None; 9044 } 9045 9046 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9047 ExprResult &LHS, ExprResult &RHS, 9048 BinaryOperator::Opcode Opc){ 9049 Expr *Literal; 9050 Expr *Other; 9051 if (isObjCObjectLiteral(LHS)) { 9052 Literal = LHS.get(); 9053 Other = RHS.get(); 9054 } else { 9055 Literal = RHS.get(); 9056 Other = LHS.get(); 9057 } 9058 9059 // Don't warn on comparisons against nil. 9060 Other = Other->IgnoreParenCasts(); 9061 if (Other->isNullPointerConstant(S.getASTContext(), 9062 Expr::NPC_ValueDependentIsNotNull)) 9063 return; 9064 9065 // This should be kept in sync with warn_objc_literal_comparison. 9066 // LK_String should always be after the other literals, since it has its own 9067 // warning flag. 9068 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9069 assert(LiteralKind != Sema::LK_Block); 9070 if (LiteralKind == Sema::LK_None) { 9071 llvm_unreachable("Unknown Objective-C object literal kind"); 9072 } 9073 9074 if (LiteralKind == Sema::LK_String) 9075 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9076 << Literal->getSourceRange(); 9077 else 9078 S.Diag(Loc, diag::warn_objc_literal_comparison) 9079 << LiteralKind << Literal->getSourceRange(); 9080 9081 if (BinaryOperator::isEqualityOp(Opc) && 9082 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9083 SourceLocation Start = LHS.get()->getLocStart(); 9084 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9085 CharSourceRange OpRange = 9086 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9087 9088 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9089 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9090 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9091 << FixItHint::CreateInsertion(End, "]"); 9092 } 9093 } 9094 9095 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9096 ExprResult &RHS, 9097 SourceLocation Loc, 9098 BinaryOperatorKind Opc) { 9099 // Check that left hand side is !something. 9100 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9101 if (!UO || UO->getOpcode() != UO_LNot) return; 9102 9103 // Only check if the right hand side is non-bool arithmetic type. 9104 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9105 9106 // Make sure that the something in !something is not bool. 9107 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9108 if (SubExpr->isKnownToHaveBooleanValue()) return; 9109 9110 // Emit warning. 9111 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9112 << Loc; 9113 9114 // First note suggest !(x < y) 9115 SourceLocation FirstOpen = SubExpr->getLocStart(); 9116 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9117 FirstClose = S.getLocForEndOfToken(FirstClose); 9118 if (FirstClose.isInvalid()) 9119 FirstOpen = SourceLocation(); 9120 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9121 << FixItHint::CreateInsertion(FirstOpen, "(") 9122 << FixItHint::CreateInsertion(FirstClose, ")"); 9123 9124 // Second note suggests (!x) < y 9125 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9126 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9127 SecondClose = S.getLocForEndOfToken(SecondClose); 9128 if (SecondClose.isInvalid()) 9129 SecondOpen = SourceLocation(); 9130 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9131 << FixItHint::CreateInsertion(SecondOpen, "(") 9132 << FixItHint::CreateInsertion(SecondClose, ")"); 9133 } 9134 9135 // Get the decl for a simple expression: a reference to a variable, 9136 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9137 static ValueDecl *getCompareDecl(Expr *E) { 9138 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9139 return DR->getDecl(); 9140 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9141 if (Ivar->isFreeIvar()) 9142 return Ivar->getDecl(); 9143 } 9144 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9145 if (Mem->isImplicitAccess()) 9146 return Mem->getMemberDecl(); 9147 } 9148 return nullptr; 9149 } 9150 9151 // C99 6.5.8, C++ [expr.rel] 9152 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9153 SourceLocation Loc, BinaryOperatorKind Opc, 9154 bool IsRelational) { 9155 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9156 9157 // Handle vector comparisons separately. 9158 if (LHS.get()->getType()->isVectorType() || 9159 RHS.get()->getType()->isVectorType()) 9160 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9161 9162 QualType LHSType = LHS.get()->getType(); 9163 QualType RHSType = RHS.get()->getType(); 9164 9165 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9166 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9167 9168 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9169 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9170 9171 if (!LHSType->hasFloatingRepresentation() && 9172 !(LHSType->isBlockPointerType() && IsRelational) && 9173 !LHS.get()->getLocStart().isMacroID() && 9174 !RHS.get()->getLocStart().isMacroID() && 9175 ActiveTemplateInstantiations.empty()) { 9176 // For non-floating point types, check for self-comparisons of the form 9177 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9178 // often indicate logic errors in the program. 9179 // 9180 // NOTE: Don't warn about comparison expressions resulting from macro 9181 // expansion. Also don't warn about comparisons which are only self 9182 // comparisons within a template specialization. The warnings should catch 9183 // obvious cases in the definition of the template anyways. The idea is to 9184 // warn when the typed comparison operator will always evaluate to the same 9185 // result. 9186 ValueDecl *DL = getCompareDecl(LHSStripped); 9187 ValueDecl *DR = getCompareDecl(RHSStripped); 9188 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9189 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9190 << 0 // self- 9191 << (Opc == BO_EQ 9192 || Opc == BO_LE 9193 || Opc == BO_GE)); 9194 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9195 !DL->getType()->isReferenceType() && 9196 !DR->getType()->isReferenceType()) { 9197 // what is it always going to eval to? 9198 char always_evals_to; 9199 switch(Opc) { 9200 case BO_EQ: // e.g. array1 == array2 9201 always_evals_to = 0; // false 9202 break; 9203 case BO_NE: // e.g. array1 != array2 9204 always_evals_to = 1; // true 9205 break; 9206 default: 9207 // best we can say is 'a constant' 9208 always_evals_to = 2; // e.g. array1 <= array2 9209 break; 9210 } 9211 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9212 << 1 // array 9213 << always_evals_to); 9214 } 9215 9216 if (isa<CastExpr>(LHSStripped)) 9217 LHSStripped = LHSStripped->IgnoreParenCasts(); 9218 if (isa<CastExpr>(RHSStripped)) 9219 RHSStripped = RHSStripped->IgnoreParenCasts(); 9220 9221 // Warn about comparisons against a string constant (unless the other 9222 // operand is null), the user probably wants strcmp. 9223 Expr *literalString = nullptr; 9224 Expr *literalStringStripped = nullptr; 9225 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9226 !RHSStripped->isNullPointerConstant(Context, 9227 Expr::NPC_ValueDependentIsNull)) { 9228 literalString = LHS.get(); 9229 literalStringStripped = LHSStripped; 9230 } else if ((isa<StringLiteral>(RHSStripped) || 9231 isa<ObjCEncodeExpr>(RHSStripped)) && 9232 !LHSStripped->isNullPointerConstant(Context, 9233 Expr::NPC_ValueDependentIsNull)) { 9234 literalString = RHS.get(); 9235 literalStringStripped = RHSStripped; 9236 } 9237 9238 if (literalString) { 9239 DiagRuntimeBehavior(Loc, nullptr, 9240 PDiag(diag::warn_stringcompare) 9241 << isa<ObjCEncodeExpr>(literalStringStripped) 9242 << literalString->getSourceRange()); 9243 } 9244 } 9245 9246 // C99 6.5.8p3 / C99 6.5.9p4 9247 UsualArithmeticConversions(LHS, RHS); 9248 if (LHS.isInvalid() || RHS.isInvalid()) 9249 return QualType(); 9250 9251 LHSType = LHS.get()->getType(); 9252 RHSType = RHS.get()->getType(); 9253 9254 // The result of comparisons is 'bool' in C++, 'int' in C. 9255 QualType ResultTy = Context.getLogicalOperationType(); 9256 9257 if (IsRelational) { 9258 if (LHSType->isRealType() && RHSType->isRealType()) 9259 return ResultTy; 9260 } else { 9261 // Check for comparisons of floating point operands using != and ==. 9262 if (LHSType->hasFloatingRepresentation()) 9263 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9264 9265 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9266 return ResultTy; 9267 } 9268 9269 const Expr::NullPointerConstantKind LHSNullKind = 9270 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9271 const Expr::NullPointerConstantKind RHSNullKind = 9272 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9273 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9274 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9275 9276 if (!IsRelational && LHSIsNull != RHSIsNull) { 9277 bool IsEquality = Opc == BO_EQ; 9278 if (RHSIsNull) 9279 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9280 RHS.get()->getSourceRange()); 9281 else 9282 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9283 LHS.get()->getSourceRange()); 9284 } 9285 9286 // All of the following pointer-related warnings are GCC extensions, except 9287 // when handling null pointer constants. 9288 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9289 QualType LCanPointeeTy = 9290 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9291 QualType RCanPointeeTy = 9292 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9293 9294 if (getLangOpts().CPlusPlus) { 9295 if (LCanPointeeTy == RCanPointeeTy) 9296 return ResultTy; 9297 if (!IsRelational && 9298 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9299 // Valid unless comparison between non-null pointer and function pointer 9300 // This is a gcc extension compatibility comparison. 9301 // In a SFINAE context, we treat this as a hard error to maintain 9302 // conformance with the C++ standard. 9303 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9304 && !LHSIsNull && !RHSIsNull) { 9305 diagnoseFunctionPointerToVoidComparison( 9306 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9307 9308 if (isSFINAEContext()) 9309 return QualType(); 9310 9311 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9312 return ResultTy; 9313 } 9314 } 9315 9316 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9317 return QualType(); 9318 else 9319 return ResultTy; 9320 } 9321 // C99 6.5.9p2 and C99 6.5.8p2 9322 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9323 RCanPointeeTy.getUnqualifiedType())) { 9324 // Valid unless a relational comparison of function pointers 9325 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9326 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9327 << LHSType << RHSType << LHS.get()->getSourceRange() 9328 << RHS.get()->getSourceRange(); 9329 } 9330 } else if (!IsRelational && 9331 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9332 // Valid unless comparison between non-null pointer and function pointer 9333 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9334 && !LHSIsNull && !RHSIsNull) 9335 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9336 /*isError*/false); 9337 } else { 9338 // Invalid 9339 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9340 } 9341 if (LCanPointeeTy != RCanPointeeTy) { 9342 // Treat NULL constant as a special case in OpenCL. 9343 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9344 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9345 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9346 Diag(Loc, 9347 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9348 << LHSType << RHSType << 0 /* comparison */ 9349 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9350 } 9351 } 9352 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9353 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9354 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9355 : CK_BitCast; 9356 if (LHSIsNull && !RHSIsNull) 9357 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9358 else 9359 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9360 } 9361 return ResultTy; 9362 } 9363 9364 if (getLangOpts().CPlusPlus) { 9365 // Comparison of nullptr_t with itself. 9366 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9367 return ResultTy; 9368 9369 // Comparison of pointers with null pointer constants and equality 9370 // comparisons of member pointers to null pointer constants. 9371 if (RHSIsNull && 9372 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9373 (!IsRelational && 9374 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9375 RHS = ImpCastExprToType(RHS.get(), LHSType, 9376 LHSType->isMemberPointerType() 9377 ? CK_NullToMemberPointer 9378 : CK_NullToPointer); 9379 return ResultTy; 9380 } 9381 if (LHSIsNull && 9382 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9383 (!IsRelational && 9384 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9385 LHS = ImpCastExprToType(LHS.get(), RHSType, 9386 RHSType->isMemberPointerType() 9387 ? CK_NullToMemberPointer 9388 : CK_NullToPointer); 9389 return ResultTy; 9390 } 9391 9392 // Comparison of member pointers. 9393 if (!IsRelational && 9394 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9395 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9396 return QualType(); 9397 else 9398 return ResultTy; 9399 } 9400 9401 // Handle scoped enumeration types specifically, since they don't promote 9402 // to integers. 9403 if (LHS.get()->getType()->isEnumeralType() && 9404 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9405 RHS.get()->getType())) 9406 return ResultTy; 9407 } 9408 9409 // Handle block pointer types. 9410 if (!IsRelational && LHSType->isBlockPointerType() && 9411 RHSType->isBlockPointerType()) { 9412 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9413 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9414 9415 if (!LHSIsNull && !RHSIsNull && 9416 !Context.typesAreCompatible(lpointee, rpointee)) { 9417 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9418 << LHSType << RHSType << LHS.get()->getSourceRange() 9419 << RHS.get()->getSourceRange(); 9420 } 9421 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9422 return ResultTy; 9423 } 9424 9425 // Allow block pointers to be compared with null pointer constants. 9426 if (!IsRelational 9427 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9428 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9429 if (!LHSIsNull && !RHSIsNull) { 9430 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9431 ->getPointeeType()->isVoidType()) 9432 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9433 ->getPointeeType()->isVoidType()))) 9434 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9435 << LHSType << RHSType << LHS.get()->getSourceRange() 9436 << RHS.get()->getSourceRange(); 9437 } 9438 if (LHSIsNull && !RHSIsNull) 9439 LHS = ImpCastExprToType(LHS.get(), RHSType, 9440 RHSType->isPointerType() ? CK_BitCast 9441 : CK_AnyPointerToBlockPointerCast); 9442 else 9443 RHS = ImpCastExprToType(RHS.get(), LHSType, 9444 LHSType->isPointerType() ? CK_BitCast 9445 : CK_AnyPointerToBlockPointerCast); 9446 return ResultTy; 9447 } 9448 9449 if (LHSType->isObjCObjectPointerType() || 9450 RHSType->isObjCObjectPointerType()) { 9451 const PointerType *LPT = LHSType->getAs<PointerType>(); 9452 const PointerType *RPT = RHSType->getAs<PointerType>(); 9453 if (LPT || RPT) { 9454 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9455 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9456 9457 if (!LPtrToVoid && !RPtrToVoid && 9458 !Context.typesAreCompatible(LHSType, RHSType)) { 9459 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9460 /*isError*/false); 9461 } 9462 if (LHSIsNull && !RHSIsNull) { 9463 Expr *E = LHS.get(); 9464 if (getLangOpts().ObjCAutoRefCount) 9465 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9466 LHS = ImpCastExprToType(E, RHSType, 9467 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9468 } 9469 else { 9470 Expr *E = RHS.get(); 9471 if (getLangOpts().ObjCAutoRefCount) 9472 CheckObjCARCConversion(SourceRange(), LHSType, E, 9473 CCK_ImplicitConversion, /*Diagnose=*/true, 9474 /*DiagnoseCFAudited=*/false, Opc); 9475 RHS = ImpCastExprToType(E, LHSType, 9476 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9477 } 9478 return ResultTy; 9479 } 9480 if (LHSType->isObjCObjectPointerType() && 9481 RHSType->isObjCObjectPointerType()) { 9482 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9483 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9484 /*isError*/false); 9485 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9486 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9487 9488 if (LHSIsNull && !RHSIsNull) 9489 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9490 else 9491 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9492 return ResultTy; 9493 } 9494 } 9495 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9496 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9497 unsigned DiagID = 0; 9498 bool isError = false; 9499 if (LangOpts.DebuggerSupport) { 9500 // Under a debugger, allow the comparison of pointers to integers, 9501 // since users tend to want to compare addresses. 9502 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9503 (RHSIsNull && RHSType->isIntegerType())) { 9504 if (IsRelational && !getLangOpts().CPlusPlus) 9505 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9506 } else if (IsRelational && !getLangOpts().CPlusPlus) 9507 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9508 else if (getLangOpts().CPlusPlus) { 9509 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9510 isError = true; 9511 } else 9512 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9513 9514 if (DiagID) { 9515 Diag(Loc, DiagID) 9516 << LHSType << RHSType << LHS.get()->getSourceRange() 9517 << RHS.get()->getSourceRange(); 9518 if (isError) 9519 return QualType(); 9520 } 9521 9522 if (LHSType->isIntegerType()) 9523 LHS = ImpCastExprToType(LHS.get(), RHSType, 9524 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9525 else 9526 RHS = ImpCastExprToType(RHS.get(), LHSType, 9527 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9528 return ResultTy; 9529 } 9530 9531 // Handle block pointers. 9532 if (!IsRelational && RHSIsNull 9533 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9534 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9535 return ResultTy; 9536 } 9537 if (!IsRelational && LHSIsNull 9538 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9539 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9540 return ResultTy; 9541 } 9542 9543 return InvalidOperands(Loc, LHS, RHS); 9544 } 9545 9546 9547 // Return a signed type that is of identical size and number of elements. 9548 // For floating point vectors, return an integer type of identical size 9549 // and number of elements. 9550 QualType Sema::GetSignedVectorType(QualType V) { 9551 const VectorType *VTy = V->getAs<VectorType>(); 9552 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9553 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9554 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9555 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9556 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9557 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9558 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9559 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9560 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9561 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9562 "Unhandled vector element size in vector compare"); 9563 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9564 } 9565 9566 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9567 /// operates on extended vector types. Instead of producing an IntTy result, 9568 /// like a scalar comparison, a vector comparison produces a vector of integer 9569 /// types. 9570 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9571 SourceLocation Loc, 9572 bool IsRelational) { 9573 // Check to make sure we're operating on vectors of the same type and width, 9574 // Allowing one side to be a scalar of element type. 9575 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9576 /*AllowBothBool*/true, 9577 /*AllowBoolConversions*/getLangOpts().ZVector); 9578 if (vType.isNull()) 9579 return vType; 9580 9581 QualType LHSType = LHS.get()->getType(); 9582 9583 // If AltiVec, the comparison results in a numeric type, i.e. 9584 // bool for C++, int for C 9585 if (getLangOpts().AltiVec && 9586 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9587 return Context.getLogicalOperationType(); 9588 9589 // For non-floating point types, check for self-comparisons of the form 9590 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9591 // often indicate logic errors in the program. 9592 if (!LHSType->hasFloatingRepresentation() && 9593 ActiveTemplateInstantiations.empty()) { 9594 if (DeclRefExpr* DRL 9595 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9596 if (DeclRefExpr* DRR 9597 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9598 if (DRL->getDecl() == DRR->getDecl()) 9599 DiagRuntimeBehavior(Loc, nullptr, 9600 PDiag(diag::warn_comparison_always) 9601 << 0 // self- 9602 << 2 // "a constant" 9603 ); 9604 } 9605 9606 // Check for comparisons of floating point operands using != and ==. 9607 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9608 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9609 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9610 } 9611 9612 // Return a signed type for the vector. 9613 return GetSignedVectorType(vType); 9614 } 9615 9616 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9617 SourceLocation Loc) { 9618 // Ensure that either both operands are of the same vector type, or 9619 // one operand is of a vector type and the other is of its element type. 9620 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9621 /*AllowBothBool*/true, 9622 /*AllowBoolConversions*/false); 9623 if (vType.isNull()) 9624 return InvalidOperands(Loc, LHS, RHS); 9625 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9626 vType->hasFloatingRepresentation()) 9627 return InvalidOperands(Loc, LHS, RHS); 9628 9629 return GetSignedVectorType(LHS.get()->getType()); 9630 } 9631 9632 inline QualType Sema::CheckBitwiseOperands( 9633 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9634 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9635 9636 if (LHS.get()->getType()->isVectorType() || 9637 RHS.get()->getType()->isVectorType()) { 9638 if (LHS.get()->getType()->hasIntegerRepresentation() && 9639 RHS.get()->getType()->hasIntegerRepresentation()) 9640 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9641 /*AllowBothBool*/true, 9642 /*AllowBoolConversions*/getLangOpts().ZVector); 9643 return InvalidOperands(Loc, LHS, RHS); 9644 } 9645 9646 ExprResult LHSResult = LHS, RHSResult = RHS; 9647 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9648 IsCompAssign); 9649 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9650 return QualType(); 9651 LHS = LHSResult.get(); 9652 RHS = RHSResult.get(); 9653 9654 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9655 return compType; 9656 return InvalidOperands(Loc, LHS, RHS); 9657 } 9658 9659 // C99 6.5.[13,14] 9660 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9661 SourceLocation Loc, 9662 BinaryOperatorKind Opc) { 9663 // Check vector operands differently. 9664 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9665 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9666 9667 // Diagnose cases where the user write a logical and/or but probably meant a 9668 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9669 // is a constant. 9670 if (LHS.get()->getType()->isIntegerType() && 9671 !LHS.get()->getType()->isBooleanType() && 9672 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9673 // Don't warn in macros or template instantiations. 9674 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9675 // If the RHS can be constant folded, and if it constant folds to something 9676 // that isn't 0 or 1 (which indicate a potential logical operation that 9677 // happened to fold to true/false) then warn. 9678 // Parens on the RHS are ignored. 9679 llvm::APSInt Result; 9680 if (RHS.get()->EvaluateAsInt(Result, Context)) 9681 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9682 !RHS.get()->getExprLoc().isMacroID()) || 9683 (Result != 0 && Result != 1)) { 9684 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9685 << RHS.get()->getSourceRange() 9686 << (Opc == BO_LAnd ? "&&" : "||"); 9687 // Suggest replacing the logical operator with the bitwise version 9688 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9689 << (Opc == BO_LAnd ? "&" : "|") 9690 << FixItHint::CreateReplacement(SourceRange( 9691 Loc, getLocForEndOfToken(Loc)), 9692 Opc == BO_LAnd ? "&" : "|"); 9693 if (Opc == BO_LAnd) 9694 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9695 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9696 << FixItHint::CreateRemoval( 9697 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9698 RHS.get()->getLocEnd())); 9699 } 9700 } 9701 9702 if (!Context.getLangOpts().CPlusPlus) { 9703 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9704 // not operate on the built-in scalar and vector float types. 9705 if (Context.getLangOpts().OpenCL && 9706 Context.getLangOpts().OpenCLVersion < 120) { 9707 if (LHS.get()->getType()->isFloatingType() || 9708 RHS.get()->getType()->isFloatingType()) 9709 return InvalidOperands(Loc, LHS, RHS); 9710 } 9711 9712 LHS = UsualUnaryConversions(LHS.get()); 9713 if (LHS.isInvalid()) 9714 return QualType(); 9715 9716 RHS = UsualUnaryConversions(RHS.get()); 9717 if (RHS.isInvalid()) 9718 return QualType(); 9719 9720 if (!LHS.get()->getType()->isScalarType() || 9721 !RHS.get()->getType()->isScalarType()) 9722 return InvalidOperands(Loc, LHS, RHS); 9723 9724 return Context.IntTy; 9725 } 9726 9727 // The following is safe because we only use this method for 9728 // non-overloadable operands. 9729 9730 // C++ [expr.log.and]p1 9731 // C++ [expr.log.or]p1 9732 // The operands are both contextually converted to type bool. 9733 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9734 if (LHSRes.isInvalid()) 9735 return InvalidOperands(Loc, LHS, RHS); 9736 LHS = LHSRes; 9737 9738 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9739 if (RHSRes.isInvalid()) 9740 return InvalidOperands(Loc, LHS, RHS); 9741 RHS = RHSRes; 9742 9743 // C++ [expr.log.and]p2 9744 // C++ [expr.log.or]p2 9745 // The result is a bool. 9746 return Context.BoolTy; 9747 } 9748 9749 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9750 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9751 if (!ME) return false; 9752 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9753 ObjCMessageExpr *Base = 9754 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9755 if (!Base) return false; 9756 return Base->getMethodDecl() != nullptr; 9757 } 9758 9759 /// Is the given expression (which must be 'const') a reference to a 9760 /// variable which was originally non-const, but which has become 9761 /// 'const' due to being captured within a block? 9762 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9763 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9764 assert(E->isLValue() && E->getType().isConstQualified()); 9765 E = E->IgnoreParens(); 9766 9767 // Must be a reference to a declaration from an enclosing scope. 9768 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9769 if (!DRE) return NCCK_None; 9770 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9771 9772 // The declaration must be a variable which is not declared 'const'. 9773 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9774 if (!var) return NCCK_None; 9775 if (var->getType().isConstQualified()) return NCCK_None; 9776 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9777 9778 // Decide whether the first capture was for a block or a lambda. 9779 DeclContext *DC = S.CurContext, *Prev = nullptr; 9780 // Decide whether the first capture was for a block or a lambda. 9781 while (DC) { 9782 // For init-capture, it is possible that the variable belongs to the 9783 // template pattern of the current context. 9784 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9785 if (var->isInitCapture() && 9786 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9787 break; 9788 if (DC == var->getDeclContext()) 9789 break; 9790 Prev = DC; 9791 DC = DC->getParent(); 9792 } 9793 // Unless we have an init-capture, we've gone one step too far. 9794 if (!var->isInitCapture()) 9795 DC = Prev; 9796 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9797 } 9798 9799 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9800 Ty = Ty.getNonReferenceType(); 9801 if (IsDereference && Ty->isPointerType()) 9802 Ty = Ty->getPointeeType(); 9803 return !Ty.isConstQualified(); 9804 } 9805 9806 /// Emit the "read-only variable not assignable" error and print notes to give 9807 /// more information about why the variable is not assignable, such as pointing 9808 /// to the declaration of a const variable, showing that a method is const, or 9809 /// that the function is returning a const reference. 9810 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9811 SourceLocation Loc) { 9812 // Update err_typecheck_assign_const and note_typecheck_assign_const 9813 // when this enum is changed. 9814 enum { 9815 ConstFunction, 9816 ConstVariable, 9817 ConstMember, 9818 ConstMethod, 9819 ConstUnknown, // Keep as last element 9820 }; 9821 9822 SourceRange ExprRange = E->getSourceRange(); 9823 9824 // Only emit one error on the first const found. All other consts will emit 9825 // a note to the error. 9826 bool DiagnosticEmitted = false; 9827 9828 // Track if the current expression is the result of a derefence, and if the 9829 // next checked expression is the result of a derefence. 9830 bool IsDereference = false; 9831 bool NextIsDereference = false; 9832 9833 // Loop to process MemberExpr chains. 9834 while (true) { 9835 IsDereference = NextIsDereference; 9836 NextIsDereference = false; 9837 9838 E = E->IgnoreParenImpCasts(); 9839 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9840 NextIsDereference = ME->isArrow(); 9841 const ValueDecl *VD = ME->getMemberDecl(); 9842 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9843 // Mutable fields can be modified even if the class is const. 9844 if (Field->isMutable()) { 9845 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9846 break; 9847 } 9848 9849 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9850 if (!DiagnosticEmitted) { 9851 S.Diag(Loc, diag::err_typecheck_assign_const) 9852 << ExprRange << ConstMember << false /*static*/ << Field 9853 << Field->getType(); 9854 DiagnosticEmitted = true; 9855 } 9856 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9857 << ConstMember << false /*static*/ << Field << Field->getType() 9858 << Field->getSourceRange(); 9859 } 9860 E = ME->getBase(); 9861 continue; 9862 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9863 if (VDecl->getType().isConstQualified()) { 9864 if (!DiagnosticEmitted) { 9865 S.Diag(Loc, diag::err_typecheck_assign_const) 9866 << ExprRange << ConstMember << true /*static*/ << VDecl 9867 << VDecl->getType(); 9868 DiagnosticEmitted = true; 9869 } 9870 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9871 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9872 << VDecl->getSourceRange(); 9873 } 9874 // Static fields do not inherit constness from parents. 9875 break; 9876 } 9877 break; 9878 } // End MemberExpr 9879 break; 9880 } 9881 9882 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9883 // Function calls 9884 const FunctionDecl *FD = CE->getDirectCallee(); 9885 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9886 if (!DiagnosticEmitted) { 9887 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9888 << ConstFunction << FD; 9889 DiagnosticEmitted = true; 9890 } 9891 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9892 diag::note_typecheck_assign_const) 9893 << ConstFunction << FD << FD->getReturnType() 9894 << FD->getReturnTypeSourceRange(); 9895 } 9896 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9897 // Point to variable declaration. 9898 if (const ValueDecl *VD = DRE->getDecl()) { 9899 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9900 if (!DiagnosticEmitted) { 9901 S.Diag(Loc, diag::err_typecheck_assign_const) 9902 << ExprRange << ConstVariable << VD << VD->getType(); 9903 DiagnosticEmitted = true; 9904 } 9905 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9906 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9907 } 9908 } 9909 } else if (isa<CXXThisExpr>(E)) { 9910 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9912 if (MD->isConst()) { 9913 if (!DiagnosticEmitted) { 9914 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9915 << ConstMethod << MD; 9916 DiagnosticEmitted = true; 9917 } 9918 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9919 << ConstMethod << MD << MD->getSourceRange(); 9920 } 9921 } 9922 } 9923 } 9924 9925 if (DiagnosticEmitted) 9926 return; 9927 9928 // Can't determine a more specific message, so display the generic error. 9929 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9930 } 9931 9932 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9933 /// emit an error and return true. If so, return false. 9934 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9935 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9936 9937 S.CheckShadowingDeclModification(E, Loc); 9938 9939 SourceLocation OrigLoc = Loc; 9940 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9941 &Loc); 9942 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9943 IsLV = Expr::MLV_InvalidMessageExpression; 9944 if (IsLV == Expr::MLV_Valid) 9945 return false; 9946 9947 unsigned DiagID = 0; 9948 bool NeedType = false; 9949 switch (IsLV) { // C99 6.5.16p2 9950 case Expr::MLV_ConstQualified: 9951 // Use a specialized diagnostic when we're assigning to an object 9952 // from an enclosing function or block. 9953 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9954 if (NCCK == NCCK_Block) 9955 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9956 else 9957 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9958 break; 9959 } 9960 9961 // In ARC, use some specialized diagnostics for occasions where we 9962 // infer 'const'. These are always pseudo-strong variables. 9963 if (S.getLangOpts().ObjCAutoRefCount) { 9964 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9965 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9966 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9967 9968 // Use the normal diagnostic if it's pseudo-__strong but the 9969 // user actually wrote 'const'. 9970 if (var->isARCPseudoStrong() && 9971 (!var->getTypeSourceInfo() || 9972 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9973 // There are two pseudo-strong cases: 9974 // - self 9975 ObjCMethodDecl *method = S.getCurMethodDecl(); 9976 if (method && var == method->getSelfDecl()) 9977 DiagID = method->isClassMethod() 9978 ? diag::err_typecheck_arc_assign_self_class_method 9979 : diag::err_typecheck_arc_assign_self; 9980 9981 // - fast enumeration variables 9982 else 9983 DiagID = diag::err_typecheck_arr_assign_enumeration; 9984 9985 SourceRange Assign; 9986 if (Loc != OrigLoc) 9987 Assign = SourceRange(OrigLoc, OrigLoc); 9988 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9989 // We need to preserve the AST regardless, so migration tool 9990 // can do its job. 9991 return false; 9992 } 9993 } 9994 } 9995 9996 // If none of the special cases above are triggered, then this is a 9997 // simple const assignment. 9998 if (DiagID == 0) { 9999 DiagnoseConstAssignment(S, E, Loc); 10000 return true; 10001 } 10002 10003 break; 10004 case Expr::MLV_ConstAddrSpace: 10005 DiagnoseConstAssignment(S, E, Loc); 10006 return true; 10007 case Expr::MLV_ArrayType: 10008 case Expr::MLV_ArrayTemporary: 10009 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10010 NeedType = true; 10011 break; 10012 case Expr::MLV_NotObjectType: 10013 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10014 NeedType = true; 10015 break; 10016 case Expr::MLV_LValueCast: 10017 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10018 break; 10019 case Expr::MLV_Valid: 10020 llvm_unreachable("did not take early return for MLV_Valid"); 10021 case Expr::MLV_InvalidExpression: 10022 case Expr::MLV_MemberFunction: 10023 case Expr::MLV_ClassTemporary: 10024 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10025 break; 10026 case Expr::MLV_IncompleteType: 10027 case Expr::MLV_IncompleteVoidType: 10028 return S.RequireCompleteType(Loc, E->getType(), 10029 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10030 case Expr::MLV_DuplicateVectorComponents: 10031 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10032 break; 10033 case Expr::MLV_NoSetterProperty: 10034 llvm_unreachable("readonly properties should be processed differently"); 10035 case Expr::MLV_InvalidMessageExpression: 10036 DiagID = diag::error_readonly_message_assignment; 10037 break; 10038 case Expr::MLV_SubObjCPropertySetting: 10039 DiagID = diag::error_no_subobject_property_setting; 10040 break; 10041 } 10042 10043 SourceRange Assign; 10044 if (Loc != OrigLoc) 10045 Assign = SourceRange(OrigLoc, OrigLoc); 10046 if (NeedType) 10047 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10048 else 10049 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10050 return true; 10051 } 10052 10053 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10054 SourceLocation Loc, 10055 Sema &Sema) { 10056 // C / C++ fields 10057 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10058 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10059 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10060 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10061 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10062 } 10063 10064 // Objective-C instance variables 10065 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10066 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10067 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10068 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10069 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10070 if (RL && RR && RL->getDecl() == RR->getDecl()) 10071 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10072 } 10073 } 10074 10075 // C99 6.5.16.1 10076 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10077 SourceLocation Loc, 10078 QualType CompoundType) { 10079 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10080 10081 // Verify that LHS is a modifiable lvalue, and emit error if not. 10082 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10083 return QualType(); 10084 10085 QualType LHSType = LHSExpr->getType(); 10086 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10087 CompoundType; 10088 AssignConvertType ConvTy; 10089 if (CompoundType.isNull()) { 10090 Expr *RHSCheck = RHS.get(); 10091 10092 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10093 10094 QualType LHSTy(LHSType); 10095 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10096 if (RHS.isInvalid()) 10097 return QualType(); 10098 // Special case of NSObject attributes on c-style pointer types. 10099 if (ConvTy == IncompatiblePointer && 10100 ((Context.isObjCNSObjectType(LHSType) && 10101 RHSType->isObjCObjectPointerType()) || 10102 (Context.isObjCNSObjectType(RHSType) && 10103 LHSType->isObjCObjectPointerType()))) 10104 ConvTy = Compatible; 10105 10106 if (ConvTy == Compatible && 10107 LHSType->isObjCObjectType()) 10108 Diag(Loc, diag::err_objc_object_assignment) 10109 << LHSType; 10110 10111 // If the RHS is a unary plus or minus, check to see if they = and + are 10112 // right next to each other. If so, the user may have typo'd "x =+ 4" 10113 // instead of "x += 4". 10114 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10115 RHSCheck = ICE->getSubExpr(); 10116 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10117 if ((UO->getOpcode() == UO_Plus || 10118 UO->getOpcode() == UO_Minus) && 10119 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10120 // Only if the two operators are exactly adjacent. 10121 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10122 // And there is a space or other character before the subexpr of the 10123 // unary +/-. We don't want to warn on "x=-1". 10124 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10125 UO->getSubExpr()->getLocStart().isFileID()) { 10126 Diag(Loc, diag::warn_not_compound_assign) 10127 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10128 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10129 } 10130 } 10131 10132 if (ConvTy == Compatible) { 10133 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10134 // Warn about retain cycles where a block captures the LHS, but 10135 // not if the LHS is a simple variable into which the block is 10136 // being stored...unless that variable can be captured by reference! 10137 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10138 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10139 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10140 checkRetainCycles(LHSExpr, RHS.get()); 10141 10142 // It is safe to assign a weak reference into a strong variable. 10143 // Although this code can still have problems: 10144 // id x = self.weakProp; 10145 // id y = self.weakProp; 10146 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10147 // paths through the function. This should be revisited if 10148 // -Wrepeated-use-of-weak is made flow-sensitive. 10149 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10150 RHS.get()->getLocStart())) 10151 getCurFunction()->markSafeWeakUse(RHS.get()); 10152 10153 } else if (getLangOpts().ObjCAutoRefCount) { 10154 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10155 } 10156 } 10157 } else { 10158 // Compound assignment "x += y" 10159 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10160 } 10161 10162 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10163 RHS.get(), AA_Assigning)) 10164 return QualType(); 10165 10166 CheckForNullPointerDereference(*this, LHSExpr); 10167 10168 // C99 6.5.16p3: The type of an assignment expression is the type of the 10169 // left operand unless the left operand has qualified type, in which case 10170 // it is the unqualified version of the type of the left operand. 10171 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10172 // is converted to the type of the assignment expression (above). 10173 // C++ 5.17p1: the type of the assignment expression is that of its left 10174 // operand. 10175 return (getLangOpts().CPlusPlus 10176 ? LHSType : LHSType.getUnqualifiedType()); 10177 } 10178 10179 // Only ignore explicit casts to void. 10180 static bool IgnoreCommaOperand(const Expr *E) { 10181 E = E->IgnoreParens(); 10182 10183 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10184 if (CE->getCastKind() == CK_ToVoid) { 10185 return true; 10186 } 10187 } 10188 10189 return false; 10190 } 10191 10192 // Look for instances where it is likely the comma operator is confused with 10193 // another operator. There is a whitelist of acceptable expressions for the 10194 // left hand side of the comma operator, otherwise emit a warning. 10195 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10196 // No warnings in macros 10197 if (Loc.isMacroID()) 10198 return; 10199 10200 // Don't warn in template instantiations. 10201 if (!ActiveTemplateInstantiations.empty()) 10202 return; 10203 10204 // Scope isn't fine-grained enough to whitelist the specific cases, so 10205 // instead, skip more than needed, then call back into here with the 10206 // CommaVisitor in SemaStmt.cpp. 10207 // The whitelisted locations are the initialization and increment portions 10208 // of a for loop. The additional checks are on the condition of 10209 // if statements, do/while loops, and for loops. 10210 const unsigned ForIncrementFlags = 10211 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10212 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10213 const unsigned ScopeFlags = getCurScope()->getFlags(); 10214 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10215 (ScopeFlags & ForInitFlags) == ForInitFlags) 10216 return; 10217 10218 // If there are multiple comma operators used together, get the RHS of the 10219 // of the comma operator as the LHS. 10220 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10221 if (BO->getOpcode() != BO_Comma) 10222 break; 10223 LHS = BO->getRHS(); 10224 } 10225 10226 // Only allow some expressions on LHS to not warn. 10227 if (IgnoreCommaOperand(LHS)) 10228 return; 10229 10230 Diag(Loc, diag::warn_comma_operator); 10231 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10232 << LHS->getSourceRange() 10233 << FixItHint::CreateInsertion(LHS->getLocStart(), 10234 LangOpts.CPlusPlus ? "static_cast<void>(" 10235 : "(void)(") 10236 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10237 ")"); 10238 } 10239 10240 // C99 6.5.17 10241 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10242 SourceLocation Loc) { 10243 LHS = S.CheckPlaceholderExpr(LHS.get()); 10244 RHS = S.CheckPlaceholderExpr(RHS.get()); 10245 if (LHS.isInvalid() || RHS.isInvalid()) 10246 return QualType(); 10247 10248 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10249 // operands, but not unary promotions. 10250 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10251 10252 // So we treat the LHS as a ignored value, and in C++ we allow the 10253 // containing site to determine what should be done with the RHS. 10254 LHS = S.IgnoredValueConversions(LHS.get()); 10255 if (LHS.isInvalid()) 10256 return QualType(); 10257 10258 S.DiagnoseUnusedExprResult(LHS.get()); 10259 10260 if (!S.getLangOpts().CPlusPlus) { 10261 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10262 if (RHS.isInvalid()) 10263 return QualType(); 10264 if (!RHS.get()->getType()->isVoidType()) 10265 S.RequireCompleteType(Loc, RHS.get()->getType(), 10266 diag::err_incomplete_type); 10267 } 10268 10269 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10270 S.DiagnoseCommaOperator(LHS.get(), Loc); 10271 10272 return RHS.get()->getType(); 10273 } 10274 10275 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10276 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10277 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10278 ExprValueKind &VK, 10279 ExprObjectKind &OK, 10280 SourceLocation OpLoc, 10281 bool IsInc, bool IsPrefix) { 10282 if (Op->isTypeDependent()) 10283 return S.Context.DependentTy; 10284 10285 QualType ResType = Op->getType(); 10286 // Atomic types can be used for increment / decrement where the non-atomic 10287 // versions can, so ignore the _Atomic() specifier for the purpose of 10288 // checking. 10289 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10290 ResType = ResAtomicType->getValueType(); 10291 10292 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10293 10294 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10295 // Decrement of bool is not allowed. 10296 if (!IsInc) { 10297 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10298 return QualType(); 10299 } 10300 // Increment of bool sets it to true, but is deprecated. 10301 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10302 : diag::warn_increment_bool) 10303 << Op->getSourceRange(); 10304 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10305 // Error on enum increments and decrements in C++ mode 10306 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10307 return QualType(); 10308 } else if (ResType->isRealType()) { 10309 // OK! 10310 } else if (ResType->isPointerType()) { 10311 // C99 6.5.2.4p2, 6.5.6p2 10312 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10313 return QualType(); 10314 } else if (ResType->isObjCObjectPointerType()) { 10315 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10316 // Otherwise, we just need a complete type. 10317 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10318 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10319 return QualType(); 10320 } else if (ResType->isAnyComplexType()) { 10321 // C99 does not support ++/-- on complex types, we allow as an extension. 10322 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10323 << ResType << Op->getSourceRange(); 10324 } else if (ResType->isPlaceholderType()) { 10325 ExprResult PR = S.CheckPlaceholderExpr(Op); 10326 if (PR.isInvalid()) return QualType(); 10327 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10328 IsInc, IsPrefix); 10329 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10330 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10331 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10332 (ResType->getAs<VectorType>()->getVectorKind() != 10333 VectorType::AltiVecBool)) { 10334 // The z vector extensions allow ++ and -- for non-bool vectors. 10335 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10336 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10337 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10338 } else { 10339 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10340 << ResType << int(IsInc) << Op->getSourceRange(); 10341 return QualType(); 10342 } 10343 // At this point, we know we have a real, complex or pointer type. 10344 // Now make sure the operand is a modifiable lvalue. 10345 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10346 return QualType(); 10347 // In C++, a prefix increment is the same type as the operand. Otherwise 10348 // (in C or with postfix), the increment is the unqualified type of the 10349 // operand. 10350 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10351 VK = VK_LValue; 10352 OK = Op->getObjectKind(); 10353 return ResType; 10354 } else { 10355 VK = VK_RValue; 10356 return ResType.getUnqualifiedType(); 10357 } 10358 } 10359 10360 10361 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10362 /// This routine allows us to typecheck complex/recursive expressions 10363 /// where the declaration is needed for type checking. We only need to 10364 /// handle cases when the expression references a function designator 10365 /// or is an lvalue. Here are some examples: 10366 /// - &(x) => x 10367 /// - &*****f => f for f a function designator. 10368 /// - &s.xx => s 10369 /// - &s.zz[1].yy -> s, if zz is an array 10370 /// - *(x + 1) -> x, if x is an array 10371 /// - &"123"[2] -> 0 10372 /// - & __real__ x -> x 10373 static ValueDecl *getPrimaryDecl(Expr *E) { 10374 switch (E->getStmtClass()) { 10375 case Stmt::DeclRefExprClass: 10376 return cast<DeclRefExpr>(E)->getDecl(); 10377 case Stmt::MemberExprClass: 10378 // If this is an arrow operator, the address is an offset from 10379 // the base's value, so the object the base refers to is 10380 // irrelevant. 10381 if (cast<MemberExpr>(E)->isArrow()) 10382 return nullptr; 10383 // Otherwise, the expression refers to a part of the base 10384 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10385 case Stmt::ArraySubscriptExprClass: { 10386 // FIXME: This code shouldn't be necessary! We should catch the implicit 10387 // promotion of register arrays earlier. 10388 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10389 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10390 if (ICE->getSubExpr()->getType()->isArrayType()) 10391 return getPrimaryDecl(ICE->getSubExpr()); 10392 } 10393 return nullptr; 10394 } 10395 case Stmt::UnaryOperatorClass: { 10396 UnaryOperator *UO = cast<UnaryOperator>(E); 10397 10398 switch(UO->getOpcode()) { 10399 case UO_Real: 10400 case UO_Imag: 10401 case UO_Extension: 10402 return getPrimaryDecl(UO->getSubExpr()); 10403 default: 10404 return nullptr; 10405 } 10406 } 10407 case Stmt::ParenExprClass: 10408 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10409 case Stmt::ImplicitCastExprClass: 10410 // If the result of an implicit cast is an l-value, we care about 10411 // the sub-expression; otherwise, the result here doesn't matter. 10412 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10413 default: 10414 return nullptr; 10415 } 10416 } 10417 10418 namespace { 10419 enum { 10420 AO_Bit_Field = 0, 10421 AO_Vector_Element = 1, 10422 AO_Property_Expansion = 2, 10423 AO_Register_Variable = 3, 10424 AO_No_Error = 4 10425 }; 10426 } 10427 /// \brief Diagnose invalid operand for address of operations. 10428 /// 10429 /// \param Type The type of operand which cannot have its address taken. 10430 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10431 Expr *E, unsigned Type) { 10432 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10433 } 10434 10435 /// CheckAddressOfOperand - The operand of & must be either a function 10436 /// designator or an lvalue designating an object. If it is an lvalue, the 10437 /// object cannot be declared with storage class register or be a bit field. 10438 /// Note: The usual conversions are *not* applied to the operand of the & 10439 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10440 /// In C++, the operand might be an overloaded function name, in which case 10441 /// we allow the '&' but retain the overloaded-function type. 10442 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10443 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10444 if (PTy->getKind() == BuiltinType::Overload) { 10445 Expr *E = OrigOp.get()->IgnoreParens(); 10446 if (!isa<OverloadExpr>(E)) { 10447 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10448 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10449 << OrigOp.get()->getSourceRange(); 10450 return QualType(); 10451 } 10452 10453 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10454 if (isa<UnresolvedMemberExpr>(Ovl)) 10455 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10456 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10457 << OrigOp.get()->getSourceRange(); 10458 return QualType(); 10459 } 10460 10461 return Context.OverloadTy; 10462 } 10463 10464 if (PTy->getKind() == BuiltinType::UnknownAny) 10465 return Context.UnknownAnyTy; 10466 10467 if (PTy->getKind() == BuiltinType::BoundMember) { 10468 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10469 << OrigOp.get()->getSourceRange(); 10470 return QualType(); 10471 } 10472 10473 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10474 if (OrigOp.isInvalid()) return QualType(); 10475 } 10476 10477 if (OrigOp.get()->isTypeDependent()) 10478 return Context.DependentTy; 10479 10480 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10481 10482 // Make sure to ignore parentheses in subsequent checks 10483 Expr *op = OrigOp.get()->IgnoreParens(); 10484 10485 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10486 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10487 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10488 return QualType(); 10489 } 10490 10491 if (getLangOpts().C99) { 10492 // Implement C99-only parts of addressof rules. 10493 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10494 if (uOp->getOpcode() == UO_Deref) 10495 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10496 // (assuming the deref expression is valid). 10497 return uOp->getSubExpr()->getType(); 10498 } 10499 // Technically, there should be a check for array subscript 10500 // expressions here, but the result of one is always an lvalue anyway. 10501 } 10502 ValueDecl *dcl = getPrimaryDecl(op); 10503 10504 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10505 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10506 op->getLocStart())) 10507 return QualType(); 10508 10509 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10510 unsigned AddressOfError = AO_No_Error; 10511 10512 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10513 bool sfinae = (bool)isSFINAEContext(); 10514 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10515 : diag::ext_typecheck_addrof_temporary) 10516 << op->getType() << op->getSourceRange(); 10517 if (sfinae) 10518 return QualType(); 10519 // Materialize the temporary as an lvalue so that we can take its address. 10520 OrigOp = op = 10521 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10522 } else if (isa<ObjCSelectorExpr>(op)) { 10523 return Context.getPointerType(op->getType()); 10524 } else if (lval == Expr::LV_MemberFunction) { 10525 // If it's an instance method, make a member pointer. 10526 // The expression must have exactly the form &A::foo. 10527 10528 // If the underlying expression isn't a decl ref, give up. 10529 if (!isa<DeclRefExpr>(op)) { 10530 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10531 << OrigOp.get()->getSourceRange(); 10532 return QualType(); 10533 } 10534 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10535 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10536 10537 // The id-expression was parenthesized. 10538 if (OrigOp.get() != DRE) { 10539 Diag(OpLoc, diag::err_parens_pointer_member_function) 10540 << OrigOp.get()->getSourceRange(); 10541 10542 // The method was named without a qualifier. 10543 } else if (!DRE->getQualifier()) { 10544 if (MD->getParent()->getName().empty()) 10545 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10546 << op->getSourceRange(); 10547 else { 10548 SmallString<32> Str; 10549 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10550 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10551 << op->getSourceRange() 10552 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10553 } 10554 } 10555 10556 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10557 if (isa<CXXDestructorDecl>(MD)) 10558 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10559 10560 QualType MPTy = Context.getMemberPointerType( 10561 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10562 // Under the MS ABI, lock down the inheritance model now. 10563 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10564 (void)isCompleteType(OpLoc, MPTy); 10565 return MPTy; 10566 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10567 // C99 6.5.3.2p1 10568 // The operand must be either an l-value or a function designator 10569 if (!op->getType()->isFunctionType()) { 10570 // Use a special diagnostic for loads from property references. 10571 if (isa<PseudoObjectExpr>(op)) { 10572 AddressOfError = AO_Property_Expansion; 10573 } else { 10574 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10575 << op->getType() << op->getSourceRange(); 10576 return QualType(); 10577 } 10578 } 10579 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10580 // The operand cannot be a bit-field 10581 AddressOfError = AO_Bit_Field; 10582 } else if (op->getObjectKind() == OK_VectorComponent) { 10583 // The operand cannot be an element of a vector 10584 AddressOfError = AO_Vector_Element; 10585 } else if (dcl) { // C99 6.5.3.2p1 10586 // We have an lvalue with a decl. Make sure the decl is not declared 10587 // with the register storage-class specifier. 10588 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10589 // in C++ it is not error to take address of a register 10590 // variable (c++03 7.1.1P3) 10591 if (vd->getStorageClass() == SC_Register && 10592 !getLangOpts().CPlusPlus) { 10593 AddressOfError = AO_Register_Variable; 10594 } 10595 } else if (isa<MSPropertyDecl>(dcl)) { 10596 AddressOfError = AO_Property_Expansion; 10597 } else if (isa<FunctionTemplateDecl>(dcl)) { 10598 return Context.OverloadTy; 10599 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10600 // Okay: we can take the address of a field. 10601 // Could be a pointer to member, though, if there is an explicit 10602 // scope qualifier for the class. 10603 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10604 DeclContext *Ctx = dcl->getDeclContext(); 10605 if (Ctx && Ctx->isRecord()) { 10606 if (dcl->getType()->isReferenceType()) { 10607 Diag(OpLoc, 10608 diag::err_cannot_form_pointer_to_member_of_reference_type) 10609 << dcl->getDeclName() << dcl->getType(); 10610 return QualType(); 10611 } 10612 10613 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10614 Ctx = Ctx->getParent(); 10615 10616 QualType MPTy = Context.getMemberPointerType( 10617 op->getType(), 10618 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10619 // Under the MS ABI, lock down the inheritance model now. 10620 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10621 (void)isCompleteType(OpLoc, MPTy); 10622 return MPTy; 10623 } 10624 } 10625 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10626 !isa<BindingDecl>(dcl)) 10627 llvm_unreachable("Unknown/unexpected decl type"); 10628 } 10629 10630 if (AddressOfError != AO_No_Error) { 10631 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10632 return QualType(); 10633 } 10634 10635 if (lval == Expr::LV_IncompleteVoidType) { 10636 // Taking the address of a void variable is technically illegal, but we 10637 // allow it in cases which are otherwise valid. 10638 // Example: "extern void x; void* y = &x;". 10639 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10640 } 10641 10642 // If the operand has type "type", the result has type "pointer to type". 10643 if (op->getType()->isObjCObjectType()) 10644 return Context.getObjCObjectPointerType(op->getType()); 10645 10646 CheckAddressOfPackedMember(op); 10647 10648 return Context.getPointerType(op->getType()); 10649 } 10650 10651 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10652 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10653 if (!DRE) 10654 return; 10655 const Decl *D = DRE->getDecl(); 10656 if (!D) 10657 return; 10658 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10659 if (!Param) 10660 return; 10661 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10662 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10663 return; 10664 if (FunctionScopeInfo *FD = S.getCurFunction()) 10665 if (!FD->ModifiedNonNullParams.count(Param)) 10666 FD->ModifiedNonNullParams.insert(Param); 10667 } 10668 10669 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10670 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10671 SourceLocation OpLoc) { 10672 if (Op->isTypeDependent()) 10673 return S.Context.DependentTy; 10674 10675 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10676 if (ConvResult.isInvalid()) 10677 return QualType(); 10678 Op = ConvResult.get(); 10679 QualType OpTy = Op->getType(); 10680 QualType Result; 10681 10682 if (isa<CXXReinterpretCastExpr>(Op)) { 10683 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10684 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10685 Op->getSourceRange()); 10686 } 10687 10688 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10689 { 10690 Result = PT->getPointeeType(); 10691 } 10692 else if (const ObjCObjectPointerType *OPT = 10693 OpTy->getAs<ObjCObjectPointerType>()) 10694 Result = OPT->getPointeeType(); 10695 else { 10696 ExprResult PR = S.CheckPlaceholderExpr(Op); 10697 if (PR.isInvalid()) return QualType(); 10698 if (PR.get() != Op) 10699 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10700 } 10701 10702 if (Result.isNull()) { 10703 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10704 << OpTy << Op->getSourceRange(); 10705 return QualType(); 10706 } 10707 10708 // Note that per both C89 and C99, indirection is always legal, even if Result 10709 // is an incomplete type or void. It would be possible to warn about 10710 // dereferencing a void pointer, but it's completely well-defined, and such a 10711 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10712 // for pointers to 'void' but is fine for any other pointer type: 10713 // 10714 // C++ [expr.unary.op]p1: 10715 // [...] the expression to which [the unary * operator] is applied shall 10716 // be a pointer to an object type, or a pointer to a function type 10717 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10718 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10719 << OpTy << Op->getSourceRange(); 10720 10721 // Dereferences are usually l-values... 10722 VK = VK_LValue; 10723 10724 // ...except that certain expressions are never l-values in C. 10725 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10726 VK = VK_RValue; 10727 10728 return Result; 10729 } 10730 10731 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10732 BinaryOperatorKind Opc; 10733 switch (Kind) { 10734 default: llvm_unreachable("Unknown binop!"); 10735 case tok::periodstar: Opc = BO_PtrMemD; break; 10736 case tok::arrowstar: Opc = BO_PtrMemI; break; 10737 case tok::star: Opc = BO_Mul; break; 10738 case tok::slash: Opc = BO_Div; break; 10739 case tok::percent: Opc = BO_Rem; break; 10740 case tok::plus: Opc = BO_Add; break; 10741 case tok::minus: Opc = BO_Sub; break; 10742 case tok::lessless: Opc = BO_Shl; break; 10743 case tok::greatergreater: Opc = BO_Shr; break; 10744 case tok::lessequal: Opc = BO_LE; break; 10745 case tok::less: Opc = BO_LT; break; 10746 case tok::greaterequal: Opc = BO_GE; break; 10747 case tok::greater: Opc = BO_GT; break; 10748 case tok::exclaimequal: Opc = BO_NE; break; 10749 case tok::equalequal: Opc = BO_EQ; break; 10750 case tok::amp: Opc = BO_And; break; 10751 case tok::caret: Opc = BO_Xor; break; 10752 case tok::pipe: Opc = BO_Or; break; 10753 case tok::ampamp: Opc = BO_LAnd; break; 10754 case tok::pipepipe: Opc = BO_LOr; break; 10755 case tok::equal: Opc = BO_Assign; break; 10756 case tok::starequal: Opc = BO_MulAssign; break; 10757 case tok::slashequal: Opc = BO_DivAssign; break; 10758 case tok::percentequal: Opc = BO_RemAssign; break; 10759 case tok::plusequal: Opc = BO_AddAssign; break; 10760 case tok::minusequal: Opc = BO_SubAssign; break; 10761 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10762 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10763 case tok::ampequal: Opc = BO_AndAssign; break; 10764 case tok::caretequal: Opc = BO_XorAssign; break; 10765 case tok::pipeequal: Opc = BO_OrAssign; break; 10766 case tok::comma: Opc = BO_Comma; break; 10767 } 10768 return Opc; 10769 } 10770 10771 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10772 tok::TokenKind Kind) { 10773 UnaryOperatorKind Opc; 10774 switch (Kind) { 10775 default: llvm_unreachable("Unknown unary op!"); 10776 case tok::plusplus: Opc = UO_PreInc; break; 10777 case tok::minusminus: Opc = UO_PreDec; break; 10778 case tok::amp: Opc = UO_AddrOf; break; 10779 case tok::star: Opc = UO_Deref; break; 10780 case tok::plus: Opc = UO_Plus; break; 10781 case tok::minus: Opc = UO_Minus; break; 10782 case tok::tilde: Opc = UO_Not; break; 10783 case tok::exclaim: Opc = UO_LNot; break; 10784 case tok::kw___real: Opc = UO_Real; break; 10785 case tok::kw___imag: Opc = UO_Imag; break; 10786 case tok::kw___extension__: Opc = UO_Extension; break; 10787 } 10788 return Opc; 10789 } 10790 10791 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10792 /// This warning is only emitted for builtin assignment operations. It is also 10793 /// suppressed in the event of macro expansions. 10794 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10795 SourceLocation OpLoc) { 10796 if (!S.ActiveTemplateInstantiations.empty()) 10797 return; 10798 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10799 return; 10800 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10801 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10802 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10803 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10804 if (!LHSDeclRef || !RHSDeclRef || 10805 LHSDeclRef->getLocation().isMacroID() || 10806 RHSDeclRef->getLocation().isMacroID()) 10807 return; 10808 const ValueDecl *LHSDecl = 10809 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10810 const ValueDecl *RHSDecl = 10811 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10812 if (LHSDecl != RHSDecl) 10813 return; 10814 if (LHSDecl->getType().isVolatileQualified()) 10815 return; 10816 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10817 if (RefTy->getPointeeType().isVolatileQualified()) 10818 return; 10819 10820 S.Diag(OpLoc, diag::warn_self_assignment) 10821 << LHSDeclRef->getType() 10822 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10823 } 10824 10825 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10826 /// is usually indicative of introspection within the Objective-C pointer. 10827 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10828 SourceLocation OpLoc) { 10829 if (!S.getLangOpts().ObjC1) 10830 return; 10831 10832 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10833 const Expr *LHS = L.get(); 10834 const Expr *RHS = R.get(); 10835 10836 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10837 ObjCPointerExpr = LHS; 10838 OtherExpr = RHS; 10839 } 10840 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10841 ObjCPointerExpr = RHS; 10842 OtherExpr = LHS; 10843 } 10844 10845 // This warning is deliberately made very specific to reduce false 10846 // positives with logic that uses '&' for hashing. This logic mainly 10847 // looks for code trying to introspect into tagged pointers, which 10848 // code should generally never do. 10849 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10850 unsigned Diag = diag::warn_objc_pointer_masking; 10851 // Determine if we are introspecting the result of performSelectorXXX. 10852 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10853 // Special case messages to -performSelector and friends, which 10854 // can return non-pointer values boxed in a pointer value. 10855 // Some clients may wish to silence warnings in this subcase. 10856 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10857 Selector S = ME->getSelector(); 10858 StringRef SelArg0 = S.getNameForSlot(0); 10859 if (SelArg0.startswith("performSelector")) 10860 Diag = diag::warn_objc_pointer_masking_performSelector; 10861 } 10862 10863 S.Diag(OpLoc, Diag) 10864 << ObjCPointerExpr->getSourceRange(); 10865 } 10866 } 10867 10868 static NamedDecl *getDeclFromExpr(Expr *E) { 10869 if (!E) 10870 return nullptr; 10871 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10872 return DRE->getDecl(); 10873 if (auto *ME = dyn_cast<MemberExpr>(E)) 10874 return ME->getMemberDecl(); 10875 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10876 return IRE->getDecl(); 10877 return nullptr; 10878 } 10879 10880 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10881 /// operator @p Opc at location @c TokLoc. This routine only supports 10882 /// built-in operations; ActOnBinOp handles overloaded operators. 10883 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10884 BinaryOperatorKind Opc, 10885 Expr *LHSExpr, Expr *RHSExpr) { 10886 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10887 // The syntax only allows initializer lists on the RHS of assignment, 10888 // so we don't need to worry about accepting invalid code for 10889 // non-assignment operators. 10890 // C++11 5.17p9: 10891 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10892 // of x = {} is x = T(). 10893 InitializationKind Kind = 10894 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10895 InitializedEntity Entity = 10896 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10897 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10898 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10899 if (Init.isInvalid()) 10900 return Init; 10901 RHSExpr = Init.get(); 10902 } 10903 10904 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10905 QualType ResultTy; // Result type of the binary operator. 10906 // The following two variables are used for compound assignment operators 10907 QualType CompLHSTy; // Type of LHS after promotions for computation 10908 QualType CompResultTy; // Type of computation result 10909 ExprValueKind VK = VK_RValue; 10910 ExprObjectKind OK = OK_Ordinary; 10911 10912 if (!getLangOpts().CPlusPlus) { 10913 // C cannot handle TypoExpr nodes on either side of a binop because it 10914 // doesn't handle dependent types properly, so make sure any TypoExprs have 10915 // been dealt with before checking the operands. 10916 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10917 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10918 if (Opc != BO_Assign) 10919 return ExprResult(E); 10920 // Avoid correcting the RHS to the same Expr as the LHS. 10921 Decl *D = getDeclFromExpr(E); 10922 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10923 }); 10924 if (!LHS.isUsable() || !RHS.isUsable()) 10925 return ExprError(); 10926 } 10927 10928 if (getLangOpts().OpenCL) { 10929 QualType LHSTy = LHSExpr->getType(); 10930 QualType RHSTy = RHSExpr->getType(); 10931 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10932 // the ATOMIC_VAR_INIT macro. 10933 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 10934 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10935 if (BO_Assign == Opc) 10936 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10937 else 10938 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10939 return ExprError(); 10940 } 10941 10942 // OpenCL special types - image, sampler, pipe, and blocks are to be used 10943 // only with a builtin functions and therefore should be disallowed here. 10944 if (LHSTy->isImageType() || RHSTy->isImageType() || 10945 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 10946 LHSTy->isPipeType() || RHSTy->isPipeType() || 10947 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 10948 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10949 return ExprError(); 10950 } 10951 } 10952 10953 switch (Opc) { 10954 case BO_Assign: 10955 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10956 if (getLangOpts().CPlusPlus && 10957 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10958 VK = LHS.get()->getValueKind(); 10959 OK = LHS.get()->getObjectKind(); 10960 } 10961 if (!ResultTy.isNull()) { 10962 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10963 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10964 } 10965 RecordModifiableNonNullParam(*this, LHS.get()); 10966 break; 10967 case BO_PtrMemD: 10968 case BO_PtrMemI: 10969 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10970 Opc == BO_PtrMemI); 10971 break; 10972 case BO_Mul: 10973 case BO_Div: 10974 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10975 Opc == BO_Div); 10976 break; 10977 case BO_Rem: 10978 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10979 break; 10980 case BO_Add: 10981 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10982 break; 10983 case BO_Sub: 10984 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10985 break; 10986 case BO_Shl: 10987 case BO_Shr: 10988 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10989 break; 10990 case BO_LE: 10991 case BO_LT: 10992 case BO_GE: 10993 case BO_GT: 10994 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10995 break; 10996 case BO_EQ: 10997 case BO_NE: 10998 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10999 break; 11000 case BO_And: 11001 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11002 case BO_Xor: 11003 case BO_Or: 11004 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 11005 break; 11006 case BO_LAnd: 11007 case BO_LOr: 11008 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11009 break; 11010 case BO_MulAssign: 11011 case BO_DivAssign: 11012 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11013 Opc == BO_DivAssign); 11014 CompLHSTy = CompResultTy; 11015 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11016 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11017 break; 11018 case BO_RemAssign: 11019 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11020 CompLHSTy = CompResultTy; 11021 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11022 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11023 break; 11024 case BO_AddAssign: 11025 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11026 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11027 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11028 break; 11029 case BO_SubAssign: 11030 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11031 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11032 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11033 break; 11034 case BO_ShlAssign: 11035 case BO_ShrAssign: 11036 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11037 CompLHSTy = CompResultTy; 11038 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11039 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11040 break; 11041 case BO_AndAssign: 11042 case BO_OrAssign: // fallthrough 11043 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11044 case BO_XorAssign: 11045 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 11046 CompLHSTy = CompResultTy; 11047 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11048 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11049 break; 11050 case BO_Comma: 11051 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11052 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11053 VK = RHS.get()->getValueKind(); 11054 OK = RHS.get()->getObjectKind(); 11055 } 11056 break; 11057 } 11058 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11059 return ExprError(); 11060 11061 // Check for array bounds violations for both sides of the BinaryOperator 11062 CheckArrayAccess(LHS.get()); 11063 CheckArrayAccess(RHS.get()); 11064 11065 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11066 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11067 &Context.Idents.get("object_setClass"), 11068 SourceLocation(), LookupOrdinaryName); 11069 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11070 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11071 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11072 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11073 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11074 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11075 } 11076 else 11077 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11078 } 11079 else if (const ObjCIvarRefExpr *OIRE = 11080 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11081 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11082 11083 if (CompResultTy.isNull()) 11084 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11085 OK, OpLoc, FPFeatures.fp_contract); 11086 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11087 OK_ObjCProperty) { 11088 VK = VK_LValue; 11089 OK = LHS.get()->getObjectKind(); 11090 } 11091 return new (Context) CompoundAssignOperator( 11092 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11093 OpLoc, FPFeatures.fp_contract); 11094 } 11095 11096 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11097 /// operators are mixed in a way that suggests that the programmer forgot that 11098 /// comparison operators have higher precedence. The most typical example of 11099 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11100 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11101 SourceLocation OpLoc, Expr *LHSExpr, 11102 Expr *RHSExpr) { 11103 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11104 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11105 11106 // Check that one of the sides is a comparison operator and the other isn't. 11107 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11108 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11109 if (isLeftComp == isRightComp) 11110 return; 11111 11112 // Bitwise operations are sometimes used as eager logical ops. 11113 // Don't diagnose this. 11114 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11115 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11116 if (isLeftBitwise || isRightBitwise) 11117 return; 11118 11119 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11120 OpLoc) 11121 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11122 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11123 SourceRange ParensRange = isLeftComp ? 11124 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11125 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11126 11127 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11128 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11129 SuggestParentheses(Self, OpLoc, 11130 Self.PDiag(diag::note_precedence_silence) << OpStr, 11131 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11132 SuggestParentheses(Self, OpLoc, 11133 Self.PDiag(diag::note_precedence_bitwise_first) 11134 << BinaryOperator::getOpcodeStr(Opc), 11135 ParensRange); 11136 } 11137 11138 /// \brief It accepts a '&&' expr that is inside a '||' one. 11139 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11140 /// in parentheses. 11141 static void 11142 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11143 BinaryOperator *Bop) { 11144 assert(Bop->getOpcode() == BO_LAnd); 11145 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11146 << Bop->getSourceRange() << OpLoc; 11147 SuggestParentheses(Self, Bop->getOperatorLoc(), 11148 Self.PDiag(diag::note_precedence_silence) 11149 << Bop->getOpcodeStr(), 11150 Bop->getSourceRange()); 11151 } 11152 11153 /// \brief Returns true if the given expression can be evaluated as a constant 11154 /// 'true'. 11155 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11156 bool Res; 11157 return !E->isValueDependent() && 11158 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11159 } 11160 11161 /// \brief Returns true if the given expression can be evaluated as a constant 11162 /// 'false'. 11163 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11164 bool Res; 11165 return !E->isValueDependent() && 11166 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11167 } 11168 11169 /// \brief Look for '&&' in the left hand of a '||' expr. 11170 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11171 Expr *LHSExpr, Expr *RHSExpr) { 11172 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11173 if (Bop->getOpcode() == BO_LAnd) { 11174 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11175 if (EvaluatesAsFalse(S, RHSExpr)) 11176 return; 11177 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11178 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11179 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11180 } else if (Bop->getOpcode() == BO_LOr) { 11181 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11182 // If it's "a || b && 1 || c" we didn't warn earlier for 11183 // "a || b && 1", but warn now. 11184 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11185 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11186 } 11187 } 11188 } 11189 } 11190 11191 /// \brief Look for '&&' in the right hand of a '||' expr. 11192 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11193 Expr *LHSExpr, Expr *RHSExpr) { 11194 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11195 if (Bop->getOpcode() == BO_LAnd) { 11196 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11197 if (EvaluatesAsFalse(S, LHSExpr)) 11198 return; 11199 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11200 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11201 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11202 } 11203 } 11204 } 11205 11206 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11207 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11208 /// the '&' expression in parentheses. 11209 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11210 SourceLocation OpLoc, Expr *SubExpr) { 11211 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11212 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11213 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11214 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11215 << Bop->getSourceRange() << OpLoc; 11216 SuggestParentheses(S, Bop->getOperatorLoc(), 11217 S.PDiag(diag::note_precedence_silence) 11218 << Bop->getOpcodeStr(), 11219 Bop->getSourceRange()); 11220 } 11221 } 11222 } 11223 11224 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11225 Expr *SubExpr, StringRef Shift) { 11226 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11227 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11228 StringRef Op = Bop->getOpcodeStr(); 11229 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11230 << Bop->getSourceRange() << OpLoc << Shift << Op; 11231 SuggestParentheses(S, Bop->getOperatorLoc(), 11232 S.PDiag(diag::note_precedence_silence) << Op, 11233 Bop->getSourceRange()); 11234 } 11235 } 11236 } 11237 11238 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11239 Expr *LHSExpr, Expr *RHSExpr) { 11240 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11241 if (!OCE) 11242 return; 11243 11244 FunctionDecl *FD = OCE->getDirectCallee(); 11245 if (!FD || !FD->isOverloadedOperator()) 11246 return; 11247 11248 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11249 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11250 return; 11251 11252 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11253 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11254 << (Kind == OO_LessLess); 11255 SuggestParentheses(S, OCE->getOperatorLoc(), 11256 S.PDiag(diag::note_precedence_silence) 11257 << (Kind == OO_LessLess ? "<<" : ">>"), 11258 OCE->getSourceRange()); 11259 SuggestParentheses(S, OpLoc, 11260 S.PDiag(diag::note_evaluate_comparison_first), 11261 SourceRange(OCE->getArg(1)->getLocStart(), 11262 RHSExpr->getLocEnd())); 11263 } 11264 11265 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11266 /// precedence. 11267 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11268 SourceLocation OpLoc, Expr *LHSExpr, 11269 Expr *RHSExpr){ 11270 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11271 if (BinaryOperator::isBitwiseOp(Opc)) 11272 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11273 11274 // Diagnose "arg1 & arg2 | arg3" 11275 if ((Opc == BO_Or || Opc == BO_Xor) && 11276 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11277 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11278 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11279 } 11280 11281 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11282 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11283 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11284 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11285 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11286 } 11287 11288 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11289 || Opc == BO_Shr) { 11290 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11291 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11292 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11293 } 11294 11295 // Warn on overloaded shift operators and comparisons, such as: 11296 // cout << 5 == 4; 11297 if (BinaryOperator::isComparisonOp(Opc)) 11298 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11299 } 11300 11301 // Binary Operators. 'Tok' is the token for the operator. 11302 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11303 tok::TokenKind Kind, 11304 Expr *LHSExpr, Expr *RHSExpr) { 11305 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11306 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11307 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11308 11309 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11310 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11311 11312 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11313 } 11314 11315 /// Build an overloaded binary operator expression in the given scope. 11316 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11317 BinaryOperatorKind Opc, 11318 Expr *LHS, Expr *RHS) { 11319 // Find all of the overloaded operators visible from this 11320 // point. We perform both an operator-name lookup from the local 11321 // scope and an argument-dependent lookup based on the types of 11322 // the arguments. 11323 UnresolvedSet<16> Functions; 11324 OverloadedOperatorKind OverOp 11325 = BinaryOperator::getOverloadedOperator(Opc); 11326 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11327 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11328 RHS->getType(), Functions); 11329 11330 // Build the (potentially-overloaded, potentially-dependent) 11331 // binary operation. 11332 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11333 } 11334 11335 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11336 BinaryOperatorKind Opc, 11337 Expr *LHSExpr, Expr *RHSExpr) { 11338 // We want to end up calling one of checkPseudoObjectAssignment 11339 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11340 // both expressions are overloadable or either is type-dependent), 11341 // or CreateBuiltinBinOp (in any other case). We also want to get 11342 // any placeholder types out of the way. 11343 11344 // Handle pseudo-objects in the LHS. 11345 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11346 // Assignments with a pseudo-object l-value need special analysis. 11347 if (pty->getKind() == BuiltinType::PseudoObject && 11348 BinaryOperator::isAssignmentOp(Opc)) 11349 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11350 11351 // Don't resolve overloads if the other type is overloadable. 11352 if (pty->getKind() == BuiltinType::Overload) { 11353 // We can't actually test that if we still have a placeholder, 11354 // though. Fortunately, none of the exceptions we see in that 11355 // code below are valid when the LHS is an overload set. Note 11356 // that an overload set can be dependently-typed, but it never 11357 // instantiates to having an overloadable type. 11358 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11359 if (resolvedRHS.isInvalid()) return ExprError(); 11360 RHSExpr = resolvedRHS.get(); 11361 11362 if (RHSExpr->isTypeDependent() || 11363 RHSExpr->getType()->isOverloadableType()) 11364 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11365 } 11366 11367 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11368 if (LHS.isInvalid()) return ExprError(); 11369 LHSExpr = LHS.get(); 11370 } 11371 11372 // Handle pseudo-objects in the RHS. 11373 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11374 // An overload in the RHS can potentially be resolved by the type 11375 // being assigned to. 11376 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11377 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11378 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11379 11380 if (LHSExpr->getType()->isOverloadableType()) 11381 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11382 11383 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11384 } 11385 11386 // Don't resolve overloads if the other type is overloadable. 11387 if (pty->getKind() == BuiltinType::Overload && 11388 LHSExpr->getType()->isOverloadableType()) 11389 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11390 11391 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11392 if (!resolvedRHS.isUsable()) return ExprError(); 11393 RHSExpr = resolvedRHS.get(); 11394 } 11395 11396 if (getLangOpts().CPlusPlus) { 11397 // If either expression is type-dependent, always build an 11398 // overloaded op. 11399 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11400 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11401 11402 // Otherwise, build an overloaded op if either expression has an 11403 // overloadable type. 11404 if (LHSExpr->getType()->isOverloadableType() || 11405 RHSExpr->getType()->isOverloadableType()) 11406 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11407 } 11408 11409 // Build a built-in binary operation. 11410 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11411 } 11412 11413 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11414 UnaryOperatorKind Opc, 11415 Expr *InputExpr) { 11416 ExprResult Input = InputExpr; 11417 ExprValueKind VK = VK_RValue; 11418 ExprObjectKind OK = OK_Ordinary; 11419 QualType resultType; 11420 if (getLangOpts().OpenCL) { 11421 QualType Ty = InputExpr->getType(); 11422 // The only legal unary operation for atomics is '&'. 11423 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11424 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11425 // only with a builtin functions and therefore should be disallowed here. 11426 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11427 || Ty->isBlockPointerType())) { 11428 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11429 << InputExpr->getType() 11430 << Input.get()->getSourceRange()); 11431 } 11432 } 11433 switch (Opc) { 11434 case UO_PreInc: 11435 case UO_PreDec: 11436 case UO_PostInc: 11437 case UO_PostDec: 11438 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11439 OpLoc, 11440 Opc == UO_PreInc || 11441 Opc == UO_PostInc, 11442 Opc == UO_PreInc || 11443 Opc == UO_PreDec); 11444 break; 11445 case UO_AddrOf: 11446 resultType = CheckAddressOfOperand(Input, OpLoc); 11447 RecordModifiableNonNullParam(*this, InputExpr); 11448 break; 11449 case UO_Deref: { 11450 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11451 if (Input.isInvalid()) return ExprError(); 11452 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11453 break; 11454 } 11455 case UO_Plus: 11456 case UO_Minus: 11457 Input = UsualUnaryConversions(Input.get()); 11458 if (Input.isInvalid()) return ExprError(); 11459 resultType = Input.get()->getType(); 11460 if (resultType->isDependentType()) 11461 break; 11462 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11463 break; 11464 else if (resultType->isVectorType() && 11465 // The z vector extensions don't allow + or - with bool vectors. 11466 (!Context.getLangOpts().ZVector || 11467 resultType->getAs<VectorType>()->getVectorKind() != 11468 VectorType::AltiVecBool)) 11469 break; 11470 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11471 Opc == UO_Plus && 11472 resultType->isPointerType()) 11473 break; 11474 11475 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11476 << resultType << Input.get()->getSourceRange()); 11477 11478 case UO_Not: // bitwise complement 11479 Input = UsualUnaryConversions(Input.get()); 11480 if (Input.isInvalid()) 11481 return ExprError(); 11482 resultType = Input.get()->getType(); 11483 if (resultType->isDependentType()) 11484 break; 11485 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11486 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11487 // C99 does not support '~' for complex conjugation. 11488 Diag(OpLoc, diag::ext_integer_complement_complex) 11489 << resultType << Input.get()->getSourceRange(); 11490 else if (resultType->hasIntegerRepresentation()) 11491 break; 11492 else if (resultType->isExtVectorType()) { 11493 if (Context.getLangOpts().OpenCL) { 11494 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11495 // on vector float types. 11496 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11497 if (!T->isIntegerType()) 11498 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11499 << resultType << Input.get()->getSourceRange()); 11500 } 11501 break; 11502 } else { 11503 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11504 << resultType << Input.get()->getSourceRange()); 11505 } 11506 break; 11507 11508 case UO_LNot: // logical negation 11509 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11510 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11511 if (Input.isInvalid()) return ExprError(); 11512 resultType = Input.get()->getType(); 11513 11514 // Though we still have to promote half FP to float... 11515 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11516 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11517 resultType = Context.FloatTy; 11518 } 11519 11520 if (resultType->isDependentType()) 11521 break; 11522 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11523 // C99 6.5.3.3p1: ok, fallthrough; 11524 if (Context.getLangOpts().CPlusPlus) { 11525 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11526 // operand contextually converted to bool. 11527 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11528 ScalarTypeToBooleanCastKind(resultType)); 11529 } else if (Context.getLangOpts().OpenCL && 11530 Context.getLangOpts().OpenCLVersion < 120) { 11531 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11532 // operate on scalar float types. 11533 if (!resultType->isIntegerType()) 11534 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11535 << resultType << Input.get()->getSourceRange()); 11536 } 11537 } else if (resultType->isExtVectorType()) { 11538 if (Context.getLangOpts().OpenCL && 11539 Context.getLangOpts().OpenCLVersion < 120) { 11540 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11541 // operate on vector float types. 11542 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11543 if (!T->isIntegerType()) 11544 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11545 << resultType << Input.get()->getSourceRange()); 11546 } 11547 // Vector logical not returns the signed variant of the operand type. 11548 resultType = GetSignedVectorType(resultType); 11549 break; 11550 } else { 11551 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11552 << resultType << Input.get()->getSourceRange()); 11553 } 11554 11555 // LNot always has type int. C99 6.5.3.3p5. 11556 // In C++, it's bool. C++ 5.3.1p8 11557 resultType = Context.getLogicalOperationType(); 11558 break; 11559 case UO_Real: 11560 case UO_Imag: 11561 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11562 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11563 // complex l-values to ordinary l-values and all other values to r-values. 11564 if (Input.isInvalid()) return ExprError(); 11565 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11566 if (Input.get()->getValueKind() != VK_RValue && 11567 Input.get()->getObjectKind() == OK_Ordinary) 11568 VK = Input.get()->getValueKind(); 11569 } else if (!getLangOpts().CPlusPlus) { 11570 // In C, a volatile scalar is read by __imag. In C++, it is not. 11571 Input = DefaultLvalueConversion(Input.get()); 11572 } 11573 break; 11574 case UO_Extension: 11575 case UO_Coawait: 11576 resultType = Input.get()->getType(); 11577 VK = Input.get()->getValueKind(); 11578 OK = Input.get()->getObjectKind(); 11579 break; 11580 } 11581 if (resultType.isNull() || Input.isInvalid()) 11582 return ExprError(); 11583 11584 // Check for array bounds violations in the operand of the UnaryOperator, 11585 // except for the '*' and '&' operators that have to be handled specially 11586 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11587 // that are explicitly defined as valid by the standard). 11588 if (Opc != UO_AddrOf && Opc != UO_Deref) 11589 CheckArrayAccess(Input.get()); 11590 11591 return new (Context) 11592 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11593 } 11594 11595 /// \brief Determine whether the given expression is a qualified member 11596 /// access expression, of a form that could be turned into a pointer to member 11597 /// with the address-of operator. 11598 static bool isQualifiedMemberAccess(Expr *E) { 11599 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11600 if (!DRE->getQualifier()) 11601 return false; 11602 11603 ValueDecl *VD = DRE->getDecl(); 11604 if (!VD->isCXXClassMember()) 11605 return false; 11606 11607 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11608 return true; 11609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11610 return Method->isInstance(); 11611 11612 return false; 11613 } 11614 11615 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11616 if (!ULE->getQualifier()) 11617 return false; 11618 11619 for (NamedDecl *D : ULE->decls()) { 11620 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11621 if (Method->isInstance()) 11622 return true; 11623 } else { 11624 // Overload set does not contain methods. 11625 break; 11626 } 11627 } 11628 11629 return false; 11630 } 11631 11632 return false; 11633 } 11634 11635 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11636 UnaryOperatorKind Opc, Expr *Input) { 11637 // First things first: handle placeholders so that the 11638 // overloaded-operator check considers the right type. 11639 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11640 // Increment and decrement of pseudo-object references. 11641 if (pty->getKind() == BuiltinType::PseudoObject && 11642 UnaryOperator::isIncrementDecrementOp(Opc)) 11643 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11644 11645 // extension is always a builtin operator. 11646 if (Opc == UO_Extension) 11647 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11648 11649 // & gets special logic for several kinds of placeholder. 11650 // The builtin code knows what to do. 11651 if (Opc == UO_AddrOf && 11652 (pty->getKind() == BuiltinType::Overload || 11653 pty->getKind() == BuiltinType::UnknownAny || 11654 pty->getKind() == BuiltinType::BoundMember)) 11655 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11656 11657 // Anything else needs to be handled now. 11658 ExprResult Result = CheckPlaceholderExpr(Input); 11659 if (Result.isInvalid()) return ExprError(); 11660 Input = Result.get(); 11661 } 11662 11663 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11664 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11665 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11666 // Find all of the overloaded operators visible from this 11667 // point. We perform both an operator-name lookup from the local 11668 // scope and an argument-dependent lookup based on the types of 11669 // the arguments. 11670 UnresolvedSet<16> Functions; 11671 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11672 if (S && OverOp != OO_None) 11673 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11674 Functions); 11675 11676 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11677 } 11678 11679 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11680 } 11681 11682 // Unary Operators. 'Tok' is the token for the operator. 11683 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11684 tok::TokenKind Op, Expr *Input) { 11685 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11686 } 11687 11688 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11689 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11690 LabelDecl *TheDecl) { 11691 TheDecl->markUsed(Context); 11692 // Create the AST node. The address of a label always has type 'void*'. 11693 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11694 Context.getPointerType(Context.VoidTy)); 11695 } 11696 11697 /// Given the last statement in a statement-expression, check whether 11698 /// the result is a producing expression (like a call to an 11699 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11700 /// release out of the full-expression. Otherwise, return null. 11701 /// Cannot fail. 11702 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11703 // Should always be wrapped with one of these. 11704 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11705 if (!cleanups) return nullptr; 11706 11707 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11708 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11709 return nullptr; 11710 11711 // Splice out the cast. This shouldn't modify any interesting 11712 // features of the statement. 11713 Expr *producer = cast->getSubExpr(); 11714 assert(producer->getType() == cast->getType()); 11715 assert(producer->getValueKind() == cast->getValueKind()); 11716 cleanups->setSubExpr(producer); 11717 return cleanups; 11718 } 11719 11720 void Sema::ActOnStartStmtExpr() { 11721 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11722 } 11723 11724 void Sema::ActOnStmtExprError() { 11725 // Note that function is also called by TreeTransform when leaving a 11726 // StmtExpr scope without rebuilding anything. 11727 11728 DiscardCleanupsInEvaluationContext(); 11729 PopExpressionEvaluationContext(); 11730 } 11731 11732 ExprResult 11733 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11734 SourceLocation RPLoc) { // "({..})" 11735 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11736 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11737 11738 if (hasAnyUnrecoverableErrorsInThisFunction()) 11739 DiscardCleanupsInEvaluationContext(); 11740 assert(!Cleanup.exprNeedsCleanups() && 11741 "cleanups within StmtExpr not correctly bound!"); 11742 PopExpressionEvaluationContext(); 11743 11744 // FIXME: there are a variety of strange constraints to enforce here, for 11745 // example, it is not possible to goto into a stmt expression apparently. 11746 // More semantic analysis is needed. 11747 11748 // If there are sub-stmts in the compound stmt, take the type of the last one 11749 // as the type of the stmtexpr. 11750 QualType Ty = Context.VoidTy; 11751 bool StmtExprMayBindToTemp = false; 11752 if (!Compound->body_empty()) { 11753 Stmt *LastStmt = Compound->body_back(); 11754 LabelStmt *LastLabelStmt = nullptr; 11755 // If LastStmt is a label, skip down through into the body. 11756 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11757 LastLabelStmt = Label; 11758 LastStmt = Label->getSubStmt(); 11759 } 11760 11761 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11762 // Do function/array conversion on the last expression, but not 11763 // lvalue-to-rvalue. However, initialize an unqualified type. 11764 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11765 if (LastExpr.isInvalid()) 11766 return ExprError(); 11767 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11768 11769 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11770 // In ARC, if the final expression ends in a consume, splice 11771 // the consume out and bind it later. In the alternate case 11772 // (when dealing with a retainable type), the result 11773 // initialization will create a produce. In both cases the 11774 // result will be +1, and we'll need to balance that out with 11775 // a bind. 11776 if (Expr *rebuiltLastStmt 11777 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11778 LastExpr = rebuiltLastStmt; 11779 } else { 11780 LastExpr = PerformCopyInitialization( 11781 InitializedEntity::InitializeResult(LPLoc, 11782 Ty, 11783 false), 11784 SourceLocation(), 11785 LastExpr); 11786 } 11787 11788 if (LastExpr.isInvalid()) 11789 return ExprError(); 11790 if (LastExpr.get() != nullptr) { 11791 if (!LastLabelStmt) 11792 Compound->setLastStmt(LastExpr.get()); 11793 else 11794 LastLabelStmt->setSubStmt(LastExpr.get()); 11795 StmtExprMayBindToTemp = true; 11796 } 11797 } 11798 } 11799 } 11800 11801 // FIXME: Check that expression type is complete/non-abstract; statement 11802 // expressions are not lvalues. 11803 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11804 if (StmtExprMayBindToTemp) 11805 return MaybeBindToTemporary(ResStmtExpr); 11806 return ResStmtExpr; 11807 } 11808 11809 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11810 TypeSourceInfo *TInfo, 11811 ArrayRef<OffsetOfComponent> Components, 11812 SourceLocation RParenLoc) { 11813 QualType ArgTy = TInfo->getType(); 11814 bool Dependent = ArgTy->isDependentType(); 11815 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11816 11817 // We must have at least one component that refers to the type, and the first 11818 // one is known to be a field designator. Verify that the ArgTy represents 11819 // a struct/union/class. 11820 if (!Dependent && !ArgTy->isRecordType()) 11821 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11822 << ArgTy << TypeRange); 11823 11824 // Type must be complete per C99 7.17p3 because a declaring a variable 11825 // with an incomplete type would be ill-formed. 11826 if (!Dependent 11827 && RequireCompleteType(BuiltinLoc, ArgTy, 11828 diag::err_offsetof_incomplete_type, TypeRange)) 11829 return ExprError(); 11830 11831 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11832 // GCC extension, diagnose them. 11833 // FIXME: This diagnostic isn't actually visible because the location is in 11834 // a system header! 11835 if (Components.size() != 1) 11836 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11837 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11838 11839 bool DidWarnAboutNonPOD = false; 11840 QualType CurrentType = ArgTy; 11841 SmallVector<OffsetOfNode, 4> Comps; 11842 SmallVector<Expr*, 4> Exprs; 11843 for (const OffsetOfComponent &OC : Components) { 11844 if (OC.isBrackets) { 11845 // Offset of an array sub-field. TODO: Should we allow vector elements? 11846 if (!CurrentType->isDependentType()) { 11847 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11848 if(!AT) 11849 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11850 << CurrentType); 11851 CurrentType = AT->getElementType(); 11852 } else 11853 CurrentType = Context.DependentTy; 11854 11855 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11856 if (IdxRval.isInvalid()) 11857 return ExprError(); 11858 Expr *Idx = IdxRval.get(); 11859 11860 // The expression must be an integral expression. 11861 // FIXME: An integral constant expression? 11862 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11863 !Idx->getType()->isIntegerType()) 11864 return ExprError(Diag(Idx->getLocStart(), 11865 diag::err_typecheck_subscript_not_integer) 11866 << Idx->getSourceRange()); 11867 11868 // Record this array index. 11869 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11870 Exprs.push_back(Idx); 11871 continue; 11872 } 11873 11874 // Offset of a field. 11875 if (CurrentType->isDependentType()) { 11876 // We have the offset of a field, but we can't look into the dependent 11877 // type. Just record the identifier of the field. 11878 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11879 CurrentType = Context.DependentTy; 11880 continue; 11881 } 11882 11883 // We need to have a complete type to look into. 11884 if (RequireCompleteType(OC.LocStart, CurrentType, 11885 diag::err_offsetof_incomplete_type)) 11886 return ExprError(); 11887 11888 // Look for the designated field. 11889 const RecordType *RC = CurrentType->getAs<RecordType>(); 11890 if (!RC) 11891 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11892 << CurrentType); 11893 RecordDecl *RD = RC->getDecl(); 11894 11895 // C++ [lib.support.types]p5: 11896 // The macro offsetof accepts a restricted set of type arguments in this 11897 // International Standard. type shall be a POD structure or a POD union 11898 // (clause 9). 11899 // C++11 [support.types]p4: 11900 // If type is not a standard-layout class (Clause 9), the results are 11901 // undefined. 11902 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11903 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11904 unsigned DiagID = 11905 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11906 : diag::ext_offsetof_non_pod_type; 11907 11908 if (!IsSafe && !DidWarnAboutNonPOD && 11909 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11910 PDiag(DiagID) 11911 << SourceRange(Components[0].LocStart, OC.LocEnd) 11912 << CurrentType)) 11913 DidWarnAboutNonPOD = true; 11914 } 11915 11916 // Look for the field. 11917 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11918 LookupQualifiedName(R, RD); 11919 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11920 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11921 if (!MemberDecl) { 11922 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11923 MemberDecl = IndirectMemberDecl->getAnonField(); 11924 } 11925 11926 if (!MemberDecl) 11927 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11928 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11929 OC.LocEnd)); 11930 11931 // C99 7.17p3: 11932 // (If the specified member is a bit-field, the behavior is undefined.) 11933 // 11934 // We diagnose this as an error. 11935 if (MemberDecl->isBitField()) { 11936 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11937 << MemberDecl->getDeclName() 11938 << SourceRange(BuiltinLoc, RParenLoc); 11939 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11940 return ExprError(); 11941 } 11942 11943 RecordDecl *Parent = MemberDecl->getParent(); 11944 if (IndirectMemberDecl) 11945 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11946 11947 // If the member was found in a base class, introduce OffsetOfNodes for 11948 // the base class indirections. 11949 CXXBasePaths Paths; 11950 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11951 Paths)) { 11952 if (Paths.getDetectedVirtual()) { 11953 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11954 << MemberDecl->getDeclName() 11955 << SourceRange(BuiltinLoc, RParenLoc); 11956 return ExprError(); 11957 } 11958 11959 CXXBasePath &Path = Paths.front(); 11960 for (const CXXBasePathElement &B : Path) 11961 Comps.push_back(OffsetOfNode(B.Base)); 11962 } 11963 11964 if (IndirectMemberDecl) { 11965 for (auto *FI : IndirectMemberDecl->chain()) { 11966 assert(isa<FieldDecl>(FI)); 11967 Comps.push_back(OffsetOfNode(OC.LocStart, 11968 cast<FieldDecl>(FI), OC.LocEnd)); 11969 } 11970 } else 11971 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11972 11973 CurrentType = MemberDecl->getType().getNonReferenceType(); 11974 } 11975 11976 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11977 Comps, Exprs, RParenLoc); 11978 } 11979 11980 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11981 SourceLocation BuiltinLoc, 11982 SourceLocation TypeLoc, 11983 ParsedType ParsedArgTy, 11984 ArrayRef<OffsetOfComponent> Components, 11985 SourceLocation RParenLoc) { 11986 11987 TypeSourceInfo *ArgTInfo; 11988 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11989 if (ArgTy.isNull()) 11990 return ExprError(); 11991 11992 if (!ArgTInfo) 11993 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11994 11995 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11996 } 11997 11998 11999 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12000 Expr *CondExpr, 12001 Expr *LHSExpr, Expr *RHSExpr, 12002 SourceLocation RPLoc) { 12003 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12004 12005 ExprValueKind VK = VK_RValue; 12006 ExprObjectKind OK = OK_Ordinary; 12007 QualType resType; 12008 bool ValueDependent = false; 12009 bool CondIsTrue = false; 12010 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12011 resType = Context.DependentTy; 12012 ValueDependent = true; 12013 } else { 12014 // The conditional expression is required to be a constant expression. 12015 llvm::APSInt condEval(32); 12016 ExprResult CondICE 12017 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12018 diag::err_typecheck_choose_expr_requires_constant, false); 12019 if (CondICE.isInvalid()) 12020 return ExprError(); 12021 CondExpr = CondICE.get(); 12022 CondIsTrue = condEval.getZExtValue(); 12023 12024 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12025 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12026 12027 resType = ActiveExpr->getType(); 12028 ValueDependent = ActiveExpr->isValueDependent(); 12029 VK = ActiveExpr->getValueKind(); 12030 OK = ActiveExpr->getObjectKind(); 12031 } 12032 12033 return new (Context) 12034 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12035 CondIsTrue, resType->isDependentType(), ValueDependent); 12036 } 12037 12038 //===----------------------------------------------------------------------===// 12039 // Clang Extensions. 12040 //===----------------------------------------------------------------------===// 12041 12042 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12043 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12044 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12045 12046 if (LangOpts.CPlusPlus) { 12047 Decl *ManglingContextDecl; 12048 if (MangleNumberingContext *MCtx = 12049 getCurrentMangleNumberContext(Block->getDeclContext(), 12050 ManglingContextDecl)) { 12051 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12052 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12053 } 12054 } 12055 12056 PushBlockScope(CurScope, Block); 12057 CurContext->addDecl(Block); 12058 if (CurScope) 12059 PushDeclContext(CurScope, Block); 12060 else 12061 CurContext = Block; 12062 12063 getCurBlock()->HasImplicitReturnType = true; 12064 12065 // Enter a new evaluation context to insulate the block from any 12066 // cleanups from the enclosing full-expression. 12067 PushExpressionEvaluationContext(PotentiallyEvaluated); 12068 } 12069 12070 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12071 Scope *CurScope) { 12072 assert(ParamInfo.getIdentifier() == nullptr && 12073 "block-id should have no identifier!"); 12074 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12075 BlockScopeInfo *CurBlock = getCurBlock(); 12076 12077 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12078 QualType T = Sig->getType(); 12079 12080 // FIXME: We should allow unexpanded parameter packs here, but that would, 12081 // in turn, make the block expression contain unexpanded parameter packs. 12082 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12083 // Drop the parameters. 12084 FunctionProtoType::ExtProtoInfo EPI; 12085 EPI.HasTrailingReturn = false; 12086 EPI.TypeQuals |= DeclSpec::TQ_const; 12087 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12088 Sig = Context.getTrivialTypeSourceInfo(T); 12089 } 12090 12091 // GetTypeForDeclarator always produces a function type for a block 12092 // literal signature. Furthermore, it is always a FunctionProtoType 12093 // unless the function was written with a typedef. 12094 assert(T->isFunctionType() && 12095 "GetTypeForDeclarator made a non-function block signature"); 12096 12097 // Look for an explicit signature in that function type. 12098 FunctionProtoTypeLoc ExplicitSignature; 12099 12100 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12101 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12102 12103 // Check whether that explicit signature was synthesized by 12104 // GetTypeForDeclarator. If so, don't save that as part of the 12105 // written signature. 12106 if (ExplicitSignature.getLocalRangeBegin() == 12107 ExplicitSignature.getLocalRangeEnd()) { 12108 // This would be much cheaper if we stored TypeLocs instead of 12109 // TypeSourceInfos. 12110 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12111 unsigned Size = Result.getFullDataSize(); 12112 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12113 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12114 12115 ExplicitSignature = FunctionProtoTypeLoc(); 12116 } 12117 } 12118 12119 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12120 CurBlock->FunctionType = T; 12121 12122 const FunctionType *Fn = T->getAs<FunctionType>(); 12123 QualType RetTy = Fn->getReturnType(); 12124 bool isVariadic = 12125 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12126 12127 CurBlock->TheDecl->setIsVariadic(isVariadic); 12128 12129 // Context.DependentTy is used as a placeholder for a missing block 12130 // return type. TODO: what should we do with declarators like: 12131 // ^ * { ... } 12132 // If the answer is "apply template argument deduction".... 12133 if (RetTy != Context.DependentTy) { 12134 CurBlock->ReturnType = RetTy; 12135 CurBlock->TheDecl->setBlockMissingReturnType(false); 12136 CurBlock->HasImplicitReturnType = false; 12137 } 12138 12139 // Push block parameters from the declarator if we had them. 12140 SmallVector<ParmVarDecl*, 8> Params; 12141 if (ExplicitSignature) { 12142 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12143 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12144 if (Param->getIdentifier() == nullptr && 12145 !Param->isImplicit() && 12146 !Param->isInvalidDecl() && 12147 !getLangOpts().CPlusPlus) 12148 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12149 Params.push_back(Param); 12150 } 12151 12152 // Fake up parameter variables if we have a typedef, like 12153 // ^ fntype { ... } 12154 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12155 for (const auto &I : Fn->param_types()) { 12156 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12157 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12158 Params.push_back(Param); 12159 } 12160 } 12161 12162 // Set the parameters on the block decl. 12163 if (!Params.empty()) { 12164 CurBlock->TheDecl->setParams(Params); 12165 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12166 /*CheckParameterNames=*/false); 12167 } 12168 12169 // Finally we can process decl attributes. 12170 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12171 12172 // Put the parameter variables in scope. 12173 for (auto AI : CurBlock->TheDecl->parameters()) { 12174 AI->setOwningFunction(CurBlock->TheDecl); 12175 12176 // If this has an identifier, add it to the scope stack. 12177 if (AI->getIdentifier()) { 12178 CheckShadow(CurBlock->TheScope, AI); 12179 12180 PushOnScopeChains(AI, CurBlock->TheScope); 12181 } 12182 } 12183 } 12184 12185 /// ActOnBlockError - If there is an error parsing a block, this callback 12186 /// is invoked to pop the information about the block from the action impl. 12187 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12188 // Leave the expression-evaluation context. 12189 DiscardCleanupsInEvaluationContext(); 12190 PopExpressionEvaluationContext(); 12191 12192 // Pop off CurBlock, handle nested blocks. 12193 PopDeclContext(); 12194 PopFunctionScopeInfo(); 12195 } 12196 12197 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12198 /// literal was successfully completed. ^(int x){...} 12199 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12200 Stmt *Body, Scope *CurScope) { 12201 // If blocks are disabled, emit an error. 12202 if (!LangOpts.Blocks) 12203 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12204 12205 // Leave the expression-evaluation context. 12206 if (hasAnyUnrecoverableErrorsInThisFunction()) 12207 DiscardCleanupsInEvaluationContext(); 12208 assert(!Cleanup.exprNeedsCleanups() && 12209 "cleanups within block not correctly bound!"); 12210 PopExpressionEvaluationContext(); 12211 12212 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12213 12214 if (BSI->HasImplicitReturnType) 12215 deduceClosureReturnType(*BSI); 12216 12217 PopDeclContext(); 12218 12219 QualType RetTy = Context.VoidTy; 12220 if (!BSI->ReturnType.isNull()) 12221 RetTy = BSI->ReturnType; 12222 12223 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12224 QualType BlockTy; 12225 12226 // Set the captured variables on the block. 12227 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12228 SmallVector<BlockDecl::Capture, 4> Captures; 12229 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12230 if (Cap.isThisCapture()) 12231 continue; 12232 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12233 Cap.isNested(), Cap.getInitExpr()); 12234 Captures.push_back(NewCap); 12235 } 12236 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12237 12238 // If the user wrote a function type in some form, try to use that. 12239 if (!BSI->FunctionType.isNull()) { 12240 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12241 12242 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12243 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12244 12245 // Turn protoless block types into nullary block types. 12246 if (isa<FunctionNoProtoType>(FTy)) { 12247 FunctionProtoType::ExtProtoInfo EPI; 12248 EPI.ExtInfo = Ext; 12249 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12250 12251 // Otherwise, if we don't need to change anything about the function type, 12252 // preserve its sugar structure. 12253 } else if (FTy->getReturnType() == RetTy && 12254 (!NoReturn || FTy->getNoReturnAttr())) { 12255 BlockTy = BSI->FunctionType; 12256 12257 // Otherwise, make the minimal modifications to the function type. 12258 } else { 12259 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12260 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12261 EPI.TypeQuals = 0; // FIXME: silently? 12262 EPI.ExtInfo = Ext; 12263 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12264 } 12265 12266 // If we don't have a function type, just build one from nothing. 12267 } else { 12268 FunctionProtoType::ExtProtoInfo EPI; 12269 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12270 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12271 } 12272 12273 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12274 BlockTy = Context.getBlockPointerType(BlockTy); 12275 12276 // If needed, diagnose invalid gotos and switches in the block. 12277 if (getCurFunction()->NeedsScopeChecking() && 12278 !PP.isCodeCompletionEnabled()) 12279 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12280 12281 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12282 12283 // Try to apply the named return value optimization. We have to check again 12284 // if we can do this, though, because blocks keep return statements around 12285 // to deduce an implicit return type. 12286 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12287 !BSI->TheDecl->isDependentContext()) 12288 computeNRVO(Body, BSI); 12289 12290 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12291 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12292 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12293 12294 // If the block isn't obviously global, i.e. it captures anything at 12295 // all, then we need to do a few things in the surrounding context: 12296 if (Result->getBlockDecl()->hasCaptures()) { 12297 // First, this expression has a new cleanup object. 12298 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12299 Cleanup.setExprNeedsCleanups(true); 12300 12301 // It also gets a branch-protected scope if any of the captured 12302 // variables needs destruction. 12303 for (const auto &CI : Result->getBlockDecl()->captures()) { 12304 const VarDecl *var = CI.getVariable(); 12305 if (var->getType().isDestructedType() != QualType::DK_none) { 12306 getCurFunction()->setHasBranchProtectedScope(); 12307 break; 12308 } 12309 } 12310 } 12311 12312 return Result; 12313 } 12314 12315 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12316 SourceLocation RPLoc) { 12317 TypeSourceInfo *TInfo; 12318 GetTypeFromParser(Ty, &TInfo); 12319 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12320 } 12321 12322 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12323 Expr *E, TypeSourceInfo *TInfo, 12324 SourceLocation RPLoc) { 12325 Expr *OrigExpr = E; 12326 bool IsMS = false; 12327 12328 // CUDA device code does not support varargs. 12329 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12330 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12331 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12332 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12333 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12334 } 12335 } 12336 12337 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12338 // as Microsoft ABI on an actual Microsoft platform, where 12339 // __builtin_ms_va_list and __builtin_va_list are the same.) 12340 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12341 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12342 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12343 if (Context.hasSameType(MSVaListType, E->getType())) { 12344 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12345 return ExprError(); 12346 IsMS = true; 12347 } 12348 } 12349 12350 // Get the va_list type 12351 QualType VaListType = Context.getBuiltinVaListType(); 12352 if (!IsMS) { 12353 if (VaListType->isArrayType()) { 12354 // Deal with implicit array decay; for example, on x86-64, 12355 // va_list is an array, but it's supposed to decay to 12356 // a pointer for va_arg. 12357 VaListType = Context.getArrayDecayedType(VaListType); 12358 // Make sure the input expression also decays appropriately. 12359 ExprResult Result = UsualUnaryConversions(E); 12360 if (Result.isInvalid()) 12361 return ExprError(); 12362 E = Result.get(); 12363 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12364 // If va_list is a record type and we are compiling in C++ mode, 12365 // check the argument using reference binding. 12366 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12367 Context, Context.getLValueReferenceType(VaListType), false); 12368 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12369 if (Init.isInvalid()) 12370 return ExprError(); 12371 E = Init.getAs<Expr>(); 12372 } else { 12373 // Otherwise, the va_list argument must be an l-value because 12374 // it is modified by va_arg. 12375 if (!E->isTypeDependent() && 12376 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12377 return ExprError(); 12378 } 12379 } 12380 12381 if (!IsMS && !E->isTypeDependent() && 12382 !Context.hasSameType(VaListType, E->getType())) 12383 return ExprError(Diag(E->getLocStart(), 12384 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12385 << OrigExpr->getType() << E->getSourceRange()); 12386 12387 if (!TInfo->getType()->isDependentType()) { 12388 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12389 diag::err_second_parameter_to_va_arg_incomplete, 12390 TInfo->getTypeLoc())) 12391 return ExprError(); 12392 12393 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12394 TInfo->getType(), 12395 diag::err_second_parameter_to_va_arg_abstract, 12396 TInfo->getTypeLoc())) 12397 return ExprError(); 12398 12399 if (!TInfo->getType().isPODType(Context)) { 12400 Diag(TInfo->getTypeLoc().getBeginLoc(), 12401 TInfo->getType()->isObjCLifetimeType() 12402 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12403 : diag::warn_second_parameter_to_va_arg_not_pod) 12404 << TInfo->getType() 12405 << TInfo->getTypeLoc().getSourceRange(); 12406 } 12407 12408 // Check for va_arg where arguments of the given type will be promoted 12409 // (i.e. this va_arg is guaranteed to have undefined behavior). 12410 QualType PromoteType; 12411 if (TInfo->getType()->isPromotableIntegerType()) { 12412 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12413 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12414 PromoteType = QualType(); 12415 } 12416 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12417 PromoteType = Context.DoubleTy; 12418 if (!PromoteType.isNull()) 12419 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12420 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12421 << TInfo->getType() 12422 << PromoteType 12423 << TInfo->getTypeLoc().getSourceRange()); 12424 } 12425 12426 QualType T = TInfo->getType().getNonLValueExprType(Context); 12427 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12428 } 12429 12430 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12431 // The type of __null will be int or long, depending on the size of 12432 // pointers on the target. 12433 QualType Ty; 12434 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12435 if (pw == Context.getTargetInfo().getIntWidth()) 12436 Ty = Context.IntTy; 12437 else if (pw == Context.getTargetInfo().getLongWidth()) 12438 Ty = Context.LongTy; 12439 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12440 Ty = Context.LongLongTy; 12441 else { 12442 llvm_unreachable("I don't know size of pointer!"); 12443 } 12444 12445 return new (Context) GNUNullExpr(Ty, TokenLoc); 12446 } 12447 12448 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12449 bool Diagnose) { 12450 if (!getLangOpts().ObjC1) 12451 return false; 12452 12453 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12454 if (!PT) 12455 return false; 12456 12457 if (!PT->isObjCIdType()) { 12458 // Check if the destination is the 'NSString' interface. 12459 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12460 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12461 return false; 12462 } 12463 12464 // Ignore any parens, implicit casts (should only be 12465 // array-to-pointer decays), and not-so-opaque values. The last is 12466 // important for making this trigger for property assignments. 12467 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12468 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12469 if (OV->getSourceExpr()) 12470 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12471 12472 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12473 if (!SL || !SL->isAscii()) 12474 return false; 12475 if (Diagnose) { 12476 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12477 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12478 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12479 } 12480 return true; 12481 } 12482 12483 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12484 const Expr *SrcExpr) { 12485 if (!DstType->isFunctionPointerType() || 12486 !SrcExpr->getType()->isFunctionType()) 12487 return false; 12488 12489 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12490 if (!DRE) 12491 return false; 12492 12493 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12494 if (!FD) 12495 return false; 12496 12497 return !S.checkAddressOfFunctionIsAvailable(FD, 12498 /*Complain=*/true, 12499 SrcExpr->getLocStart()); 12500 } 12501 12502 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12503 SourceLocation Loc, 12504 QualType DstType, QualType SrcType, 12505 Expr *SrcExpr, AssignmentAction Action, 12506 bool *Complained) { 12507 if (Complained) 12508 *Complained = false; 12509 12510 // Decode the result (notice that AST's are still created for extensions). 12511 bool CheckInferredResultType = false; 12512 bool isInvalid = false; 12513 unsigned DiagKind = 0; 12514 FixItHint Hint; 12515 ConversionFixItGenerator ConvHints; 12516 bool MayHaveConvFixit = false; 12517 bool MayHaveFunctionDiff = false; 12518 const ObjCInterfaceDecl *IFace = nullptr; 12519 const ObjCProtocolDecl *PDecl = nullptr; 12520 12521 switch (ConvTy) { 12522 case Compatible: 12523 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12524 return false; 12525 12526 case PointerToInt: 12527 DiagKind = diag::ext_typecheck_convert_pointer_int; 12528 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12529 MayHaveConvFixit = true; 12530 break; 12531 case IntToPointer: 12532 DiagKind = diag::ext_typecheck_convert_int_pointer; 12533 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12534 MayHaveConvFixit = true; 12535 break; 12536 case IncompatiblePointer: 12537 if (Action == AA_Passing_CFAudited) 12538 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12539 else if (SrcType->isFunctionPointerType() && 12540 DstType->isFunctionPointerType()) 12541 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12542 else 12543 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12544 12545 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12546 SrcType->isObjCObjectPointerType(); 12547 if (Hint.isNull() && !CheckInferredResultType) { 12548 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12549 } 12550 else if (CheckInferredResultType) { 12551 SrcType = SrcType.getUnqualifiedType(); 12552 DstType = DstType.getUnqualifiedType(); 12553 } 12554 MayHaveConvFixit = true; 12555 break; 12556 case IncompatiblePointerSign: 12557 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12558 break; 12559 case FunctionVoidPointer: 12560 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12561 break; 12562 case IncompatiblePointerDiscardsQualifiers: { 12563 // Perform array-to-pointer decay if necessary. 12564 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12565 12566 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12567 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12568 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12569 DiagKind = diag::err_typecheck_incompatible_address_space; 12570 break; 12571 12572 12573 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12574 DiagKind = diag::err_typecheck_incompatible_ownership; 12575 break; 12576 } 12577 12578 llvm_unreachable("unknown error case for discarding qualifiers!"); 12579 // fallthrough 12580 } 12581 case CompatiblePointerDiscardsQualifiers: 12582 // If the qualifiers lost were because we were applying the 12583 // (deprecated) C++ conversion from a string literal to a char* 12584 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12585 // Ideally, this check would be performed in 12586 // checkPointerTypesForAssignment. However, that would require a 12587 // bit of refactoring (so that the second argument is an 12588 // expression, rather than a type), which should be done as part 12589 // of a larger effort to fix checkPointerTypesForAssignment for 12590 // C++ semantics. 12591 if (getLangOpts().CPlusPlus && 12592 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12593 return false; 12594 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12595 break; 12596 case IncompatibleNestedPointerQualifiers: 12597 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12598 break; 12599 case IntToBlockPointer: 12600 DiagKind = diag::err_int_to_block_pointer; 12601 break; 12602 case IncompatibleBlockPointer: 12603 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12604 break; 12605 case IncompatibleObjCQualifiedId: { 12606 if (SrcType->isObjCQualifiedIdType()) { 12607 const ObjCObjectPointerType *srcOPT = 12608 SrcType->getAs<ObjCObjectPointerType>(); 12609 for (auto *srcProto : srcOPT->quals()) { 12610 PDecl = srcProto; 12611 break; 12612 } 12613 if (const ObjCInterfaceType *IFaceT = 12614 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12615 IFace = IFaceT->getDecl(); 12616 } 12617 else if (DstType->isObjCQualifiedIdType()) { 12618 const ObjCObjectPointerType *dstOPT = 12619 DstType->getAs<ObjCObjectPointerType>(); 12620 for (auto *dstProto : dstOPT->quals()) { 12621 PDecl = dstProto; 12622 break; 12623 } 12624 if (const ObjCInterfaceType *IFaceT = 12625 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12626 IFace = IFaceT->getDecl(); 12627 } 12628 DiagKind = diag::warn_incompatible_qualified_id; 12629 break; 12630 } 12631 case IncompatibleVectors: 12632 DiagKind = diag::warn_incompatible_vectors; 12633 break; 12634 case IncompatibleObjCWeakRef: 12635 DiagKind = diag::err_arc_weak_unavailable_assign; 12636 break; 12637 case Incompatible: 12638 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12639 if (Complained) 12640 *Complained = true; 12641 return true; 12642 } 12643 12644 DiagKind = diag::err_typecheck_convert_incompatible; 12645 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12646 MayHaveConvFixit = true; 12647 isInvalid = true; 12648 MayHaveFunctionDiff = true; 12649 break; 12650 } 12651 12652 QualType FirstType, SecondType; 12653 switch (Action) { 12654 case AA_Assigning: 12655 case AA_Initializing: 12656 // The destination type comes first. 12657 FirstType = DstType; 12658 SecondType = SrcType; 12659 break; 12660 12661 case AA_Returning: 12662 case AA_Passing: 12663 case AA_Passing_CFAudited: 12664 case AA_Converting: 12665 case AA_Sending: 12666 case AA_Casting: 12667 // The source type comes first. 12668 FirstType = SrcType; 12669 SecondType = DstType; 12670 break; 12671 } 12672 12673 PartialDiagnostic FDiag = PDiag(DiagKind); 12674 if (Action == AA_Passing_CFAudited) 12675 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12676 else 12677 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12678 12679 // If we can fix the conversion, suggest the FixIts. 12680 assert(ConvHints.isNull() || Hint.isNull()); 12681 if (!ConvHints.isNull()) { 12682 for (FixItHint &H : ConvHints.Hints) 12683 FDiag << H; 12684 } else { 12685 FDiag << Hint; 12686 } 12687 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12688 12689 if (MayHaveFunctionDiff) 12690 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12691 12692 Diag(Loc, FDiag); 12693 if (DiagKind == diag::warn_incompatible_qualified_id && 12694 PDecl && IFace && !IFace->hasDefinition()) 12695 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12696 << IFace->getName() << PDecl->getName(); 12697 12698 if (SecondType == Context.OverloadTy) 12699 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12700 FirstType, /*TakingAddress=*/true); 12701 12702 if (CheckInferredResultType) 12703 EmitRelatedResultTypeNote(SrcExpr); 12704 12705 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12706 EmitRelatedResultTypeNoteForReturn(DstType); 12707 12708 if (Complained) 12709 *Complained = true; 12710 return isInvalid; 12711 } 12712 12713 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12714 llvm::APSInt *Result) { 12715 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12716 public: 12717 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12718 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12719 } 12720 } Diagnoser; 12721 12722 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12723 } 12724 12725 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12726 llvm::APSInt *Result, 12727 unsigned DiagID, 12728 bool AllowFold) { 12729 class IDDiagnoser : public VerifyICEDiagnoser { 12730 unsigned DiagID; 12731 12732 public: 12733 IDDiagnoser(unsigned DiagID) 12734 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12735 12736 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12737 S.Diag(Loc, DiagID) << SR; 12738 } 12739 } Diagnoser(DiagID); 12740 12741 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12742 } 12743 12744 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12745 SourceRange SR) { 12746 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12747 } 12748 12749 ExprResult 12750 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12751 VerifyICEDiagnoser &Diagnoser, 12752 bool AllowFold) { 12753 SourceLocation DiagLoc = E->getLocStart(); 12754 12755 if (getLangOpts().CPlusPlus11) { 12756 // C++11 [expr.const]p5: 12757 // If an expression of literal class type is used in a context where an 12758 // integral constant expression is required, then that class type shall 12759 // have a single non-explicit conversion function to an integral or 12760 // unscoped enumeration type 12761 ExprResult Converted; 12762 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12763 public: 12764 CXX11ConvertDiagnoser(bool Silent) 12765 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12766 Silent, true) {} 12767 12768 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12769 QualType T) override { 12770 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12771 } 12772 12773 SemaDiagnosticBuilder diagnoseIncomplete( 12774 Sema &S, SourceLocation Loc, QualType T) override { 12775 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12776 } 12777 12778 SemaDiagnosticBuilder diagnoseExplicitConv( 12779 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12780 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12781 } 12782 12783 SemaDiagnosticBuilder noteExplicitConv( 12784 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12785 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12786 << ConvTy->isEnumeralType() << ConvTy; 12787 } 12788 12789 SemaDiagnosticBuilder diagnoseAmbiguous( 12790 Sema &S, SourceLocation Loc, QualType T) override { 12791 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12792 } 12793 12794 SemaDiagnosticBuilder noteAmbiguous( 12795 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12796 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12797 << ConvTy->isEnumeralType() << ConvTy; 12798 } 12799 12800 SemaDiagnosticBuilder diagnoseConversion( 12801 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12802 llvm_unreachable("conversion functions are permitted"); 12803 } 12804 } ConvertDiagnoser(Diagnoser.Suppress); 12805 12806 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12807 ConvertDiagnoser); 12808 if (Converted.isInvalid()) 12809 return Converted; 12810 E = Converted.get(); 12811 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12812 return ExprError(); 12813 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12814 // An ICE must be of integral or unscoped enumeration type. 12815 if (!Diagnoser.Suppress) 12816 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12817 return ExprError(); 12818 } 12819 12820 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12821 // in the non-ICE case. 12822 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12823 if (Result) 12824 *Result = E->EvaluateKnownConstInt(Context); 12825 return E; 12826 } 12827 12828 Expr::EvalResult EvalResult; 12829 SmallVector<PartialDiagnosticAt, 8> Notes; 12830 EvalResult.Diag = &Notes; 12831 12832 // Try to evaluate the expression, and produce diagnostics explaining why it's 12833 // not a constant expression as a side-effect. 12834 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12835 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12836 12837 // In C++11, we can rely on diagnostics being produced for any expression 12838 // which is not a constant expression. If no diagnostics were produced, then 12839 // this is a constant expression. 12840 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12841 if (Result) 12842 *Result = EvalResult.Val.getInt(); 12843 return E; 12844 } 12845 12846 // If our only note is the usual "invalid subexpression" note, just point 12847 // the caret at its location rather than producing an essentially 12848 // redundant note. 12849 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12850 diag::note_invalid_subexpr_in_const_expr) { 12851 DiagLoc = Notes[0].first; 12852 Notes.clear(); 12853 } 12854 12855 if (!Folded || !AllowFold) { 12856 if (!Diagnoser.Suppress) { 12857 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12858 for (const PartialDiagnosticAt &Note : Notes) 12859 Diag(Note.first, Note.second); 12860 } 12861 12862 return ExprError(); 12863 } 12864 12865 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12866 for (const PartialDiagnosticAt &Note : Notes) 12867 Diag(Note.first, Note.second); 12868 12869 if (Result) 12870 *Result = EvalResult.Val.getInt(); 12871 return E; 12872 } 12873 12874 namespace { 12875 // Handle the case where we conclude a expression which we speculatively 12876 // considered to be unevaluated is actually evaluated. 12877 class TransformToPE : public TreeTransform<TransformToPE> { 12878 typedef TreeTransform<TransformToPE> BaseTransform; 12879 12880 public: 12881 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12882 12883 // Make sure we redo semantic analysis 12884 bool AlwaysRebuild() { return true; } 12885 12886 // Make sure we handle LabelStmts correctly. 12887 // FIXME: This does the right thing, but maybe we need a more general 12888 // fix to TreeTransform? 12889 StmtResult TransformLabelStmt(LabelStmt *S) { 12890 S->getDecl()->setStmt(nullptr); 12891 return BaseTransform::TransformLabelStmt(S); 12892 } 12893 12894 // We need to special-case DeclRefExprs referring to FieldDecls which 12895 // are not part of a member pointer formation; normal TreeTransforming 12896 // doesn't catch this case because of the way we represent them in the AST. 12897 // FIXME: This is a bit ugly; is it really the best way to handle this 12898 // case? 12899 // 12900 // Error on DeclRefExprs referring to FieldDecls. 12901 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12902 if (isa<FieldDecl>(E->getDecl()) && 12903 !SemaRef.isUnevaluatedContext()) 12904 return SemaRef.Diag(E->getLocation(), 12905 diag::err_invalid_non_static_member_use) 12906 << E->getDecl() << E->getSourceRange(); 12907 12908 return BaseTransform::TransformDeclRefExpr(E); 12909 } 12910 12911 // Exception: filter out member pointer formation 12912 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12913 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12914 return E; 12915 12916 return BaseTransform::TransformUnaryOperator(E); 12917 } 12918 12919 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12920 // Lambdas never need to be transformed. 12921 return E; 12922 } 12923 }; 12924 } 12925 12926 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12927 assert(isUnevaluatedContext() && 12928 "Should only transform unevaluated expressions"); 12929 ExprEvalContexts.back().Context = 12930 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12931 if (isUnevaluatedContext()) 12932 return E; 12933 return TransformToPE(*this).TransformExpr(E); 12934 } 12935 12936 void 12937 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12938 Decl *LambdaContextDecl, 12939 bool IsDecltype) { 12940 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12941 LambdaContextDecl, IsDecltype); 12942 Cleanup.reset(); 12943 if (!MaybeODRUseExprs.empty()) 12944 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12945 } 12946 12947 void 12948 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12949 ReuseLambdaContextDecl_t, 12950 bool IsDecltype) { 12951 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12952 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12953 } 12954 12955 void Sema::PopExpressionEvaluationContext() { 12956 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12957 unsigned NumTypos = Rec.NumTypos; 12958 12959 if (!Rec.Lambdas.empty()) { 12960 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12961 unsigned D; 12962 if (Rec.isUnevaluated()) { 12963 // C++11 [expr.prim.lambda]p2: 12964 // A lambda-expression shall not appear in an unevaluated operand 12965 // (Clause 5). 12966 D = diag::err_lambda_unevaluated_operand; 12967 } else { 12968 // C++1y [expr.const]p2: 12969 // A conditional-expression e is a core constant expression unless the 12970 // evaluation of e, following the rules of the abstract machine, would 12971 // evaluate [...] a lambda-expression. 12972 D = diag::err_lambda_in_constant_expression; 12973 } 12974 for (const auto *L : Rec.Lambdas) 12975 Diag(L->getLocStart(), D); 12976 } else { 12977 // Mark the capture expressions odr-used. This was deferred 12978 // during lambda expression creation. 12979 for (auto *Lambda : Rec.Lambdas) { 12980 for (auto *C : Lambda->capture_inits()) 12981 MarkDeclarationsReferencedInExpr(C); 12982 } 12983 } 12984 } 12985 12986 // When are coming out of an unevaluated context, clear out any 12987 // temporaries that we may have created as part of the evaluation of 12988 // the expression in that context: they aren't relevant because they 12989 // will never be constructed. 12990 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12991 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12992 ExprCleanupObjects.end()); 12993 Cleanup = Rec.ParentCleanup; 12994 CleanupVarDeclMarking(); 12995 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12996 // Otherwise, merge the contexts together. 12997 } else { 12998 Cleanup.mergeFrom(Rec.ParentCleanup); 12999 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13000 Rec.SavedMaybeODRUseExprs.end()); 13001 } 13002 13003 // Pop the current expression evaluation context off the stack. 13004 ExprEvalContexts.pop_back(); 13005 13006 if (!ExprEvalContexts.empty()) 13007 ExprEvalContexts.back().NumTypos += NumTypos; 13008 else 13009 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13010 "last ExpressionEvaluationContextRecord"); 13011 } 13012 13013 void Sema::DiscardCleanupsInEvaluationContext() { 13014 ExprCleanupObjects.erase( 13015 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13016 ExprCleanupObjects.end()); 13017 Cleanup.reset(); 13018 MaybeODRUseExprs.clear(); 13019 } 13020 13021 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13022 if (!E->getType()->isVariablyModifiedType()) 13023 return E; 13024 return TransformToPotentiallyEvaluated(E); 13025 } 13026 13027 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13028 // Do not mark anything as "used" within a dependent context; wait for 13029 // an instantiation. 13030 if (SemaRef.CurContext->isDependentContext()) 13031 return false; 13032 13033 switch (SemaRef.ExprEvalContexts.back().Context) { 13034 case Sema::Unevaluated: 13035 case Sema::UnevaluatedAbstract: 13036 // We are in an expression that is not potentially evaluated; do nothing. 13037 // (Depending on how you read the standard, we actually do need to do 13038 // something here for null pointer constants, but the standard's 13039 // definition of a null pointer constant is completely crazy.) 13040 return false; 13041 13042 case Sema::DiscardedStatement: 13043 // These are technically a potentially evaluated but they have the effect 13044 // of suppressing use marking. 13045 return false; 13046 13047 case Sema::ConstantEvaluated: 13048 case Sema::PotentiallyEvaluated: 13049 // We are in a potentially evaluated expression (or a constant-expression 13050 // in C++03); we need to do implicit template instantiation, implicitly 13051 // define class members, and mark most declarations as used. 13052 return true; 13053 13054 case Sema::PotentiallyEvaluatedIfUsed: 13055 // Referenced declarations will only be used if the construct in the 13056 // containing expression is used. 13057 return false; 13058 } 13059 llvm_unreachable("Invalid context"); 13060 } 13061 13062 /// \brief Mark a function referenced, and check whether it is odr-used 13063 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13064 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13065 bool MightBeOdrUse) { 13066 assert(Func && "No function?"); 13067 13068 Func->setReferenced(); 13069 13070 // C++11 [basic.def.odr]p3: 13071 // A function whose name appears as a potentially-evaluated expression is 13072 // odr-used if it is the unique lookup result or the selected member of a 13073 // set of overloaded functions [...]. 13074 // 13075 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13076 // can just check that here. 13077 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13078 13079 // Determine whether we require a function definition to exist, per 13080 // C++11 [temp.inst]p3: 13081 // Unless a function template specialization has been explicitly 13082 // instantiated or explicitly specialized, the function template 13083 // specialization is implicitly instantiated when the specialization is 13084 // referenced in a context that requires a function definition to exist. 13085 // 13086 // We consider constexpr function templates to be referenced in a context 13087 // that requires a definition to exist whenever they are referenced. 13088 // 13089 // FIXME: This instantiates constexpr functions too frequently. If this is 13090 // really an unevaluated context (and we're not just in the definition of a 13091 // function template or overload resolution or other cases which we 13092 // incorrectly consider to be unevaluated contexts), and we're not in a 13093 // subexpression which we actually need to evaluate (for instance, a 13094 // template argument, array bound or an expression in a braced-init-list), 13095 // we are not permitted to instantiate this constexpr function definition. 13096 // 13097 // FIXME: This also implicitly defines special members too frequently. They 13098 // are only supposed to be implicitly defined if they are odr-used, but they 13099 // are not odr-used from constant expressions in unevaluated contexts. 13100 // However, they cannot be referenced if they are deleted, and they are 13101 // deleted whenever the implicit definition of the special member would 13102 // fail (with very few exceptions). 13103 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13104 bool NeedDefinition = 13105 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13106 (MD && !MD->isUserProvided()))); 13107 13108 // C++14 [temp.expl.spec]p6: 13109 // If a template [...] is explicitly specialized then that specialization 13110 // shall be declared before the first use of that specialization that would 13111 // cause an implicit instantiation to take place, in every translation unit 13112 // in which such a use occurs 13113 if (NeedDefinition && 13114 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13115 Func->getMemberSpecializationInfo())) 13116 checkSpecializationVisibility(Loc, Func); 13117 13118 // If we don't need to mark the function as used, and we don't need to 13119 // try to provide a definition, there's nothing more to do. 13120 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13121 (!NeedDefinition || Func->getBody())) 13122 return; 13123 13124 // Note that this declaration has been used. 13125 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13126 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13127 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13128 if (Constructor->isDefaultConstructor()) { 13129 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13130 return; 13131 DefineImplicitDefaultConstructor(Loc, Constructor); 13132 } else if (Constructor->isCopyConstructor()) { 13133 DefineImplicitCopyConstructor(Loc, Constructor); 13134 } else if (Constructor->isMoveConstructor()) { 13135 DefineImplicitMoveConstructor(Loc, Constructor); 13136 } 13137 } else if (Constructor->getInheritedConstructor()) { 13138 DefineInheritingConstructor(Loc, Constructor); 13139 } 13140 } else if (CXXDestructorDecl *Destructor = 13141 dyn_cast<CXXDestructorDecl>(Func)) { 13142 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13143 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13144 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13145 return; 13146 DefineImplicitDestructor(Loc, Destructor); 13147 } 13148 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13149 MarkVTableUsed(Loc, Destructor->getParent()); 13150 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13151 if (MethodDecl->isOverloadedOperator() && 13152 MethodDecl->getOverloadedOperator() == OO_Equal) { 13153 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13154 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13155 if (MethodDecl->isCopyAssignmentOperator()) 13156 DefineImplicitCopyAssignment(Loc, MethodDecl); 13157 else if (MethodDecl->isMoveAssignmentOperator()) 13158 DefineImplicitMoveAssignment(Loc, MethodDecl); 13159 } 13160 } else if (isa<CXXConversionDecl>(MethodDecl) && 13161 MethodDecl->getParent()->isLambda()) { 13162 CXXConversionDecl *Conversion = 13163 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13164 if (Conversion->isLambdaToBlockPointerConversion()) 13165 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13166 else 13167 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13168 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13169 MarkVTableUsed(Loc, MethodDecl->getParent()); 13170 } 13171 13172 // Recursive functions should be marked when used from another function. 13173 // FIXME: Is this really right? 13174 if (CurContext == Func) return; 13175 13176 // Resolve the exception specification for any function which is 13177 // used: CodeGen will need it. 13178 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13179 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13180 ResolveExceptionSpec(Loc, FPT); 13181 13182 // Implicit instantiation of function templates and member functions of 13183 // class templates. 13184 if (Func->isImplicitlyInstantiable()) { 13185 bool AlreadyInstantiated = false; 13186 SourceLocation PointOfInstantiation = Loc; 13187 if (FunctionTemplateSpecializationInfo *SpecInfo 13188 = Func->getTemplateSpecializationInfo()) { 13189 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13190 SpecInfo->setPointOfInstantiation(Loc); 13191 else if (SpecInfo->getTemplateSpecializationKind() 13192 == TSK_ImplicitInstantiation) { 13193 AlreadyInstantiated = true; 13194 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13195 } 13196 } else if (MemberSpecializationInfo *MSInfo 13197 = Func->getMemberSpecializationInfo()) { 13198 if (MSInfo->getPointOfInstantiation().isInvalid()) 13199 MSInfo->setPointOfInstantiation(Loc); 13200 else if (MSInfo->getTemplateSpecializationKind() 13201 == TSK_ImplicitInstantiation) { 13202 AlreadyInstantiated = true; 13203 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13204 } 13205 } 13206 13207 if (!AlreadyInstantiated || Func->isConstexpr()) { 13208 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13209 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13210 ActiveTemplateInstantiations.size()) 13211 PendingLocalImplicitInstantiations.push_back( 13212 std::make_pair(Func, PointOfInstantiation)); 13213 else if (Func->isConstexpr()) 13214 // Do not defer instantiations of constexpr functions, to avoid the 13215 // expression evaluator needing to call back into Sema if it sees a 13216 // call to such a function. 13217 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13218 else { 13219 PendingInstantiations.push_back(std::make_pair(Func, 13220 PointOfInstantiation)); 13221 // Notify the consumer that a function was implicitly instantiated. 13222 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13223 } 13224 } 13225 } else { 13226 // Walk redefinitions, as some of them may be instantiable. 13227 for (auto i : Func->redecls()) { 13228 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13229 MarkFunctionReferenced(Loc, i, OdrUse); 13230 } 13231 } 13232 13233 if (!OdrUse) return; 13234 13235 // Keep track of used but undefined functions. 13236 if (!Func->isDefined()) { 13237 if (mightHaveNonExternalLinkage(Func)) 13238 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13239 else if (Func->getMostRecentDecl()->isInlined() && 13240 !LangOpts.GNUInline && 13241 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13242 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13243 } 13244 13245 Func->markUsed(Context); 13246 } 13247 13248 static void 13249 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13250 ValueDecl *var, DeclContext *DC) { 13251 DeclContext *VarDC = var->getDeclContext(); 13252 13253 // If the parameter still belongs to the translation unit, then 13254 // we're actually just using one parameter in the declaration of 13255 // the next. 13256 if (isa<ParmVarDecl>(var) && 13257 isa<TranslationUnitDecl>(VarDC)) 13258 return; 13259 13260 // For C code, don't diagnose about capture if we're not actually in code 13261 // right now; it's impossible to write a non-constant expression outside of 13262 // function context, so we'll get other (more useful) diagnostics later. 13263 // 13264 // For C++, things get a bit more nasty... it would be nice to suppress this 13265 // diagnostic for certain cases like using a local variable in an array bound 13266 // for a member of a local class, but the correct predicate is not obvious. 13267 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13268 return; 13269 13270 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13271 unsigned ContextKind = 3; // unknown 13272 if (isa<CXXMethodDecl>(VarDC) && 13273 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13274 ContextKind = 2; 13275 } else if (isa<FunctionDecl>(VarDC)) { 13276 ContextKind = 0; 13277 } else if (isa<BlockDecl>(VarDC)) { 13278 ContextKind = 1; 13279 } 13280 13281 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13282 << var << ValueKind << ContextKind << VarDC; 13283 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13284 << var; 13285 13286 // FIXME: Add additional diagnostic info about class etc. which prevents 13287 // capture. 13288 } 13289 13290 13291 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13292 bool &SubCapturesAreNested, 13293 QualType &CaptureType, 13294 QualType &DeclRefType) { 13295 // Check whether we've already captured it. 13296 if (CSI->CaptureMap.count(Var)) { 13297 // If we found a capture, any subcaptures are nested. 13298 SubCapturesAreNested = true; 13299 13300 // Retrieve the capture type for this variable. 13301 CaptureType = CSI->getCapture(Var).getCaptureType(); 13302 13303 // Compute the type of an expression that refers to this variable. 13304 DeclRefType = CaptureType.getNonReferenceType(); 13305 13306 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13307 // are mutable in the sense that user can change their value - they are 13308 // private instances of the captured declarations. 13309 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13310 if (Cap.isCopyCapture() && 13311 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13312 !(isa<CapturedRegionScopeInfo>(CSI) && 13313 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13314 DeclRefType.addConst(); 13315 return true; 13316 } 13317 return false; 13318 } 13319 13320 // Only block literals, captured statements, and lambda expressions can 13321 // capture; other scopes don't work. 13322 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13323 SourceLocation Loc, 13324 const bool Diagnose, Sema &S) { 13325 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13326 return getLambdaAwareParentOfDeclContext(DC); 13327 else if (Var->hasLocalStorage()) { 13328 if (Diagnose) 13329 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13330 } 13331 return nullptr; 13332 } 13333 13334 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13335 // certain types of variables (unnamed, variably modified types etc.) 13336 // so check for eligibility. 13337 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13338 SourceLocation Loc, 13339 const bool Diagnose, Sema &S) { 13340 13341 bool IsBlock = isa<BlockScopeInfo>(CSI); 13342 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13343 13344 // Lambdas are not allowed to capture unnamed variables 13345 // (e.g. anonymous unions). 13346 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13347 // assuming that's the intent. 13348 if (IsLambda && !Var->getDeclName()) { 13349 if (Diagnose) { 13350 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13351 S.Diag(Var->getLocation(), diag::note_declared_at); 13352 } 13353 return false; 13354 } 13355 13356 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13357 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13358 if (Diagnose) { 13359 S.Diag(Loc, diag::err_ref_vm_type); 13360 S.Diag(Var->getLocation(), diag::note_previous_decl) 13361 << Var->getDeclName(); 13362 } 13363 return false; 13364 } 13365 // Prohibit structs with flexible array members too. 13366 // We cannot capture what is in the tail end of the struct. 13367 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13368 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13369 if (Diagnose) { 13370 if (IsBlock) 13371 S.Diag(Loc, diag::err_ref_flexarray_type); 13372 else 13373 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13374 << Var->getDeclName(); 13375 S.Diag(Var->getLocation(), diag::note_previous_decl) 13376 << Var->getDeclName(); 13377 } 13378 return false; 13379 } 13380 } 13381 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13382 // Lambdas and captured statements are not allowed to capture __block 13383 // variables; they don't support the expected semantics. 13384 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13385 if (Diagnose) { 13386 S.Diag(Loc, diag::err_capture_block_variable) 13387 << Var->getDeclName() << !IsLambda; 13388 S.Diag(Var->getLocation(), diag::note_previous_decl) 13389 << Var->getDeclName(); 13390 } 13391 return false; 13392 } 13393 13394 return true; 13395 } 13396 13397 // Returns true if the capture by block was successful. 13398 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13399 SourceLocation Loc, 13400 const bool BuildAndDiagnose, 13401 QualType &CaptureType, 13402 QualType &DeclRefType, 13403 const bool Nested, 13404 Sema &S) { 13405 Expr *CopyExpr = nullptr; 13406 bool ByRef = false; 13407 13408 // Blocks are not allowed to capture arrays. 13409 if (CaptureType->isArrayType()) { 13410 if (BuildAndDiagnose) { 13411 S.Diag(Loc, diag::err_ref_array_type); 13412 S.Diag(Var->getLocation(), diag::note_previous_decl) 13413 << Var->getDeclName(); 13414 } 13415 return false; 13416 } 13417 13418 // Forbid the block-capture of autoreleasing variables. 13419 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13420 if (BuildAndDiagnose) { 13421 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13422 << /*block*/ 0; 13423 S.Diag(Var->getLocation(), diag::note_previous_decl) 13424 << Var->getDeclName(); 13425 } 13426 return false; 13427 } 13428 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13429 if (HasBlocksAttr || CaptureType->isReferenceType() || 13430 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13431 // Block capture by reference does not change the capture or 13432 // declaration reference types. 13433 ByRef = true; 13434 } else { 13435 // Block capture by copy introduces 'const'. 13436 CaptureType = CaptureType.getNonReferenceType().withConst(); 13437 DeclRefType = CaptureType; 13438 13439 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13440 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13441 // The capture logic needs the destructor, so make sure we mark it. 13442 // Usually this is unnecessary because most local variables have 13443 // their destructors marked at declaration time, but parameters are 13444 // an exception because it's technically only the call site that 13445 // actually requires the destructor. 13446 if (isa<ParmVarDecl>(Var)) 13447 S.FinalizeVarWithDestructor(Var, Record); 13448 13449 // Enter a new evaluation context to insulate the copy 13450 // full-expression. 13451 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13452 13453 // According to the blocks spec, the capture of a variable from 13454 // the stack requires a const copy constructor. This is not true 13455 // of the copy/move done to move a __block variable to the heap. 13456 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13457 DeclRefType.withConst(), 13458 VK_LValue, Loc); 13459 13460 ExprResult Result 13461 = S.PerformCopyInitialization( 13462 InitializedEntity::InitializeBlock(Var->getLocation(), 13463 CaptureType, false), 13464 Loc, DeclRef); 13465 13466 // Build a full-expression copy expression if initialization 13467 // succeeded and used a non-trivial constructor. Recover from 13468 // errors by pretending that the copy isn't necessary. 13469 if (!Result.isInvalid() && 13470 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13471 ->isTrivial()) { 13472 Result = S.MaybeCreateExprWithCleanups(Result); 13473 CopyExpr = Result.get(); 13474 } 13475 } 13476 } 13477 } 13478 13479 // Actually capture the variable. 13480 if (BuildAndDiagnose) 13481 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13482 SourceLocation(), CaptureType, CopyExpr); 13483 13484 return true; 13485 13486 } 13487 13488 13489 /// \brief Capture the given variable in the captured region. 13490 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13491 VarDecl *Var, 13492 SourceLocation Loc, 13493 const bool BuildAndDiagnose, 13494 QualType &CaptureType, 13495 QualType &DeclRefType, 13496 const bool RefersToCapturedVariable, 13497 Sema &S) { 13498 // By default, capture variables by reference. 13499 bool ByRef = true; 13500 // Using an LValue reference type is consistent with Lambdas (see below). 13501 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13502 if (S.IsOpenMPCapturedDecl(Var)) 13503 DeclRefType = DeclRefType.getUnqualifiedType(); 13504 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13505 } 13506 13507 if (ByRef) 13508 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13509 else 13510 CaptureType = DeclRefType; 13511 13512 Expr *CopyExpr = nullptr; 13513 if (BuildAndDiagnose) { 13514 // The current implementation assumes that all variables are captured 13515 // by references. Since there is no capture by copy, no expression 13516 // evaluation will be needed. 13517 RecordDecl *RD = RSI->TheRecordDecl; 13518 13519 FieldDecl *Field 13520 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13521 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13522 nullptr, false, ICIS_NoInit); 13523 Field->setImplicit(true); 13524 Field->setAccess(AS_private); 13525 RD->addDecl(Field); 13526 13527 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13528 DeclRefType, VK_LValue, Loc); 13529 Var->setReferenced(true); 13530 Var->markUsed(S.Context); 13531 } 13532 13533 // Actually capture the variable. 13534 if (BuildAndDiagnose) 13535 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13536 SourceLocation(), CaptureType, CopyExpr); 13537 13538 13539 return true; 13540 } 13541 13542 /// \brief Create a field within the lambda class for the variable 13543 /// being captured. 13544 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13545 QualType FieldType, QualType DeclRefType, 13546 SourceLocation Loc, 13547 bool RefersToCapturedVariable) { 13548 CXXRecordDecl *Lambda = LSI->Lambda; 13549 13550 // Build the non-static data member. 13551 FieldDecl *Field 13552 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13553 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13554 nullptr, false, ICIS_NoInit); 13555 Field->setImplicit(true); 13556 Field->setAccess(AS_private); 13557 Lambda->addDecl(Field); 13558 } 13559 13560 /// \brief Capture the given variable in the lambda. 13561 static bool captureInLambda(LambdaScopeInfo *LSI, 13562 VarDecl *Var, 13563 SourceLocation Loc, 13564 const bool BuildAndDiagnose, 13565 QualType &CaptureType, 13566 QualType &DeclRefType, 13567 const bool RefersToCapturedVariable, 13568 const Sema::TryCaptureKind Kind, 13569 SourceLocation EllipsisLoc, 13570 const bool IsTopScope, 13571 Sema &S) { 13572 13573 // Determine whether we are capturing by reference or by value. 13574 bool ByRef = false; 13575 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13576 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13577 } else { 13578 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13579 } 13580 13581 // Compute the type of the field that will capture this variable. 13582 if (ByRef) { 13583 // C++11 [expr.prim.lambda]p15: 13584 // An entity is captured by reference if it is implicitly or 13585 // explicitly captured but not captured by copy. It is 13586 // unspecified whether additional unnamed non-static data 13587 // members are declared in the closure type for entities 13588 // captured by reference. 13589 // 13590 // FIXME: It is not clear whether we want to build an lvalue reference 13591 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13592 // to do the former, while EDG does the latter. Core issue 1249 will 13593 // clarify, but for now we follow GCC because it's a more permissive and 13594 // easily defensible position. 13595 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13596 } else { 13597 // C++11 [expr.prim.lambda]p14: 13598 // For each entity captured by copy, an unnamed non-static 13599 // data member is declared in the closure type. The 13600 // declaration order of these members is unspecified. The type 13601 // of such a data member is the type of the corresponding 13602 // captured entity if the entity is not a reference to an 13603 // object, or the referenced type otherwise. [Note: If the 13604 // captured entity is a reference to a function, the 13605 // corresponding data member is also a reference to a 13606 // function. - end note ] 13607 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13608 if (!RefType->getPointeeType()->isFunctionType()) 13609 CaptureType = RefType->getPointeeType(); 13610 } 13611 13612 // Forbid the lambda copy-capture of autoreleasing variables. 13613 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13614 if (BuildAndDiagnose) { 13615 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13616 S.Diag(Var->getLocation(), diag::note_previous_decl) 13617 << Var->getDeclName(); 13618 } 13619 return false; 13620 } 13621 13622 // Make sure that by-copy captures are of a complete and non-abstract type. 13623 if (BuildAndDiagnose) { 13624 if (!CaptureType->isDependentType() && 13625 S.RequireCompleteType(Loc, CaptureType, 13626 diag::err_capture_of_incomplete_type, 13627 Var->getDeclName())) 13628 return false; 13629 13630 if (S.RequireNonAbstractType(Loc, CaptureType, 13631 diag::err_capture_of_abstract_type)) 13632 return false; 13633 } 13634 } 13635 13636 // Capture this variable in the lambda. 13637 if (BuildAndDiagnose) 13638 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13639 RefersToCapturedVariable); 13640 13641 // Compute the type of a reference to this captured variable. 13642 if (ByRef) 13643 DeclRefType = CaptureType.getNonReferenceType(); 13644 else { 13645 // C++ [expr.prim.lambda]p5: 13646 // The closure type for a lambda-expression has a public inline 13647 // function call operator [...]. This function call operator is 13648 // declared const (9.3.1) if and only if the lambda-expression’s 13649 // parameter-declaration-clause is not followed by mutable. 13650 DeclRefType = CaptureType.getNonReferenceType(); 13651 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13652 DeclRefType.addConst(); 13653 } 13654 13655 // Add the capture. 13656 if (BuildAndDiagnose) 13657 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13658 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13659 13660 return true; 13661 } 13662 13663 bool Sema::tryCaptureVariable( 13664 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13665 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13666 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13667 // An init-capture is notionally from the context surrounding its 13668 // declaration, but its parent DC is the lambda class. 13669 DeclContext *VarDC = Var->getDeclContext(); 13670 if (Var->isInitCapture()) 13671 VarDC = VarDC->getParent(); 13672 13673 DeclContext *DC = CurContext; 13674 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13675 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13676 // We need to sync up the Declaration Context with the 13677 // FunctionScopeIndexToStopAt 13678 if (FunctionScopeIndexToStopAt) { 13679 unsigned FSIndex = FunctionScopes.size() - 1; 13680 while (FSIndex != MaxFunctionScopesIndex) { 13681 DC = getLambdaAwareParentOfDeclContext(DC); 13682 --FSIndex; 13683 } 13684 } 13685 13686 13687 // If the variable is declared in the current context, there is no need to 13688 // capture it. 13689 if (VarDC == DC) return true; 13690 13691 // Capture global variables if it is required to use private copy of this 13692 // variable. 13693 bool IsGlobal = !Var->hasLocalStorage(); 13694 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13695 return true; 13696 13697 // Walk up the stack to determine whether we can capture the variable, 13698 // performing the "simple" checks that don't depend on type. We stop when 13699 // we've either hit the declared scope of the variable or find an existing 13700 // capture of that variable. We start from the innermost capturing-entity 13701 // (the DC) and ensure that all intervening capturing-entities 13702 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13703 // declcontext can either capture the variable or have already captured 13704 // the variable. 13705 CaptureType = Var->getType(); 13706 DeclRefType = CaptureType.getNonReferenceType(); 13707 bool Nested = false; 13708 bool Explicit = (Kind != TryCapture_Implicit); 13709 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13710 do { 13711 // Only block literals, captured statements, and lambda expressions can 13712 // capture; other scopes don't work. 13713 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13714 ExprLoc, 13715 BuildAndDiagnose, 13716 *this); 13717 // We need to check for the parent *first* because, if we *have* 13718 // private-captured a global variable, we need to recursively capture it in 13719 // intermediate blocks, lambdas, etc. 13720 if (!ParentDC) { 13721 if (IsGlobal) { 13722 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13723 break; 13724 } 13725 return true; 13726 } 13727 13728 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13729 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13730 13731 13732 // Check whether we've already captured it. 13733 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13734 DeclRefType)) 13735 break; 13736 // If we are instantiating a generic lambda call operator body, 13737 // we do not want to capture new variables. What was captured 13738 // during either a lambdas transformation or initial parsing 13739 // should be used. 13740 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13741 if (BuildAndDiagnose) { 13742 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13743 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13744 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13745 Diag(Var->getLocation(), diag::note_previous_decl) 13746 << Var->getDeclName(); 13747 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13748 } else 13749 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13750 } 13751 return true; 13752 } 13753 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13754 // certain types of variables (unnamed, variably modified types etc.) 13755 // so check for eligibility. 13756 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13757 return true; 13758 13759 // Try to capture variable-length arrays types. 13760 if (Var->getType()->isVariablyModifiedType()) { 13761 // We're going to walk down into the type and look for VLA 13762 // expressions. 13763 QualType QTy = Var->getType(); 13764 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13765 QTy = PVD->getOriginalType(); 13766 captureVariablyModifiedType(Context, QTy, CSI); 13767 } 13768 13769 if (getLangOpts().OpenMP) { 13770 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13771 // OpenMP private variables should not be captured in outer scope, so 13772 // just break here. Similarly, global variables that are captured in a 13773 // target region should not be captured outside the scope of the region. 13774 if (RSI->CapRegionKind == CR_OpenMP) { 13775 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13776 // When we detect target captures we are looking from inside the 13777 // target region, therefore we need to propagate the capture from the 13778 // enclosing region. Therefore, the capture is not initially nested. 13779 if (IsTargetCap) 13780 FunctionScopesIndex--; 13781 13782 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13783 Nested = !IsTargetCap; 13784 DeclRefType = DeclRefType.getUnqualifiedType(); 13785 CaptureType = Context.getLValueReferenceType(DeclRefType); 13786 break; 13787 } 13788 } 13789 } 13790 } 13791 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13792 // No capture-default, and this is not an explicit capture 13793 // so cannot capture this variable. 13794 if (BuildAndDiagnose) { 13795 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13796 Diag(Var->getLocation(), diag::note_previous_decl) 13797 << Var->getDeclName(); 13798 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13799 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13800 diag::note_lambda_decl); 13801 // FIXME: If we error out because an outer lambda can not implicitly 13802 // capture a variable that an inner lambda explicitly captures, we 13803 // should have the inner lambda do the explicit capture - because 13804 // it makes for cleaner diagnostics later. This would purely be done 13805 // so that the diagnostic does not misleadingly claim that a variable 13806 // can not be captured by a lambda implicitly even though it is captured 13807 // explicitly. Suggestion: 13808 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13809 // at the function head 13810 // - cache the StartingDeclContext - this must be a lambda 13811 // - captureInLambda in the innermost lambda the variable. 13812 } 13813 return true; 13814 } 13815 13816 FunctionScopesIndex--; 13817 DC = ParentDC; 13818 Explicit = false; 13819 } while (!VarDC->Equals(DC)); 13820 13821 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13822 // computing the type of the capture at each step, checking type-specific 13823 // requirements, and adding captures if requested. 13824 // If the variable had already been captured previously, we start capturing 13825 // at the lambda nested within that one. 13826 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13827 ++I) { 13828 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13829 13830 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13831 if (!captureInBlock(BSI, Var, ExprLoc, 13832 BuildAndDiagnose, CaptureType, 13833 DeclRefType, Nested, *this)) 13834 return true; 13835 Nested = true; 13836 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13837 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13838 BuildAndDiagnose, CaptureType, 13839 DeclRefType, Nested, *this)) 13840 return true; 13841 Nested = true; 13842 } else { 13843 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13844 if (!captureInLambda(LSI, Var, ExprLoc, 13845 BuildAndDiagnose, CaptureType, 13846 DeclRefType, Nested, Kind, EllipsisLoc, 13847 /*IsTopScope*/I == N - 1, *this)) 13848 return true; 13849 Nested = true; 13850 } 13851 } 13852 return false; 13853 } 13854 13855 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13856 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13857 QualType CaptureType; 13858 QualType DeclRefType; 13859 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13860 /*BuildAndDiagnose=*/true, CaptureType, 13861 DeclRefType, nullptr); 13862 } 13863 13864 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13865 QualType CaptureType; 13866 QualType DeclRefType; 13867 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13868 /*BuildAndDiagnose=*/false, CaptureType, 13869 DeclRefType, nullptr); 13870 } 13871 13872 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13873 QualType CaptureType; 13874 QualType DeclRefType; 13875 13876 // Determine whether we can capture this variable. 13877 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13878 /*BuildAndDiagnose=*/false, CaptureType, 13879 DeclRefType, nullptr)) 13880 return QualType(); 13881 13882 return DeclRefType; 13883 } 13884 13885 13886 13887 // If either the type of the variable or the initializer is dependent, 13888 // return false. Otherwise, determine whether the variable is a constant 13889 // expression. Use this if you need to know if a variable that might or 13890 // might not be dependent is truly a constant expression. 13891 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13892 ASTContext &Context) { 13893 13894 if (Var->getType()->isDependentType()) 13895 return false; 13896 const VarDecl *DefVD = nullptr; 13897 Var->getAnyInitializer(DefVD); 13898 if (!DefVD) 13899 return false; 13900 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13901 Expr *Init = cast<Expr>(Eval->Value); 13902 if (Init->isValueDependent()) 13903 return false; 13904 return IsVariableAConstantExpression(Var, Context); 13905 } 13906 13907 13908 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13909 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13910 // an object that satisfies the requirements for appearing in a 13911 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13912 // is immediately applied." This function handles the lvalue-to-rvalue 13913 // conversion part. 13914 MaybeODRUseExprs.erase(E->IgnoreParens()); 13915 13916 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13917 // to a variable that is a constant expression, and if so, identify it as 13918 // a reference to a variable that does not involve an odr-use of that 13919 // variable. 13920 if (LambdaScopeInfo *LSI = getCurLambda()) { 13921 Expr *SansParensExpr = E->IgnoreParens(); 13922 VarDecl *Var = nullptr; 13923 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13924 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13925 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13926 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13927 13928 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13929 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13930 } 13931 } 13932 13933 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13934 Res = CorrectDelayedTyposInExpr(Res); 13935 13936 if (!Res.isUsable()) 13937 return Res; 13938 13939 // If a constant-expression is a reference to a variable where we delay 13940 // deciding whether it is an odr-use, just assume we will apply the 13941 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13942 // (a non-type template argument), we have special handling anyway. 13943 UpdateMarkingForLValueToRValue(Res.get()); 13944 return Res; 13945 } 13946 13947 void Sema::CleanupVarDeclMarking() { 13948 for (Expr *E : MaybeODRUseExprs) { 13949 VarDecl *Var; 13950 SourceLocation Loc; 13951 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13952 Var = cast<VarDecl>(DRE->getDecl()); 13953 Loc = DRE->getLocation(); 13954 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13955 Var = cast<VarDecl>(ME->getMemberDecl()); 13956 Loc = ME->getMemberLoc(); 13957 } else { 13958 llvm_unreachable("Unexpected expression"); 13959 } 13960 13961 MarkVarDeclODRUsed(Var, Loc, *this, 13962 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13963 } 13964 13965 MaybeODRUseExprs.clear(); 13966 } 13967 13968 13969 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13970 VarDecl *Var, Expr *E) { 13971 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13972 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13973 Var->setReferenced(); 13974 13975 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13976 bool MarkODRUsed = true; 13977 13978 // If the context is not potentially evaluated, this is not an odr-use and 13979 // does not trigger instantiation. 13980 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13981 if (SemaRef.isUnevaluatedContext()) 13982 return; 13983 13984 // If we don't yet know whether this context is going to end up being an 13985 // evaluated context, and we're referencing a variable from an enclosing 13986 // scope, add a potential capture. 13987 // 13988 // FIXME: Is this necessary? These contexts are only used for default 13989 // arguments, where local variables can't be used. 13990 const bool RefersToEnclosingScope = 13991 (SemaRef.CurContext != Var->getDeclContext() && 13992 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13993 if (RefersToEnclosingScope) { 13994 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13995 // If a variable could potentially be odr-used, defer marking it so 13996 // until we finish analyzing the full expression for any 13997 // lvalue-to-rvalue 13998 // or discarded value conversions that would obviate odr-use. 13999 // Add it to the list of potential captures that will be analyzed 14000 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14001 // unless the variable is a reference that was initialized by a constant 14002 // expression (this will never need to be captured or odr-used). 14003 assert(E && "Capture variable should be used in an expression."); 14004 if (!Var->getType()->isReferenceType() || 14005 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14006 LSI->addPotentialCapture(E->IgnoreParens()); 14007 } 14008 } 14009 14010 if (!isTemplateInstantiation(TSK)) 14011 return; 14012 14013 // Instantiate, but do not mark as odr-used, variable templates. 14014 MarkODRUsed = false; 14015 } 14016 14017 VarTemplateSpecializationDecl *VarSpec = 14018 dyn_cast<VarTemplateSpecializationDecl>(Var); 14019 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14020 "Can't instantiate a partial template specialization."); 14021 14022 // If this might be a member specialization of a static data member, check 14023 // the specialization is visible. We already did the checks for variable 14024 // template specializations when we created them. 14025 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14026 SemaRef.checkSpecializationVisibility(Loc, Var); 14027 14028 // Perform implicit instantiation of static data members, static data member 14029 // templates of class templates, and variable template specializations. Delay 14030 // instantiations of variable templates, except for those that could be used 14031 // in a constant expression. 14032 if (isTemplateInstantiation(TSK)) { 14033 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14034 14035 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14036 if (Var->getPointOfInstantiation().isInvalid()) { 14037 // This is a modification of an existing AST node. Notify listeners. 14038 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14039 L->StaticDataMemberInstantiated(Var); 14040 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14041 // Don't bother trying to instantiate it again, unless we might need 14042 // its initializer before we get to the end of the TU. 14043 TryInstantiating = false; 14044 } 14045 14046 if (Var->getPointOfInstantiation().isInvalid()) 14047 Var->setTemplateSpecializationKind(TSK, Loc); 14048 14049 if (TryInstantiating) { 14050 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14051 bool InstantiationDependent = false; 14052 bool IsNonDependent = 14053 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14054 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14055 : true; 14056 14057 // Do not instantiate specializations that are still type-dependent. 14058 if (IsNonDependent) { 14059 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14060 // Do not defer instantiations of variables which could be used in a 14061 // constant expression. 14062 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14063 } else { 14064 SemaRef.PendingInstantiations 14065 .push_back(std::make_pair(Var, PointOfInstantiation)); 14066 } 14067 } 14068 } 14069 } 14070 14071 if (!MarkODRUsed) 14072 return; 14073 14074 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14075 // the requirements for appearing in a constant expression (5.19) and, if 14076 // it is an object, the lvalue-to-rvalue conversion (4.1) 14077 // is immediately applied." We check the first part here, and 14078 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14079 // Note that we use the C++11 definition everywhere because nothing in 14080 // C++03 depends on whether we get the C++03 version correct. The second 14081 // part does not apply to references, since they are not objects. 14082 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14083 // A reference initialized by a constant expression can never be 14084 // odr-used, so simply ignore it. 14085 if (!Var->getType()->isReferenceType()) 14086 SemaRef.MaybeODRUseExprs.insert(E); 14087 } else 14088 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14089 /*MaxFunctionScopeIndex ptr*/ nullptr); 14090 } 14091 14092 /// \brief Mark a variable referenced, and check whether it is odr-used 14093 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14094 /// used directly for normal expressions referring to VarDecl. 14095 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14096 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14097 } 14098 14099 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14100 Decl *D, Expr *E, bool MightBeOdrUse) { 14101 if (SemaRef.isInOpenMPDeclareTargetContext()) 14102 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14103 14104 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14105 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14106 return; 14107 } 14108 14109 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14110 14111 // If this is a call to a method via a cast, also mark the method in the 14112 // derived class used in case codegen can devirtualize the call. 14113 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14114 if (!ME) 14115 return; 14116 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14117 if (!MD) 14118 return; 14119 // Only attempt to devirtualize if this is truly a virtual call. 14120 bool IsVirtualCall = MD->isVirtual() && 14121 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14122 if (!IsVirtualCall) 14123 return; 14124 const Expr *Base = ME->getBase(); 14125 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14126 if (!MostDerivedClassDecl) 14127 return; 14128 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14129 if (!DM || DM->isPure()) 14130 return; 14131 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14132 } 14133 14134 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14135 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14136 // TODO: update this with DR# once a defect report is filed. 14137 // C++11 defect. The address of a pure member should not be an ODR use, even 14138 // if it's a qualified reference. 14139 bool OdrUse = true; 14140 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14141 if (Method->isVirtual()) 14142 OdrUse = false; 14143 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14144 } 14145 14146 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14147 void Sema::MarkMemberReferenced(MemberExpr *E) { 14148 // C++11 [basic.def.odr]p2: 14149 // A non-overloaded function whose name appears as a potentially-evaluated 14150 // expression or a member of a set of candidate functions, if selected by 14151 // overload resolution when referred to from a potentially-evaluated 14152 // expression, is odr-used, unless it is a pure virtual function and its 14153 // name is not explicitly qualified. 14154 bool MightBeOdrUse = true; 14155 if (E->performsVirtualDispatch(getLangOpts())) { 14156 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14157 if (Method->isPure()) 14158 MightBeOdrUse = false; 14159 } 14160 SourceLocation Loc = E->getMemberLoc().isValid() ? 14161 E->getMemberLoc() : E->getLocStart(); 14162 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14163 } 14164 14165 /// \brief Perform marking for a reference to an arbitrary declaration. It 14166 /// marks the declaration referenced, and performs odr-use checking for 14167 /// functions and variables. This method should not be used when building a 14168 /// normal expression which refers to a variable. 14169 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14170 bool MightBeOdrUse) { 14171 if (MightBeOdrUse) { 14172 if (auto *VD = dyn_cast<VarDecl>(D)) { 14173 MarkVariableReferenced(Loc, VD); 14174 return; 14175 } 14176 } 14177 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14178 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14179 return; 14180 } 14181 D->setReferenced(); 14182 } 14183 14184 namespace { 14185 // Mark all of the declarations referenced 14186 // FIXME: Not fully implemented yet! We need to have a better understanding 14187 // of when we're entering 14188 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14189 Sema &S; 14190 SourceLocation Loc; 14191 14192 public: 14193 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14194 14195 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14196 14197 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14198 bool TraverseRecordType(RecordType *T); 14199 }; 14200 } 14201 14202 bool MarkReferencedDecls::TraverseTemplateArgument( 14203 const TemplateArgument &Arg) { 14204 if (Arg.getKind() == TemplateArgument::Declaration) { 14205 if (Decl *D = Arg.getAsDecl()) 14206 S.MarkAnyDeclReferenced(Loc, D, true); 14207 } 14208 14209 return Inherited::TraverseTemplateArgument(Arg); 14210 } 14211 14212 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14213 if (ClassTemplateSpecializationDecl *Spec 14214 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14215 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14216 return TraverseTemplateArguments(Args.data(), Args.size()); 14217 } 14218 14219 return true; 14220 } 14221 14222 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14223 MarkReferencedDecls Marker(*this, Loc); 14224 Marker.TraverseType(Context.getCanonicalType(T)); 14225 } 14226 14227 namespace { 14228 /// \brief Helper class that marks all of the declarations referenced by 14229 /// potentially-evaluated subexpressions as "referenced". 14230 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14231 Sema &S; 14232 bool SkipLocalVariables; 14233 14234 public: 14235 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14236 14237 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14238 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14239 14240 void VisitDeclRefExpr(DeclRefExpr *E) { 14241 // If we were asked not to visit local variables, don't. 14242 if (SkipLocalVariables) { 14243 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14244 if (VD->hasLocalStorage()) 14245 return; 14246 } 14247 14248 S.MarkDeclRefReferenced(E); 14249 } 14250 14251 void VisitMemberExpr(MemberExpr *E) { 14252 S.MarkMemberReferenced(E); 14253 Inherited::VisitMemberExpr(E); 14254 } 14255 14256 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14257 S.MarkFunctionReferenced(E->getLocStart(), 14258 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14259 Visit(E->getSubExpr()); 14260 } 14261 14262 void VisitCXXNewExpr(CXXNewExpr *E) { 14263 if (E->getOperatorNew()) 14264 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14265 if (E->getOperatorDelete()) 14266 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14267 Inherited::VisitCXXNewExpr(E); 14268 } 14269 14270 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14271 if (E->getOperatorDelete()) 14272 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14273 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14274 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14275 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14276 S.MarkFunctionReferenced(E->getLocStart(), 14277 S.LookupDestructor(Record)); 14278 } 14279 14280 Inherited::VisitCXXDeleteExpr(E); 14281 } 14282 14283 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14284 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14285 Inherited::VisitCXXConstructExpr(E); 14286 } 14287 14288 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14289 Visit(E->getExpr()); 14290 } 14291 14292 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14293 Inherited::VisitImplicitCastExpr(E); 14294 14295 if (E->getCastKind() == CK_LValueToRValue) 14296 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14297 } 14298 }; 14299 } 14300 14301 /// \brief Mark any declarations that appear within this expression or any 14302 /// potentially-evaluated subexpressions as "referenced". 14303 /// 14304 /// \param SkipLocalVariables If true, don't mark local variables as 14305 /// 'referenced'. 14306 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14307 bool SkipLocalVariables) { 14308 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14309 } 14310 14311 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14312 /// of the program being compiled. 14313 /// 14314 /// This routine emits the given diagnostic when the code currently being 14315 /// type-checked is "potentially evaluated", meaning that there is a 14316 /// possibility that the code will actually be executable. Code in sizeof() 14317 /// expressions, code used only during overload resolution, etc., are not 14318 /// potentially evaluated. This routine will suppress such diagnostics or, 14319 /// in the absolutely nutty case of potentially potentially evaluated 14320 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14321 /// later. 14322 /// 14323 /// This routine should be used for all diagnostics that describe the run-time 14324 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14325 /// Failure to do so will likely result in spurious diagnostics or failures 14326 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14327 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14328 const PartialDiagnostic &PD) { 14329 switch (ExprEvalContexts.back().Context) { 14330 case Unevaluated: 14331 case UnevaluatedAbstract: 14332 case DiscardedStatement: 14333 // The argument will never be evaluated, so don't complain. 14334 break; 14335 14336 case ConstantEvaluated: 14337 // Relevant diagnostics should be produced by constant evaluation. 14338 break; 14339 14340 case PotentiallyEvaluated: 14341 case PotentiallyEvaluatedIfUsed: 14342 if (Statement && getCurFunctionOrMethodDecl()) { 14343 FunctionScopes.back()->PossiblyUnreachableDiags. 14344 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14345 } 14346 else 14347 Diag(Loc, PD); 14348 14349 return true; 14350 } 14351 14352 return false; 14353 } 14354 14355 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14356 CallExpr *CE, FunctionDecl *FD) { 14357 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14358 return false; 14359 14360 // If we're inside a decltype's expression, don't check for a valid return 14361 // type or construct temporaries until we know whether this is the last call. 14362 if (ExprEvalContexts.back().IsDecltype) { 14363 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14364 return false; 14365 } 14366 14367 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14368 FunctionDecl *FD; 14369 CallExpr *CE; 14370 14371 public: 14372 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14373 : FD(FD), CE(CE) { } 14374 14375 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14376 if (!FD) { 14377 S.Diag(Loc, diag::err_call_incomplete_return) 14378 << T << CE->getSourceRange(); 14379 return; 14380 } 14381 14382 S.Diag(Loc, diag::err_call_function_incomplete_return) 14383 << CE->getSourceRange() << FD->getDeclName() << T; 14384 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14385 << FD->getDeclName(); 14386 } 14387 } Diagnoser(FD, CE); 14388 14389 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14390 return true; 14391 14392 return false; 14393 } 14394 14395 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14396 // will prevent this condition from triggering, which is what we want. 14397 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14398 SourceLocation Loc; 14399 14400 unsigned diagnostic = diag::warn_condition_is_assignment; 14401 bool IsOrAssign = false; 14402 14403 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14404 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14405 return; 14406 14407 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14408 14409 // Greylist some idioms by putting them into a warning subcategory. 14410 if (ObjCMessageExpr *ME 14411 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14412 Selector Sel = ME->getSelector(); 14413 14414 // self = [<foo> init...] 14415 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14416 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14417 14418 // <foo> = [<bar> nextObject] 14419 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14420 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14421 } 14422 14423 Loc = Op->getOperatorLoc(); 14424 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14425 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14426 return; 14427 14428 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14429 Loc = Op->getOperatorLoc(); 14430 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14431 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14432 else { 14433 // Not an assignment. 14434 return; 14435 } 14436 14437 Diag(Loc, diagnostic) << E->getSourceRange(); 14438 14439 SourceLocation Open = E->getLocStart(); 14440 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14441 Diag(Loc, diag::note_condition_assign_silence) 14442 << FixItHint::CreateInsertion(Open, "(") 14443 << FixItHint::CreateInsertion(Close, ")"); 14444 14445 if (IsOrAssign) 14446 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14447 << FixItHint::CreateReplacement(Loc, "!="); 14448 else 14449 Diag(Loc, diag::note_condition_assign_to_comparison) 14450 << FixItHint::CreateReplacement(Loc, "=="); 14451 } 14452 14453 /// \brief Redundant parentheses over an equality comparison can indicate 14454 /// that the user intended an assignment used as condition. 14455 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14456 // Don't warn if the parens came from a macro. 14457 SourceLocation parenLoc = ParenE->getLocStart(); 14458 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14459 return; 14460 // Don't warn for dependent expressions. 14461 if (ParenE->isTypeDependent()) 14462 return; 14463 14464 Expr *E = ParenE->IgnoreParens(); 14465 14466 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14467 if (opE->getOpcode() == BO_EQ && 14468 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14469 == Expr::MLV_Valid) { 14470 SourceLocation Loc = opE->getOperatorLoc(); 14471 14472 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14473 SourceRange ParenERange = ParenE->getSourceRange(); 14474 Diag(Loc, diag::note_equality_comparison_silence) 14475 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14476 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14477 Diag(Loc, diag::note_equality_comparison_to_assign) 14478 << FixItHint::CreateReplacement(Loc, "="); 14479 } 14480 } 14481 14482 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14483 bool IsConstexpr) { 14484 DiagnoseAssignmentAsCondition(E); 14485 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14486 DiagnoseEqualityWithExtraParens(parenE); 14487 14488 ExprResult result = CheckPlaceholderExpr(E); 14489 if (result.isInvalid()) return ExprError(); 14490 E = result.get(); 14491 14492 if (!E->isTypeDependent()) { 14493 if (getLangOpts().CPlusPlus) 14494 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14495 14496 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14497 if (ERes.isInvalid()) 14498 return ExprError(); 14499 E = ERes.get(); 14500 14501 QualType T = E->getType(); 14502 if (!T->isScalarType()) { // C99 6.8.4.1p1 14503 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14504 << T << E->getSourceRange(); 14505 return ExprError(); 14506 } 14507 CheckBoolLikeConversion(E, Loc); 14508 } 14509 14510 return E; 14511 } 14512 14513 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14514 Expr *SubExpr, ConditionKind CK) { 14515 // Empty conditions are valid in for-statements. 14516 if (!SubExpr) 14517 return ConditionResult(); 14518 14519 ExprResult Cond; 14520 switch (CK) { 14521 case ConditionKind::Boolean: 14522 Cond = CheckBooleanCondition(Loc, SubExpr); 14523 break; 14524 14525 case ConditionKind::ConstexprIf: 14526 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14527 break; 14528 14529 case ConditionKind::Switch: 14530 Cond = CheckSwitchCondition(Loc, SubExpr); 14531 break; 14532 } 14533 if (Cond.isInvalid()) 14534 return ConditionError(); 14535 14536 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14537 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14538 if (!FullExpr.get()) 14539 return ConditionError(); 14540 14541 return ConditionResult(*this, nullptr, FullExpr, 14542 CK == ConditionKind::ConstexprIf); 14543 } 14544 14545 namespace { 14546 /// A visitor for rebuilding a call to an __unknown_any expression 14547 /// to have an appropriate type. 14548 struct RebuildUnknownAnyFunction 14549 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14550 14551 Sema &S; 14552 14553 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14554 14555 ExprResult VisitStmt(Stmt *S) { 14556 llvm_unreachable("unexpected statement!"); 14557 } 14558 14559 ExprResult VisitExpr(Expr *E) { 14560 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14561 << E->getSourceRange(); 14562 return ExprError(); 14563 } 14564 14565 /// Rebuild an expression which simply semantically wraps another 14566 /// expression which it shares the type and value kind of. 14567 template <class T> ExprResult rebuildSugarExpr(T *E) { 14568 ExprResult SubResult = Visit(E->getSubExpr()); 14569 if (SubResult.isInvalid()) return ExprError(); 14570 14571 Expr *SubExpr = SubResult.get(); 14572 E->setSubExpr(SubExpr); 14573 E->setType(SubExpr->getType()); 14574 E->setValueKind(SubExpr->getValueKind()); 14575 assert(E->getObjectKind() == OK_Ordinary); 14576 return E; 14577 } 14578 14579 ExprResult VisitParenExpr(ParenExpr *E) { 14580 return rebuildSugarExpr(E); 14581 } 14582 14583 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14584 return rebuildSugarExpr(E); 14585 } 14586 14587 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14588 ExprResult SubResult = Visit(E->getSubExpr()); 14589 if (SubResult.isInvalid()) return ExprError(); 14590 14591 Expr *SubExpr = SubResult.get(); 14592 E->setSubExpr(SubExpr); 14593 E->setType(S.Context.getPointerType(SubExpr->getType())); 14594 assert(E->getValueKind() == VK_RValue); 14595 assert(E->getObjectKind() == OK_Ordinary); 14596 return E; 14597 } 14598 14599 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14600 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14601 14602 E->setType(VD->getType()); 14603 14604 assert(E->getValueKind() == VK_RValue); 14605 if (S.getLangOpts().CPlusPlus && 14606 !(isa<CXXMethodDecl>(VD) && 14607 cast<CXXMethodDecl>(VD)->isInstance())) 14608 E->setValueKind(VK_LValue); 14609 14610 return E; 14611 } 14612 14613 ExprResult VisitMemberExpr(MemberExpr *E) { 14614 return resolveDecl(E, E->getMemberDecl()); 14615 } 14616 14617 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14618 return resolveDecl(E, E->getDecl()); 14619 } 14620 }; 14621 } 14622 14623 /// Given a function expression of unknown-any type, try to rebuild it 14624 /// to have a function type. 14625 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14626 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14627 if (Result.isInvalid()) return ExprError(); 14628 return S.DefaultFunctionArrayConversion(Result.get()); 14629 } 14630 14631 namespace { 14632 /// A visitor for rebuilding an expression of type __unknown_anytype 14633 /// into one which resolves the type directly on the referring 14634 /// expression. Strict preservation of the original source 14635 /// structure is not a goal. 14636 struct RebuildUnknownAnyExpr 14637 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14638 14639 Sema &S; 14640 14641 /// The current destination type. 14642 QualType DestType; 14643 14644 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14645 : S(S), DestType(CastType) {} 14646 14647 ExprResult VisitStmt(Stmt *S) { 14648 llvm_unreachable("unexpected statement!"); 14649 } 14650 14651 ExprResult VisitExpr(Expr *E) { 14652 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14653 << E->getSourceRange(); 14654 return ExprError(); 14655 } 14656 14657 ExprResult VisitCallExpr(CallExpr *E); 14658 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14659 14660 /// Rebuild an expression which simply semantically wraps another 14661 /// expression which it shares the type and value kind of. 14662 template <class T> ExprResult rebuildSugarExpr(T *E) { 14663 ExprResult SubResult = Visit(E->getSubExpr()); 14664 if (SubResult.isInvalid()) return ExprError(); 14665 Expr *SubExpr = SubResult.get(); 14666 E->setSubExpr(SubExpr); 14667 E->setType(SubExpr->getType()); 14668 E->setValueKind(SubExpr->getValueKind()); 14669 assert(E->getObjectKind() == OK_Ordinary); 14670 return E; 14671 } 14672 14673 ExprResult VisitParenExpr(ParenExpr *E) { 14674 return rebuildSugarExpr(E); 14675 } 14676 14677 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14678 return rebuildSugarExpr(E); 14679 } 14680 14681 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14682 const PointerType *Ptr = DestType->getAs<PointerType>(); 14683 if (!Ptr) { 14684 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14685 << E->getSourceRange(); 14686 return ExprError(); 14687 } 14688 assert(E->getValueKind() == VK_RValue); 14689 assert(E->getObjectKind() == OK_Ordinary); 14690 E->setType(DestType); 14691 14692 // Build the sub-expression as if it were an object of the pointee type. 14693 DestType = Ptr->getPointeeType(); 14694 ExprResult SubResult = Visit(E->getSubExpr()); 14695 if (SubResult.isInvalid()) return ExprError(); 14696 E->setSubExpr(SubResult.get()); 14697 return E; 14698 } 14699 14700 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14701 14702 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14703 14704 ExprResult VisitMemberExpr(MemberExpr *E) { 14705 return resolveDecl(E, E->getMemberDecl()); 14706 } 14707 14708 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14709 return resolveDecl(E, E->getDecl()); 14710 } 14711 }; 14712 } 14713 14714 /// Rebuilds a call expression which yielded __unknown_anytype. 14715 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14716 Expr *CalleeExpr = E->getCallee(); 14717 14718 enum FnKind { 14719 FK_MemberFunction, 14720 FK_FunctionPointer, 14721 FK_BlockPointer 14722 }; 14723 14724 FnKind Kind; 14725 QualType CalleeType = CalleeExpr->getType(); 14726 if (CalleeType == S.Context.BoundMemberTy) { 14727 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14728 Kind = FK_MemberFunction; 14729 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14730 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14731 CalleeType = Ptr->getPointeeType(); 14732 Kind = FK_FunctionPointer; 14733 } else { 14734 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14735 Kind = FK_BlockPointer; 14736 } 14737 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14738 14739 // Verify that this is a legal result type of a function. 14740 if (DestType->isArrayType() || DestType->isFunctionType()) { 14741 unsigned diagID = diag::err_func_returning_array_function; 14742 if (Kind == FK_BlockPointer) 14743 diagID = diag::err_block_returning_array_function; 14744 14745 S.Diag(E->getExprLoc(), diagID) 14746 << DestType->isFunctionType() << DestType; 14747 return ExprError(); 14748 } 14749 14750 // Otherwise, go ahead and set DestType as the call's result. 14751 E->setType(DestType.getNonLValueExprType(S.Context)); 14752 E->setValueKind(Expr::getValueKindForType(DestType)); 14753 assert(E->getObjectKind() == OK_Ordinary); 14754 14755 // Rebuild the function type, replacing the result type with DestType. 14756 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14757 if (Proto) { 14758 // __unknown_anytype(...) is a special case used by the debugger when 14759 // it has no idea what a function's signature is. 14760 // 14761 // We want to build this call essentially under the K&R 14762 // unprototyped rules, but making a FunctionNoProtoType in C++ 14763 // would foul up all sorts of assumptions. However, we cannot 14764 // simply pass all arguments as variadic arguments, nor can we 14765 // portably just call the function under a non-variadic type; see 14766 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14767 // However, it turns out that in practice it is generally safe to 14768 // call a function declared as "A foo(B,C,D);" under the prototype 14769 // "A foo(B,C,D,...);". The only known exception is with the 14770 // Windows ABI, where any variadic function is implicitly cdecl 14771 // regardless of its normal CC. Therefore we change the parameter 14772 // types to match the types of the arguments. 14773 // 14774 // This is a hack, but it is far superior to moving the 14775 // corresponding target-specific code from IR-gen to Sema/AST. 14776 14777 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14778 SmallVector<QualType, 8> ArgTypes; 14779 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14780 ArgTypes.reserve(E->getNumArgs()); 14781 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14782 Expr *Arg = E->getArg(i); 14783 QualType ArgType = Arg->getType(); 14784 if (E->isLValue()) { 14785 ArgType = S.Context.getLValueReferenceType(ArgType); 14786 } else if (E->isXValue()) { 14787 ArgType = S.Context.getRValueReferenceType(ArgType); 14788 } 14789 ArgTypes.push_back(ArgType); 14790 } 14791 ParamTypes = ArgTypes; 14792 } 14793 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14794 Proto->getExtProtoInfo()); 14795 } else { 14796 DestType = S.Context.getFunctionNoProtoType(DestType, 14797 FnType->getExtInfo()); 14798 } 14799 14800 // Rebuild the appropriate pointer-to-function type. 14801 switch (Kind) { 14802 case FK_MemberFunction: 14803 // Nothing to do. 14804 break; 14805 14806 case FK_FunctionPointer: 14807 DestType = S.Context.getPointerType(DestType); 14808 break; 14809 14810 case FK_BlockPointer: 14811 DestType = S.Context.getBlockPointerType(DestType); 14812 break; 14813 } 14814 14815 // Finally, we can recurse. 14816 ExprResult CalleeResult = Visit(CalleeExpr); 14817 if (!CalleeResult.isUsable()) return ExprError(); 14818 E->setCallee(CalleeResult.get()); 14819 14820 // Bind a temporary if necessary. 14821 return S.MaybeBindToTemporary(E); 14822 } 14823 14824 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14825 // Verify that this is a legal result type of a call. 14826 if (DestType->isArrayType() || DestType->isFunctionType()) { 14827 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14828 << DestType->isFunctionType() << DestType; 14829 return ExprError(); 14830 } 14831 14832 // Rewrite the method result type if available. 14833 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14834 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14835 Method->setReturnType(DestType); 14836 } 14837 14838 // Change the type of the message. 14839 E->setType(DestType.getNonReferenceType()); 14840 E->setValueKind(Expr::getValueKindForType(DestType)); 14841 14842 return S.MaybeBindToTemporary(E); 14843 } 14844 14845 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14846 // The only case we should ever see here is a function-to-pointer decay. 14847 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14848 assert(E->getValueKind() == VK_RValue); 14849 assert(E->getObjectKind() == OK_Ordinary); 14850 14851 E->setType(DestType); 14852 14853 // Rebuild the sub-expression as the pointee (function) type. 14854 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14855 14856 ExprResult Result = Visit(E->getSubExpr()); 14857 if (!Result.isUsable()) return ExprError(); 14858 14859 E->setSubExpr(Result.get()); 14860 return E; 14861 } else if (E->getCastKind() == CK_LValueToRValue) { 14862 assert(E->getValueKind() == VK_RValue); 14863 assert(E->getObjectKind() == OK_Ordinary); 14864 14865 assert(isa<BlockPointerType>(E->getType())); 14866 14867 E->setType(DestType); 14868 14869 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14870 DestType = S.Context.getLValueReferenceType(DestType); 14871 14872 ExprResult Result = Visit(E->getSubExpr()); 14873 if (!Result.isUsable()) return ExprError(); 14874 14875 E->setSubExpr(Result.get()); 14876 return E; 14877 } else { 14878 llvm_unreachable("Unhandled cast type!"); 14879 } 14880 } 14881 14882 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14883 ExprValueKind ValueKind = VK_LValue; 14884 QualType Type = DestType; 14885 14886 // We know how to make this work for certain kinds of decls: 14887 14888 // - functions 14889 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14890 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14891 DestType = Ptr->getPointeeType(); 14892 ExprResult Result = resolveDecl(E, VD); 14893 if (Result.isInvalid()) return ExprError(); 14894 return S.ImpCastExprToType(Result.get(), Type, 14895 CK_FunctionToPointerDecay, VK_RValue); 14896 } 14897 14898 if (!Type->isFunctionType()) { 14899 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14900 << VD << E->getSourceRange(); 14901 return ExprError(); 14902 } 14903 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14904 // We must match the FunctionDecl's type to the hack introduced in 14905 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14906 // type. See the lengthy commentary in that routine. 14907 QualType FDT = FD->getType(); 14908 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14909 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14910 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14911 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14912 SourceLocation Loc = FD->getLocation(); 14913 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14914 FD->getDeclContext(), 14915 Loc, Loc, FD->getNameInfo().getName(), 14916 DestType, FD->getTypeSourceInfo(), 14917 SC_None, false/*isInlineSpecified*/, 14918 FD->hasPrototype(), 14919 false/*isConstexprSpecified*/); 14920 14921 if (FD->getQualifier()) 14922 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14923 14924 SmallVector<ParmVarDecl*, 16> Params; 14925 for (const auto &AI : FT->param_types()) { 14926 ParmVarDecl *Param = 14927 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14928 Param->setScopeInfo(0, Params.size()); 14929 Params.push_back(Param); 14930 } 14931 NewFD->setParams(Params); 14932 DRE->setDecl(NewFD); 14933 VD = DRE->getDecl(); 14934 } 14935 } 14936 14937 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14938 if (MD->isInstance()) { 14939 ValueKind = VK_RValue; 14940 Type = S.Context.BoundMemberTy; 14941 } 14942 14943 // Function references aren't l-values in C. 14944 if (!S.getLangOpts().CPlusPlus) 14945 ValueKind = VK_RValue; 14946 14947 // - variables 14948 } else if (isa<VarDecl>(VD)) { 14949 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14950 Type = RefTy->getPointeeType(); 14951 } else if (Type->isFunctionType()) { 14952 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14953 << VD << E->getSourceRange(); 14954 return ExprError(); 14955 } 14956 14957 // - nothing else 14958 } else { 14959 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14960 << VD << E->getSourceRange(); 14961 return ExprError(); 14962 } 14963 14964 // Modifying the declaration like this is friendly to IR-gen but 14965 // also really dangerous. 14966 VD->setType(DestType); 14967 E->setType(Type); 14968 E->setValueKind(ValueKind); 14969 return E; 14970 } 14971 14972 /// Check a cast of an unknown-any type. We intentionally only 14973 /// trigger this for C-style casts. 14974 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14975 Expr *CastExpr, CastKind &CastKind, 14976 ExprValueKind &VK, CXXCastPath &Path) { 14977 // The type we're casting to must be either void or complete. 14978 if (!CastType->isVoidType() && 14979 RequireCompleteType(TypeRange.getBegin(), CastType, 14980 diag::err_typecheck_cast_to_incomplete)) 14981 return ExprError(); 14982 14983 // Rewrite the casted expression from scratch. 14984 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14985 if (!result.isUsable()) return ExprError(); 14986 14987 CastExpr = result.get(); 14988 VK = CastExpr->getValueKind(); 14989 CastKind = CK_NoOp; 14990 14991 return CastExpr; 14992 } 14993 14994 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14995 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14996 } 14997 14998 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14999 Expr *arg, QualType ¶mType) { 15000 // If the syntactic form of the argument is not an explicit cast of 15001 // any sort, just do default argument promotion. 15002 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15003 if (!castArg) { 15004 ExprResult result = DefaultArgumentPromotion(arg); 15005 if (result.isInvalid()) return ExprError(); 15006 paramType = result.get()->getType(); 15007 return result; 15008 } 15009 15010 // Otherwise, use the type that was written in the explicit cast. 15011 assert(!arg->hasPlaceholderType()); 15012 paramType = castArg->getTypeAsWritten(); 15013 15014 // Copy-initialize a parameter of that type. 15015 InitializedEntity entity = 15016 InitializedEntity::InitializeParameter(Context, paramType, 15017 /*consumed*/ false); 15018 return PerformCopyInitialization(entity, callLoc, arg); 15019 } 15020 15021 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15022 Expr *orig = E; 15023 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15024 while (true) { 15025 E = E->IgnoreParenImpCasts(); 15026 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15027 E = call->getCallee(); 15028 diagID = diag::err_uncasted_call_of_unknown_any; 15029 } else { 15030 break; 15031 } 15032 } 15033 15034 SourceLocation loc; 15035 NamedDecl *d; 15036 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15037 loc = ref->getLocation(); 15038 d = ref->getDecl(); 15039 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15040 loc = mem->getMemberLoc(); 15041 d = mem->getMemberDecl(); 15042 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15043 diagID = diag::err_uncasted_call_of_unknown_any; 15044 loc = msg->getSelectorStartLoc(); 15045 d = msg->getMethodDecl(); 15046 if (!d) { 15047 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15048 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15049 << orig->getSourceRange(); 15050 return ExprError(); 15051 } 15052 } else { 15053 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15054 << E->getSourceRange(); 15055 return ExprError(); 15056 } 15057 15058 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15059 15060 // Never recoverable. 15061 return ExprError(); 15062 } 15063 15064 /// Check for operands with placeholder types and complain if found. 15065 /// Returns true if there was an error and no recovery was possible. 15066 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15067 if (!getLangOpts().CPlusPlus) { 15068 // C cannot handle TypoExpr nodes on either side of a binop because it 15069 // doesn't handle dependent types properly, so make sure any TypoExprs have 15070 // been dealt with before checking the operands. 15071 ExprResult Result = CorrectDelayedTyposInExpr(E); 15072 if (!Result.isUsable()) return ExprError(); 15073 E = Result.get(); 15074 } 15075 15076 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15077 if (!placeholderType) return E; 15078 15079 switch (placeholderType->getKind()) { 15080 15081 // Overloaded expressions. 15082 case BuiltinType::Overload: { 15083 // Try to resolve a single function template specialization. 15084 // This is obligatory. 15085 ExprResult Result = E; 15086 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15087 return Result; 15088 15089 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15090 // leaves Result unchanged on failure. 15091 Result = E; 15092 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15093 return Result; 15094 15095 // If that failed, try to recover with a call. 15096 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15097 /*complain*/ true); 15098 return Result; 15099 } 15100 15101 // Bound member functions. 15102 case BuiltinType::BoundMember: { 15103 ExprResult result = E; 15104 const Expr *BME = E->IgnoreParens(); 15105 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15106 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15107 if (isa<CXXPseudoDestructorExpr>(BME)) { 15108 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15109 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15110 if (ME->getMemberNameInfo().getName().getNameKind() == 15111 DeclarationName::CXXDestructorName) 15112 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15113 } 15114 tryToRecoverWithCall(result, PD, 15115 /*complain*/ true); 15116 return result; 15117 } 15118 15119 // ARC unbridged casts. 15120 case BuiltinType::ARCUnbridgedCast: { 15121 Expr *realCast = stripARCUnbridgedCast(E); 15122 diagnoseARCUnbridgedCast(realCast); 15123 return realCast; 15124 } 15125 15126 // Expressions of unknown type. 15127 case BuiltinType::UnknownAny: 15128 return diagnoseUnknownAnyExpr(*this, E); 15129 15130 // Pseudo-objects. 15131 case BuiltinType::PseudoObject: 15132 return checkPseudoObjectRValue(E); 15133 15134 case BuiltinType::BuiltinFn: { 15135 // Accept __noop without parens by implicitly converting it to a call expr. 15136 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15137 if (DRE) { 15138 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15139 if (FD->getBuiltinID() == Builtin::BI__noop) { 15140 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15141 CK_BuiltinFnToFnPtr).get(); 15142 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15143 VK_RValue, SourceLocation()); 15144 } 15145 } 15146 15147 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15148 return ExprError(); 15149 } 15150 15151 // Expressions of unknown type. 15152 case BuiltinType::OMPArraySection: 15153 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15154 return ExprError(); 15155 15156 // Everything else should be impossible. 15157 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15158 case BuiltinType::Id: 15159 #include "clang/Basic/OpenCLImageTypes.def" 15160 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15161 #define PLACEHOLDER_TYPE(Id, SingletonId) 15162 #include "clang/AST/BuiltinTypes.def" 15163 break; 15164 } 15165 15166 llvm_unreachable("invalid placeholder type!"); 15167 } 15168 15169 bool Sema::CheckCaseExpression(Expr *E) { 15170 if (E->isTypeDependent()) 15171 return true; 15172 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15173 return E->getType()->isIntegralOrEnumerationType(); 15174 return false; 15175 } 15176 15177 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15178 ExprResult 15179 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15180 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15181 "Unknown Objective-C Boolean value!"); 15182 QualType BoolT = Context.ObjCBuiltinBoolTy; 15183 if (!Context.getBOOLDecl()) { 15184 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15185 Sema::LookupOrdinaryName); 15186 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15187 NamedDecl *ND = Result.getFoundDecl(); 15188 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15189 Context.setBOOLDecl(TD); 15190 } 15191 } 15192 if (Context.getBOOLDecl()) 15193 BoolT = Context.getBOOLType(); 15194 return new (Context) 15195 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15196 } 15197 15198 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15199 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15200 SourceLocation RParen) { 15201 15202 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15203 15204 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15205 [&](const AvailabilitySpec &Spec) { 15206 return Spec.getPlatform() == Platform; 15207 }); 15208 15209 VersionTuple Version; 15210 if (Spec != AvailSpecs.end()) 15211 Version = Spec->getVersion(); 15212 15213 return new (Context) 15214 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15215 } 15216