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 "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.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 static AvailabilityResult 107 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 108 const ObjCInterfaceDecl *UnknownObjCClass, 109 bool ObjCPropertyAccess) { 110 // See if this declaration is unavailable or deprecated. 111 std::string Message; 112 AvailabilityResult Result = D->getAvailability(&Message); 113 114 // For typedefs, if the typedef declaration appears available look 115 // to the underlying type to see if it is more restrictive. 116 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 117 if (Result == AR_Available) { 118 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 119 D = TT->getDecl(); 120 Result = D->getAvailability(&Message); 121 continue; 122 } 123 } 124 break; 125 } 126 127 // Forward class declarations get their attributes from their definition. 128 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 129 if (IDecl->getDefinition()) { 130 D = IDecl->getDefinition(); 131 Result = D->getAvailability(&Message); 132 } 133 } 134 135 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 136 if (Result == AR_Available) { 137 const DeclContext *DC = ECD->getDeclContext(); 138 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 139 Result = TheEnumDecl->getAvailability(&Message); 140 } 141 142 const ObjCPropertyDecl *ObjCPDecl = nullptr; 143 if (Result == AR_Deprecated || Result == AR_Unavailable || 144 Result == AR_NotYetIntroduced) { 145 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 146 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 147 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 148 if (PDeclResult == Result) 149 ObjCPDecl = PD; 150 } 151 } 152 } 153 154 switch (Result) { 155 case AR_Available: 156 break; 157 158 case AR_Deprecated: 159 if (S.getCurContextAvailability() != AR_Deprecated) 160 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 161 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 162 ObjCPropertyAccess); 163 break; 164 165 case AR_NotYetIntroduced: { 166 // Don't do this for enums, they can't be redeclared. 167 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 168 break; 169 170 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 171 // Objective-C method declarations in categories are not modelled as 172 // redeclarations, so manually look for a redeclaration in a category 173 // if necessary. 174 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 175 Warn = false; 176 // In general, D will point to the most recent redeclaration. However, 177 // for `@class A;` decls, this isn't true -- manually go through the 178 // redecl chain in that case. 179 if (Warn && isa<ObjCInterfaceDecl>(D)) 180 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 181 Redecl = Redecl->getPreviousDecl()) 182 if (!Redecl->hasAttr<AvailabilityAttr>() || 183 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 184 Warn = false; 185 186 if (Warn) 187 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 188 UnknownObjCClass, ObjCPDecl, 189 ObjCPropertyAccess); 190 break; 191 } 192 193 case AR_Unavailable: 194 if (S.getCurContextAvailability() != AR_Unavailable) 195 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 196 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 197 ObjCPropertyAccess); 198 break; 199 200 } 201 return Result; 202 } 203 204 /// \brief Emit a note explaining that this function is deleted. 205 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 206 assert(Decl->isDeleted()); 207 208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 209 210 if (Method && Method->isDeleted() && Method->isDefaulted()) { 211 // If the method was explicitly defaulted, point at that declaration. 212 if (!Method->isImplicit()) 213 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 214 215 // Try to diagnose why this special member function was implicitly 216 // deleted. This might fail, if that reason no longer applies. 217 CXXSpecialMember CSM = getSpecialMember(Method); 218 if (CSM != CXXInvalid) 219 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 220 221 return; 222 } 223 224 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 225 if (CXXConstructorDecl *BaseCD = 226 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 227 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 228 if (BaseCD->isDeleted()) { 229 NoteDeletedFunction(BaseCD); 230 } else { 231 // FIXME: An explanation of why exactly it can't be inherited 232 // would be nice. 233 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 234 } 235 return; 236 } 237 } 238 239 Diag(Decl->getLocation(), diag::note_availability_specified_here) 240 << Decl << true; 241 } 242 243 /// \brief Determine whether a FunctionDecl was ever declared with an 244 /// explicit storage class. 245 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 246 for (auto I : D->redecls()) { 247 if (I->getStorageClass() != SC_None) 248 return true; 249 } 250 return false; 251 } 252 253 /// \brief Check whether we're in an extern inline function and referring to a 254 /// variable or function with internal linkage (C11 6.7.4p3). 255 /// 256 /// This is only a warning because we used to silently accept this code, but 257 /// in many cases it will not behave correctly. This is not enabled in C++ mode 258 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 259 /// and so while there may still be user mistakes, most of the time we can't 260 /// prove that there are errors. 261 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 262 const NamedDecl *D, 263 SourceLocation Loc) { 264 // This is disabled under C++; there are too many ways for this to fire in 265 // contexts where the warning is a false positive, or where it is technically 266 // correct but benign. 267 if (S.getLangOpts().CPlusPlus) 268 return; 269 270 // Check if this is an inlined function or method. 271 FunctionDecl *Current = S.getCurFunctionDecl(); 272 if (!Current) 273 return; 274 if (!Current->isInlined()) 275 return; 276 if (!Current->isExternallyVisible()) 277 return; 278 279 // Check if the decl has internal linkage. 280 if (D->getFormalLinkage() != InternalLinkage) 281 return; 282 283 // Downgrade from ExtWarn to Extension if 284 // (1) the supposedly external inline function is in the main file, 285 // and probably won't be included anywhere else. 286 // (2) the thing we're referencing is a pure function. 287 // (3) the thing we're referencing is another inline function. 288 // This last can give us false negatives, but it's better than warning on 289 // wrappers for simple C library functions. 290 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 291 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 292 if (!DowngradeWarning && UsedFn) 293 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 294 295 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 296 : diag::ext_internal_in_extern_inline) 297 << /*IsVar=*/!UsedFn << D; 298 299 S.MaybeSuggestAddingStaticToDecl(Current); 300 301 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 302 << D; 303 } 304 305 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 306 const FunctionDecl *First = Cur->getFirstDecl(); 307 308 // Suggest "static" on the function, if possible. 309 if (!hasAnyExplicitStorageClass(First)) { 310 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 311 Diag(DeclBegin, diag::note_convert_inline_to_static) 312 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 313 } 314 } 315 316 /// \brief Determine whether the use of this declaration is valid, and 317 /// emit any corresponding diagnostics. 318 /// 319 /// This routine diagnoses various problems with referencing 320 /// declarations that can occur when using a declaration. For example, 321 /// it might warn if a deprecated or unavailable declaration is being 322 /// used, or produce an error (and return true) if a C++0x deleted 323 /// function is being used. 324 /// 325 /// \returns true if there was an error (this declaration cannot be 326 /// referenced), false otherwise. 327 /// 328 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 329 const ObjCInterfaceDecl *UnknownObjCClass, 330 bool ObjCPropertyAccess) { 331 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 332 // If there were any diagnostics suppressed by template argument deduction, 333 // emit them now. 334 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 335 if (Pos != SuppressedDiagnostics.end()) { 336 for (const PartialDiagnosticAt &Suppressed : Pos->second) 337 Diag(Suppressed.first, Suppressed.second); 338 339 // Clear out the list of suppressed diagnostics, so that we don't emit 340 // them again for this specialization. However, we don't obsolete this 341 // entry from the table, because we want to avoid ever emitting these 342 // diagnostics again. 343 Pos->second.clear(); 344 } 345 346 // C++ [basic.start.main]p3: 347 // The function 'main' shall not be used within a program. 348 if (cast<FunctionDecl>(D)->isMain()) 349 Diag(Loc, diag::ext_main_used); 350 } 351 352 // See if this is an auto-typed variable whose initializer we are parsing. 353 if (ParsingInitForAutoVars.count(D)) { 354 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 355 356 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 357 << D->getDeclName() << (unsigned)AT->getKeyword(); 358 return true; 359 } 360 361 // See if this is a deleted function. 362 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 363 if (FD->isDeleted()) { 364 Diag(Loc, diag::err_deleted_function_use); 365 NoteDeletedFunction(FD); 366 return true; 367 } 368 369 // If the function has a deduced return type, and we can't deduce it, 370 // then we can't use it either. 371 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 372 DeduceReturnType(FD, Loc)) 373 return true; 374 } 375 376 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 377 // Only the variables omp_in and omp_out are allowed in the combiner. 378 // Only the variables omp_priv and omp_orig are allowed in the 379 // initializer-clause. 380 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 381 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 382 isa<VarDecl>(D)) { 383 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 384 << getCurFunction()->HasOMPDeclareReductionCombiner; 385 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 386 return true; 387 } 388 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 389 ObjCPropertyAccess); 390 391 DiagnoseUnusedOfDecl(*this, D, Loc); 392 393 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 394 395 return false; 396 } 397 398 /// \brief Retrieve the message suffix that should be added to a 399 /// diagnostic complaining about the given function being deleted or 400 /// unavailable. 401 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 402 std::string Message; 403 if (FD->getAvailability(&Message)) 404 return ": " + Message; 405 406 return std::string(); 407 } 408 409 /// DiagnoseSentinelCalls - This routine checks whether a call or 410 /// message-send is to a declaration with the sentinel attribute, and 411 /// if so, it checks that the requirements of the sentinel are 412 /// satisfied. 413 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 414 ArrayRef<Expr *> Args) { 415 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 416 if (!attr) 417 return; 418 419 // The number of formal parameters of the declaration. 420 unsigned numFormalParams; 421 422 // The kind of declaration. This is also an index into a %select in 423 // the diagnostic. 424 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 425 426 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 427 numFormalParams = MD->param_size(); 428 calleeType = CT_Method; 429 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 430 numFormalParams = FD->param_size(); 431 calleeType = CT_Function; 432 } else if (isa<VarDecl>(D)) { 433 QualType type = cast<ValueDecl>(D)->getType(); 434 const FunctionType *fn = nullptr; 435 if (const PointerType *ptr = type->getAs<PointerType>()) { 436 fn = ptr->getPointeeType()->getAs<FunctionType>(); 437 if (!fn) return; 438 calleeType = CT_Function; 439 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 440 fn = ptr->getPointeeType()->castAs<FunctionType>(); 441 calleeType = CT_Block; 442 } else { 443 return; 444 } 445 446 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 447 numFormalParams = proto->getNumParams(); 448 } else { 449 numFormalParams = 0; 450 } 451 } else { 452 return; 453 } 454 455 // "nullPos" is the number of formal parameters at the end which 456 // effectively count as part of the variadic arguments. This is 457 // useful if you would prefer to not have *any* formal parameters, 458 // but the language forces you to have at least one. 459 unsigned nullPos = attr->getNullPos(); 460 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 461 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 462 463 // The number of arguments which should follow the sentinel. 464 unsigned numArgsAfterSentinel = attr->getSentinel(); 465 466 // If there aren't enough arguments for all the formal parameters, 467 // the sentinel, and the args after the sentinel, complain. 468 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 469 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 470 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 471 return; 472 } 473 474 // Otherwise, find the sentinel expression. 475 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 476 if (!sentinelExpr) return; 477 if (sentinelExpr->isValueDependent()) return; 478 if (Context.isSentinelNullExpr(sentinelExpr)) return; 479 480 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 481 // or 'NULL' if those are actually defined in the context. Only use 482 // 'nil' for ObjC methods, where it's much more likely that the 483 // variadic arguments form a list of object pointers. 484 SourceLocation MissingNilLoc 485 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 486 std::string NullValue; 487 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 488 NullValue = "nil"; 489 else if (getLangOpts().CPlusPlus11) 490 NullValue = "nullptr"; 491 else if (PP.isMacroDefined("NULL")) 492 NullValue = "NULL"; 493 else 494 NullValue = "(void*) 0"; 495 496 if (MissingNilLoc.isInvalid()) 497 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 498 else 499 Diag(MissingNilLoc, diag::warn_missing_sentinel) 500 << int(calleeType) 501 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 502 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 503 } 504 505 SourceRange Sema::getExprRange(Expr *E) const { 506 return E ? E->getSourceRange() : SourceRange(); 507 } 508 509 //===----------------------------------------------------------------------===// 510 // Standard Promotions and Conversions 511 //===----------------------------------------------------------------------===// 512 513 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 514 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 515 // Handle any placeholder expressions which made it here. 516 if (E->getType()->isPlaceholderType()) { 517 ExprResult result = CheckPlaceholderExpr(E); 518 if (result.isInvalid()) return ExprError(); 519 E = result.get(); 520 } 521 522 QualType Ty = E->getType(); 523 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 524 525 if (Ty->isFunctionType()) { 526 // If we are here, we are not calling a function but taking 527 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 528 if (getLangOpts().OpenCL) { 529 if (Diagnose) 530 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 531 return ExprError(); 532 } 533 534 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 535 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 536 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 537 return ExprError(); 538 539 E = ImpCastExprToType(E, Context.getPointerType(Ty), 540 CK_FunctionToPointerDecay).get(); 541 } else if (Ty->isArrayType()) { 542 // In C90 mode, arrays only promote to pointers if the array expression is 543 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 544 // type 'array of type' is converted to an expression that has type 'pointer 545 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 546 // that has type 'array of type' ...". The relevant change is "an lvalue" 547 // (C90) to "an expression" (C99). 548 // 549 // C++ 4.2p1: 550 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 551 // T" can be converted to an rvalue of type "pointer to T". 552 // 553 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 554 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 555 CK_ArrayToPointerDecay).get(); 556 } 557 return E; 558 } 559 560 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 561 // Check to see if we are dereferencing a null pointer. If so, 562 // and if not volatile-qualified, this is undefined behavior that the 563 // optimizer will delete, so warn about it. People sometimes try to use this 564 // to get a deterministic trap and are surprised by clang's behavior. This 565 // only handles the pattern "*null", which is a very syntactic check. 566 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 567 if (UO->getOpcode() == UO_Deref && 568 UO->getSubExpr()->IgnoreParenCasts()-> 569 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 570 !UO->getType().isVolatileQualified()) { 571 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 572 S.PDiag(diag::warn_indirection_through_null) 573 << UO->getSubExpr()->getSourceRange()); 574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 575 S.PDiag(diag::note_indirection_through_null)); 576 } 577 } 578 579 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 580 SourceLocation AssignLoc, 581 const Expr* RHS) { 582 const ObjCIvarDecl *IV = OIRE->getDecl(); 583 if (!IV) 584 return; 585 586 DeclarationName MemberName = IV->getDeclName(); 587 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 588 if (!Member || !Member->isStr("isa")) 589 return; 590 591 const Expr *Base = OIRE->getBase(); 592 QualType BaseType = Base->getType(); 593 if (OIRE->isArrow()) 594 BaseType = BaseType->getPointeeType(); 595 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 596 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 597 ObjCInterfaceDecl *ClassDeclared = nullptr; 598 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 599 if (!ClassDeclared->getSuperClass() 600 && (*ClassDeclared->ivar_begin()) == IV) { 601 if (RHS) { 602 NamedDecl *ObjectSetClass = 603 S.LookupSingleName(S.TUScope, 604 &S.Context.Idents.get("object_setClass"), 605 SourceLocation(), S.LookupOrdinaryName); 606 if (ObjectSetClass) { 607 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 609 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 610 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 611 AssignLoc), ",") << 612 FixItHint::CreateInsertion(RHSLocEnd, ")"); 613 } 614 else 615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 616 } else { 617 NamedDecl *ObjectGetClass = 618 S.LookupSingleName(S.TUScope, 619 &S.Context.Idents.get("object_getClass"), 620 SourceLocation(), S.LookupOrdinaryName); 621 if (ObjectGetClass) 622 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 623 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 624 FixItHint::CreateReplacement( 625 SourceRange(OIRE->getOpLoc(), 626 OIRE->getLocEnd()), ")"); 627 else 628 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 629 } 630 S.Diag(IV->getLocation(), diag::note_ivar_decl); 631 } 632 } 633 } 634 635 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 636 // Handle any placeholder expressions which made it here. 637 if (E->getType()->isPlaceholderType()) { 638 ExprResult result = CheckPlaceholderExpr(E); 639 if (result.isInvalid()) return ExprError(); 640 E = result.get(); 641 } 642 643 // C++ [conv.lval]p1: 644 // A glvalue of a non-function, non-array type T can be 645 // converted to a prvalue. 646 if (!E->isGLValue()) return E; 647 648 QualType T = E->getType(); 649 assert(!T.isNull() && "r-value conversion on typeless expression?"); 650 651 // We don't want to throw lvalue-to-rvalue casts on top of 652 // expressions of certain types in C++. 653 if (getLangOpts().CPlusPlus && 654 (E->getType() == Context.OverloadTy || 655 T->isDependentType() || 656 T->isRecordType())) 657 return E; 658 659 // The C standard is actually really unclear on this point, and 660 // DR106 tells us what the result should be but not why. It's 661 // generally best to say that void types just doesn't undergo 662 // lvalue-to-rvalue at all. Note that expressions of unqualified 663 // 'void' type are never l-values, but qualified void can be. 664 if (T->isVoidType()) 665 return E; 666 667 // OpenCL usually rejects direct accesses to values of 'half' type. 668 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 669 T->isHalfType()) { 670 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 671 << 0 << T; 672 return ExprError(); 673 } 674 675 CheckForNullPointerDereference(*this, E); 676 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 677 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 678 &Context.Idents.get("object_getClass"), 679 SourceLocation(), LookupOrdinaryName); 680 if (ObjectGetClass) 681 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 682 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 683 FixItHint::CreateReplacement( 684 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 685 else 686 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 687 } 688 else if (const ObjCIvarRefExpr *OIRE = 689 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 690 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 691 692 // C++ [conv.lval]p1: 693 // [...] If T is a non-class type, the type of the prvalue is the 694 // cv-unqualified version of T. Otherwise, the type of the 695 // rvalue is T. 696 // 697 // C99 6.3.2.1p2: 698 // If the lvalue has qualified type, the value has the unqualified 699 // version of the type of the lvalue; otherwise, the value has the 700 // type of the lvalue. 701 if (T.hasQualifiers()) 702 T = T.getUnqualifiedType(); 703 704 // Under the MS ABI, lock down the inheritance model now. 705 if (T->isMemberPointerType() && 706 Context.getTargetInfo().getCXXABI().isMicrosoft()) 707 (void)isCompleteType(E->getExprLoc(), T); 708 709 UpdateMarkingForLValueToRValue(E); 710 711 // Loading a __weak object implicitly retains the value, so we need a cleanup to 712 // balance that. 713 if (getLangOpts().ObjCAutoRefCount && 714 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 715 ExprNeedsCleanups = true; 716 717 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 718 nullptr, VK_RValue); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_RValue); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay).get(); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 // Half FP have to be promoted to float unless it is natively supported 777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 779 780 // Try to perform integral promotions if the object has a theoretically 781 // promotable type. 782 if (Ty->isIntegralOrUnscopedEnumerationType()) { 783 // C99 6.3.1.1p2: 784 // 785 // The following may be used in an expression wherever an int or 786 // unsigned int may be used: 787 // - an object or expression with an integer type whose integer 788 // conversion rank is less than or equal to the rank of int 789 // and unsigned int. 790 // - A bit-field of type _Bool, int, signed int, or unsigned int. 791 // 792 // If an int can represent all values of the original type, the 793 // value is converted to an int; otherwise, it is converted to an 794 // unsigned int. These are called the integer promotions. All 795 // other types are unchanged by the integer promotions. 796 797 QualType PTy = Context.isPromotableBitField(E); 798 if (!PTy.isNull()) { 799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 800 return E; 801 } 802 if (Ty->isPromotableIntegerType()) { 803 QualType PT = Context.getPromotedIntegerType(Ty); 804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 805 return E; 806 } 807 } 808 return E; 809 } 810 811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 812 /// do not have a prototype. Arguments that have type float or __fp16 813 /// are promoted to double. All other argument types are converted by 814 /// UsualUnaryConversions(). 815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 816 QualType Ty = E->getType(); 817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 818 819 ExprResult Res = UsualUnaryConversions(E); 820 if (Res.isInvalid()) 821 return ExprError(); 822 E = Res.get(); 823 824 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 825 // double. 826 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 827 if (BTy && (BTy->getKind() == BuiltinType::Half || 828 BTy->getKind() == BuiltinType::Float)) 829 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 830 831 // C++ performs lvalue-to-rvalue conversion as a default argument 832 // promotion, even on class types, but note: 833 // C++11 [conv.lval]p2: 834 // When an lvalue-to-rvalue conversion occurs in an unevaluated 835 // operand or a subexpression thereof the value contained in the 836 // referenced object is not accessed. Otherwise, if the glvalue 837 // has a class type, the conversion copy-initializes a temporary 838 // of type T from the glvalue and the result of the conversion 839 // is a prvalue for the temporary. 840 // FIXME: add some way to gate this entire thing for correctness in 841 // potentially potentially evaluated contexts. 842 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 843 ExprResult Temp = PerformCopyInitialization( 844 InitializedEntity::InitializeTemporary(E->getType()), 845 E->getExprLoc(), E); 846 if (Temp.isInvalid()) 847 return ExprError(); 848 E = Temp.get(); 849 } 850 851 return E; 852 } 853 854 /// Determine the degree of POD-ness for an expression. 855 /// Incomplete types are considered POD, since this check can be performed 856 /// when we're in an unevaluated context. 857 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 858 if (Ty->isIncompleteType()) { 859 // C++11 [expr.call]p7: 860 // After these conversions, if the argument does not have arithmetic, 861 // enumeration, pointer, pointer to member, or class type, the program 862 // is ill-formed. 863 // 864 // Since we've already performed array-to-pointer and function-to-pointer 865 // decay, the only such type in C++ is cv void. This also handles 866 // initializer lists as variadic arguments. 867 if (Ty->isVoidType()) 868 return VAK_Invalid; 869 870 if (Ty->isObjCObjectType()) 871 return VAK_Invalid; 872 return VAK_Valid; 873 } 874 875 if (Ty.isCXX98PODType(Context)) 876 return VAK_Valid; 877 878 // C++11 [expr.call]p7: 879 // Passing a potentially-evaluated argument of class type (Clause 9) 880 // having a non-trivial copy constructor, a non-trivial move constructor, 881 // or a non-trivial destructor, with no corresponding parameter, 882 // is conditionally-supported with implementation-defined semantics. 883 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 884 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 885 if (!Record->hasNonTrivialCopyConstructor() && 886 !Record->hasNonTrivialMoveConstructor() && 887 !Record->hasNonTrivialDestructor()) 888 return VAK_ValidInCXX11; 889 890 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 891 return VAK_Valid; 892 893 if (Ty->isObjCObjectType()) 894 return VAK_Invalid; 895 896 if (getLangOpts().MSVCCompat) 897 return VAK_MSVCUndefined; 898 899 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 900 // permitted to reject them. We should consider doing so. 901 return VAK_Undefined; 902 } 903 904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 905 // Don't allow one to pass an Objective-C interface to a vararg. 906 const QualType &Ty = E->getType(); 907 VarArgKind VAK = isValidVarArgType(Ty); 908 909 // Complain about passing non-POD types through varargs. 910 switch (VAK) { 911 case VAK_ValidInCXX11: 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 915 << Ty << CT); 916 // Fall through. 917 case VAK_Valid: 918 if (Ty->isRecordType()) { 919 // This is unlikely to be what the user intended. If the class has a 920 // 'c_str' member function, the user probably meant to call that. 921 DiagRuntimeBehavior(E->getLocStart(), nullptr, 922 PDiag(diag::warn_pass_class_arg_to_vararg) 923 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 924 } 925 break; 926 927 case VAK_Undefined: 928 case VAK_MSVCUndefined: 929 DiagRuntimeBehavior( 930 E->getLocStart(), nullptr, 931 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 932 << getLangOpts().CPlusPlus11 << Ty << CT); 933 break; 934 935 case VAK_Invalid: 936 if (Ty->isObjCObjectType()) 937 DiagRuntimeBehavior( 938 E->getLocStart(), nullptr, 939 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 940 << Ty << CT); 941 else 942 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 943 << isa<InitListExpr>(E) << Ty << CT; 944 break; 945 } 946 } 947 948 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 949 /// will create a trap if the resulting type is not a POD type. 950 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 951 FunctionDecl *FDecl) { 952 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 953 // Strip the unbridged-cast placeholder expression off, if applicable. 954 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 955 (CT == VariadicMethod || 956 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 957 E = stripARCUnbridgedCast(E); 958 959 // Otherwise, do normal placeholder checking. 960 } else { 961 ExprResult ExprRes = CheckPlaceholderExpr(E); 962 if (ExprRes.isInvalid()) 963 return ExprError(); 964 E = ExprRes.get(); 965 } 966 } 967 968 ExprResult ExprRes = DefaultArgumentPromotion(E); 969 if (ExprRes.isInvalid()) 970 return ExprError(); 971 E = ExprRes.get(); 972 973 // Diagnostics regarding non-POD argument types are 974 // emitted along with format string checking in Sema::CheckFunctionCall(). 975 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 976 // Turn this into a trap. 977 CXXScopeSpec SS; 978 SourceLocation TemplateKWLoc; 979 UnqualifiedId Name; 980 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 981 E->getLocStart()); 982 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 983 Name, true, false); 984 if (TrapFn.isInvalid()) 985 return ExprError(); 986 987 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 988 E->getLocStart(), None, 989 E->getLocEnd()); 990 if (Call.isInvalid()) 991 return ExprError(); 992 993 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 994 Call.get(), E); 995 if (Comma.isInvalid()) 996 return ExprError(); 997 return Comma.get(); 998 } 999 1000 if (!getLangOpts().CPlusPlus && 1001 RequireCompleteType(E->getExprLoc(), E->getType(), 1002 diag::err_call_incomplete_argument)) 1003 return ExprError(); 1004 1005 return E; 1006 } 1007 1008 /// \brief Converts an integer to complex float type. Helper function of 1009 /// UsualArithmeticConversions() 1010 /// 1011 /// \return false if the integer expression is an integer type and is 1012 /// successfully converted to the complex type. 1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1014 ExprResult &ComplexExpr, 1015 QualType IntTy, 1016 QualType ComplexTy, 1017 bool SkipCast) { 1018 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1019 if (SkipCast) return false; 1020 if (IntTy->isIntegerType()) { 1021 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1024 CK_FloatingRealToComplex); 1025 } else { 1026 assert(IntTy->isComplexIntegerType()); 1027 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1028 CK_IntegralComplexToFloatingComplex); 1029 } 1030 return false; 1031 } 1032 1033 /// \brief Handle arithmetic conversion with complex types. Helper function of 1034 /// UsualArithmeticConversions() 1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1036 ExprResult &RHS, QualType LHSType, 1037 QualType RHSType, 1038 bool IsCompAssign) { 1039 // if we have an integer operand, the result is the complex type. 1040 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1041 /*skipCast*/false)) 1042 return LHSType; 1043 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1044 /*skipCast*/IsCompAssign)) 1045 return RHSType; 1046 1047 // This handles complex/complex, complex/float, or float/complex. 1048 // When both operands are complex, the shorter operand is converted to the 1049 // type of the longer, and that is the type of the result. This corresponds 1050 // to what is done when combining two real floating-point operands. 1051 // The fun begins when size promotion occur across type domains. 1052 // From H&S 6.3.4: When one operand is complex and the other is a real 1053 // floating-point type, the less precise type is converted, within it's 1054 // real or complex domain, to the precision of the other type. For example, 1055 // when combining a "long double" with a "double _Complex", the 1056 // "double _Complex" is promoted to "long double _Complex". 1057 1058 // Compute the rank of the two types, regardless of whether they are complex. 1059 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1060 1061 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1062 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1063 QualType LHSElementType = 1064 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1065 QualType RHSElementType = 1066 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1067 1068 QualType ResultType = S.Context.getComplexType(LHSElementType); 1069 if (Order < 0) { 1070 // Promote the precision of the LHS if not an assignment. 1071 ResultType = S.Context.getComplexType(RHSElementType); 1072 if (!IsCompAssign) { 1073 if (LHSComplexType) 1074 LHS = 1075 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1076 else 1077 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1078 } 1079 } else if (Order > 0) { 1080 // Promote the precision of the RHS. 1081 if (RHSComplexType) 1082 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1083 else 1084 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1085 } 1086 return ResultType; 1087 } 1088 1089 /// \brief Hande arithmetic conversion from integer to float. Helper function 1090 /// of UsualArithmeticConversions() 1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1092 ExprResult &IntExpr, 1093 QualType FloatTy, QualType IntTy, 1094 bool ConvertFloat, bool ConvertInt) { 1095 if (IntTy->isIntegerType()) { 1096 if (ConvertInt) 1097 // Convert intExpr to the lhs floating point type. 1098 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1099 CK_IntegralToFloating); 1100 return FloatTy; 1101 } 1102 1103 // Convert both sides to the appropriate complex float. 1104 assert(IntTy->isComplexIntegerType()); 1105 QualType result = S.Context.getComplexType(FloatTy); 1106 1107 // _Complex int -> _Complex float 1108 if (ConvertInt) 1109 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1110 CK_IntegralComplexToFloatingComplex); 1111 1112 // float -> _Complex float 1113 if (ConvertFloat) 1114 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1115 CK_FloatingRealToComplex); 1116 1117 return result; 1118 } 1119 1120 /// \brief Handle arithmethic conversion with floating point types. Helper 1121 /// function of UsualArithmeticConversions() 1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1123 ExprResult &RHS, QualType LHSType, 1124 QualType RHSType, bool IsCompAssign) { 1125 bool LHSFloat = LHSType->isRealFloatingType(); 1126 bool RHSFloat = RHSType->isRealFloatingType(); 1127 1128 // If we have two real floating types, convert the smaller operand 1129 // to the bigger result. 1130 if (LHSFloat && RHSFloat) { 1131 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1132 if (order > 0) { 1133 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1134 return LHSType; 1135 } 1136 1137 assert(order < 0 && "illegal float comparison"); 1138 if (!IsCompAssign) 1139 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1140 return RHSType; 1141 } 1142 1143 if (LHSFloat) { 1144 // Half FP has to be promoted to float unless it is natively supported 1145 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1146 LHSType = S.Context.FloatTy; 1147 1148 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1149 /*convertFloat=*/!IsCompAssign, 1150 /*convertInt=*/ true); 1151 } 1152 assert(RHSFloat); 1153 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1154 /*convertInt=*/ true, 1155 /*convertFloat=*/!IsCompAssign); 1156 } 1157 1158 /// \brief Diagnose attempts to convert between __float128 and long double if 1159 /// there is no support for such conversion. Helper function of 1160 /// UsualArithmeticConversions(). 1161 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1162 QualType RHSType) { 1163 /* No issue converting if at least one of the types is not a floating point 1164 type or the two types have the same rank. 1165 */ 1166 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1167 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1168 return false; 1169 1170 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1171 "The remaining types must be floating point types."); 1172 1173 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1174 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1175 1176 QualType LHSElemType = LHSComplex ? 1177 LHSComplex->getElementType() : LHSType; 1178 QualType RHSElemType = RHSComplex ? 1179 RHSComplex->getElementType() : RHSType; 1180 1181 // No issue if the two types have the same representation 1182 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1183 &S.Context.getFloatTypeSemantics(RHSElemType)) 1184 return false; 1185 1186 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1187 RHSElemType == S.Context.LongDoubleTy); 1188 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1189 RHSElemType == S.Context.Float128Ty); 1190 1191 /* We've handled the situation where __float128 and long double have the same 1192 representation. The only other allowable conversion is if long double is 1193 really just double. 1194 */ 1195 return Float128AndLongDouble && 1196 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1197 &llvm::APFloat::IEEEdouble); 1198 } 1199 1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1201 1202 namespace { 1203 /// These helper callbacks are placed in an anonymous namespace to 1204 /// permit their use as function template parameters. 1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1206 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1207 } 1208 1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1210 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1211 CK_IntegralComplexCast); 1212 } 1213 } 1214 1215 /// \brief Handle integer arithmetic conversions. Helper function of 1216 /// UsualArithmeticConversions() 1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1219 ExprResult &RHS, QualType LHSType, 1220 QualType RHSType, bool IsCompAssign) { 1221 // The rules for this case are in C99 6.3.1.8 1222 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1223 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1224 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1225 if (LHSSigned == RHSSigned) { 1226 // Same signedness; use the higher-ranked type 1227 if (order >= 0) { 1228 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1229 return LHSType; 1230 } else if (!IsCompAssign) 1231 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1232 return RHSType; 1233 } else if (order != (LHSSigned ? 1 : -1)) { 1234 // The unsigned type has greater than or equal rank to the 1235 // signed type, so use the unsigned type 1236 if (RHSSigned) { 1237 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1238 return LHSType; 1239 } else if (!IsCompAssign) 1240 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1241 return RHSType; 1242 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1243 // The two types are different widths; if we are here, that 1244 // means the signed type is larger than the unsigned type, so 1245 // use the signed type. 1246 if (LHSSigned) { 1247 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1248 return LHSType; 1249 } else if (!IsCompAssign) 1250 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1251 return RHSType; 1252 } else { 1253 // The signed type is higher-ranked than the unsigned type, 1254 // but isn't actually any bigger (like unsigned int and long 1255 // on most 32-bit systems). Use the unsigned type corresponding 1256 // to the signed type. 1257 QualType result = 1258 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1259 RHS = (*doRHSCast)(S, RHS.get(), result); 1260 if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), result); 1262 return result; 1263 } 1264 } 1265 1266 /// \brief Handle conversions with GCC complex int extension. Helper function 1267 /// of UsualArithmeticConversions() 1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1269 ExprResult &RHS, QualType LHSType, 1270 QualType RHSType, 1271 bool IsCompAssign) { 1272 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1273 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1274 1275 if (LHSComplexInt && RHSComplexInt) { 1276 QualType LHSEltType = LHSComplexInt->getElementType(); 1277 QualType RHSEltType = RHSComplexInt->getElementType(); 1278 QualType ScalarType = 1279 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1280 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1281 1282 return S.Context.getComplexType(ScalarType); 1283 } 1284 1285 if (LHSComplexInt) { 1286 QualType LHSEltType = LHSComplexInt->getElementType(); 1287 QualType ScalarType = 1288 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1289 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1290 QualType ComplexType = S.Context.getComplexType(ScalarType); 1291 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1292 CK_IntegralRealToComplex); 1293 1294 return ComplexType; 1295 } 1296 1297 assert(RHSComplexInt); 1298 1299 QualType RHSEltType = RHSComplexInt->getElementType(); 1300 QualType ScalarType = 1301 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1302 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1303 QualType ComplexType = S.Context.getComplexType(ScalarType); 1304 1305 if (!IsCompAssign) 1306 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1307 CK_IntegralRealToComplex); 1308 return ComplexType; 1309 } 1310 1311 /// UsualArithmeticConversions - Performs various conversions that are common to 1312 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1313 /// routine returns the first non-arithmetic type found. The client is 1314 /// responsible for emitting appropriate error diagnostics. 1315 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1316 bool IsCompAssign) { 1317 if (!IsCompAssign) { 1318 LHS = UsualUnaryConversions(LHS.get()); 1319 if (LHS.isInvalid()) 1320 return QualType(); 1321 } 1322 1323 RHS = UsualUnaryConversions(RHS.get()); 1324 if (RHS.isInvalid()) 1325 return QualType(); 1326 1327 // For conversion purposes, we ignore any qualifiers. 1328 // For example, "const float" and "float" are equivalent. 1329 QualType LHSType = 1330 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1331 QualType RHSType = 1332 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1333 1334 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1335 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1336 LHSType = AtomicLHS->getValueType(); 1337 1338 // If both types are identical, no conversion is needed. 1339 if (LHSType == RHSType) 1340 return LHSType; 1341 1342 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1343 // The caller can deal with this (e.g. pointer + int). 1344 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1345 return QualType(); 1346 1347 // Apply unary and bitfield promotions to the LHS's type. 1348 QualType LHSUnpromotedType = LHSType; 1349 if (LHSType->isPromotableIntegerType()) 1350 LHSType = Context.getPromotedIntegerType(LHSType); 1351 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1352 if (!LHSBitfieldPromoteTy.isNull()) 1353 LHSType = LHSBitfieldPromoteTy; 1354 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1355 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1356 1357 // If both types are identical, no conversion is needed. 1358 if (LHSType == RHSType) 1359 return LHSType; 1360 1361 // At this point, we have two different arithmetic types. 1362 1363 // Diagnose attempts to convert between __float128 and long double where 1364 // such conversions currently can't be handled. 1365 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1366 return QualType(); 1367 1368 // Handle complex types first (C99 6.3.1.8p1). 1369 if (LHSType->isComplexType() || RHSType->isComplexType()) 1370 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1371 IsCompAssign); 1372 1373 // Now handle "real" floating types (i.e. float, double, long double). 1374 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1375 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1376 IsCompAssign); 1377 1378 // Handle GCC complex int extension. 1379 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1380 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1381 IsCompAssign); 1382 1383 // Finally, we have two differing integer types. 1384 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1385 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1386 } 1387 1388 1389 //===----------------------------------------------------------------------===// 1390 // Semantic Analysis for various Expression Types 1391 //===----------------------------------------------------------------------===// 1392 1393 1394 ExprResult 1395 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1396 SourceLocation DefaultLoc, 1397 SourceLocation RParenLoc, 1398 Expr *ControllingExpr, 1399 ArrayRef<ParsedType> ArgTypes, 1400 ArrayRef<Expr *> ArgExprs) { 1401 unsigned NumAssocs = ArgTypes.size(); 1402 assert(NumAssocs == ArgExprs.size()); 1403 1404 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1405 for (unsigned i = 0; i < NumAssocs; ++i) { 1406 if (ArgTypes[i]) 1407 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1408 else 1409 Types[i] = nullptr; 1410 } 1411 1412 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1413 ControllingExpr, 1414 llvm::makeArrayRef(Types, NumAssocs), 1415 ArgExprs); 1416 delete [] Types; 1417 return ER; 1418 } 1419 1420 ExprResult 1421 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1422 SourceLocation DefaultLoc, 1423 SourceLocation RParenLoc, 1424 Expr *ControllingExpr, 1425 ArrayRef<TypeSourceInfo *> Types, 1426 ArrayRef<Expr *> Exprs) { 1427 unsigned NumAssocs = Types.size(); 1428 assert(NumAssocs == Exprs.size()); 1429 1430 // Decay and strip qualifiers for the controlling expression type, and handle 1431 // placeholder type replacement. See committee discussion from WG14 DR423. 1432 { 1433 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1434 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1435 if (R.isInvalid()) 1436 return ExprError(); 1437 ControllingExpr = R.get(); 1438 } 1439 1440 // The controlling expression is an unevaluated operand, so side effects are 1441 // likely unintended. 1442 if (ActiveTemplateInstantiations.empty() && 1443 ControllingExpr->HasSideEffects(Context, false)) 1444 Diag(ControllingExpr->getExprLoc(), 1445 diag::warn_side_effects_unevaluated_context); 1446 1447 bool TypeErrorFound = false, 1448 IsResultDependent = ControllingExpr->isTypeDependent(), 1449 ContainsUnexpandedParameterPack 1450 = ControllingExpr->containsUnexpandedParameterPack(); 1451 1452 for (unsigned i = 0; i < NumAssocs; ++i) { 1453 if (Exprs[i]->containsUnexpandedParameterPack()) 1454 ContainsUnexpandedParameterPack = true; 1455 1456 if (Types[i]) { 1457 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1458 ContainsUnexpandedParameterPack = true; 1459 1460 if (Types[i]->getType()->isDependentType()) { 1461 IsResultDependent = true; 1462 } else { 1463 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1464 // complete object type other than a variably modified type." 1465 unsigned D = 0; 1466 if (Types[i]->getType()->isIncompleteType()) 1467 D = diag::err_assoc_type_incomplete; 1468 else if (!Types[i]->getType()->isObjectType()) 1469 D = diag::err_assoc_type_nonobject; 1470 else if (Types[i]->getType()->isVariablyModifiedType()) 1471 D = diag::err_assoc_type_variably_modified; 1472 1473 if (D != 0) { 1474 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1475 << Types[i]->getTypeLoc().getSourceRange() 1476 << Types[i]->getType(); 1477 TypeErrorFound = true; 1478 } 1479 1480 // C11 6.5.1.1p2 "No two generic associations in the same generic 1481 // selection shall specify compatible types." 1482 for (unsigned j = i+1; j < NumAssocs; ++j) 1483 if (Types[j] && !Types[j]->getType()->isDependentType() && 1484 Context.typesAreCompatible(Types[i]->getType(), 1485 Types[j]->getType())) { 1486 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1487 diag::err_assoc_compatible_types) 1488 << Types[j]->getTypeLoc().getSourceRange() 1489 << Types[j]->getType() 1490 << Types[i]->getType(); 1491 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1492 diag::note_compat_assoc) 1493 << Types[i]->getTypeLoc().getSourceRange() 1494 << Types[i]->getType(); 1495 TypeErrorFound = true; 1496 } 1497 } 1498 } 1499 } 1500 if (TypeErrorFound) 1501 return ExprError(); 1502 1503 // If we determined that the generic selection is result-dependent, don't 1504 // try to compute the result expression. 1505 if (IsResultDependent) 1506 return new (Context) GenericSelectionExpr( 1507 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1508 ContainsUnexpandedParameterPack); 1509 1510 SmallVector<unsigned, 1> CompatIndices; 1511 unsigned DefaultIndex = -1U; 1512 for (unsigned i = 0; i < NumAssocs; ++i) { 1513 if (!Types[i]) 1514 DefaultIndex = i; 1515 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1516 Types[i]->getType())) 1517 CompatIndices.push_back(i); 1518 } 1519 1520 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1521 // type compatible with at most one of the types named in its generic 1522 // association list." 1523 if (CompatIndices.size() > 1) { 1524 // We strip parens here because the controlling expression is typically 1525 // parenthesized in macro definitions. 1526 ControllingExpr = ControllingExpr->IgnoreParens(); 1527 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1528 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1529 << (unsigned) CompatIndices.size(); 1530 for (unsigned I : CompatIndices) { 1531 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1532 diag::note_compat_assoc) 1533 << Types[I]->getTypeLoc().getSourceRange() 1534 << Types[I]->getType(); 1535 } 1536 return ExprError(); 1537 } 1538 1539 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1540 // its controlling expression shall have type compatible with exactly one of 1541 // the types named in its generic association list." 1542 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1543 // We strip parens here because the controlling expression is typically 1544 // parenthesized in macro definitions. 1545 ControllingExpr = ControllingExpr->IgnoreParens(); 1546 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1547 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1548 return ExprError(); 1549 } 1550 1551 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1552 // type name that is compatible with the type of the controlling expression, 1553 // then the result expression of the generic selection is the expression 1554 // in that generic association. Otherwise, the result expression of the 1555 // generic selection is the expression in the default generic association." 1556 unsigned ResultIndex = 1557 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1558 1559 return new (Context) GenericSelectionExpr( 1560 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1561 ContainsUnexpandedParameterPack, ResultIndex); 1562 } 1563 1564 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1565 /// location of the token and the offset of the ud-suffix within it. 1566 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1567 unsigned Offset) { 1568 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1569 S.getLangOpts()); 1570 } 1571 1572 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1573 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1574 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1575 IdentifierInfo *UDSuffix, 1576 SourceLocation UDSuffixLoc, 1577 ArrayRef<Expr*> Args, 1578 SourceLocation LitEndLoc) { 1579 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1580 1581 QualType ArgTy[2]; 1582 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1583 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1584 if (ArgTy[ArgIdx]->isArrayType()) 1585 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1586 } 1587 1588 DeclarationName OpName = 1589 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1590 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1591 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1592 1593 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1594 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1595 /*AllowRaw*/false, /*AllowTemplate*/false, 1596 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1597 return ExprError(); 1598 1599 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1600 } 1601 1602 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1603 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1604 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1605 /// multiple tokens. However, the common case is that StringToks points to one 1606 /// string. 1607 /// 1608 ExprResult 1609 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1610 assert(!StringToks.empty() && "Must have at least one string!"); 1611 1612 StringLiteralParser Literal(StringToks, PP); 1613 if (Literal.hadError) 1614 return ExprError(); 1615 1616 SmallVector<SourceLocation, 4> StringTokLocs; 1617 for (const Token &Tok : StringToks) 1618 StringTokLocs.push_back(Tok.getLocation()); 1619 1620 QualType CharTy = Context.CharTy; 1621 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1622 if (Literal.isWide()) { 1623 CharTy = Context.getWideCharType(); 1624 Kind = StringLiteral::Wide; 1625 } else if (Literal.isUTF8()) { 1626 Kind = StringLiteral::UTF8; 1627 } else if (Literal.isUTF16()) { 1628 CharTy = Context.Char16Ty; 1629 Kind = StringLiteral::UTF16; 1630 } else if (Literal.isUTF32()) { 1631 CharTy = Context.Char32Ty; 1632 Kind = StringLiteral::UTF32; 1633 } else if (Literal.isPascal()) { 1634 CharTy = Context.UnsignedCharTy; 1635 } 1636 1637 QualType CharTyConst = CharTy; 1638 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1639 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1640 CharTyConst.addConst(); 1641 1642 // Get an array type for the string, according to C99 6.4.5. This includes 1643 // the nul terminator character as well as the string length for pascal 1644 // strings. 1645 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1646 llvm::APInt(32, Literal.GetNumStringChars()+1), 1647 ArrayType::Normal, 0); 1648 1649 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1650 if (getLangOpts().OpenCL) { 1651 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1652 } 1653 1654 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1655 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1656 Kind, Literal.Pascal, StrTy, 1657 &StringTokLocs[0], 1658 StringTokLocs.size()); 1659 if (Literal.getUDSuffix().empty()) 1660 return Lit; 1661 1662 // We're building a user-defined literal. 1663 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1664 SourceLocation UDSuffixLoc = 1665 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1666 Literal.getUDSuffixOffset()); 1667 1668 // Make sure we're allowed user-defined literals here. 1669 if (!UDLScope) 1670 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1671 1672 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1673 // operator "" X (str, len) 1674 QualType SizeType = Context.getSizeType(); 1675 1676 DeclarationName OpName = 1677 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1678 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1679 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1680 1681 QualType ArgTy[] = { 1682 Context.getArrayDecayedType(StrTy), SizeType 1683 }; 1684 1685 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1686 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1687 /*AllowRaw*/false, /*AllowTemplate*/false, 1688 /*AllowStringTemplate*/true)) { 1689 1690 case LOLR_Cooked: { 1691 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1692 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1693 StringTokLocs[0]); 1694 Expr *Args[] = { Lit, LenArg }; 1695 1696 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1697 } 1698 1699 case LOLR_StringTemplate: { 1700 TemplateArgumentListInfo ExplicitArgs; 1701 1702 unsigned CharBits = Context.getIntWidth(CharTy); 1703 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1704 llvm::APSInt Value(CharBits, CharIsUnsigned); 1705 1706 TemplateArgument TypeArg(CharTy); 1707 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1708 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1709 1710 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1711 Value = Lit->getCodeUnit(I); 1712 TemplateArgument Arg(Context, Value, CharTy); 1713 TemplateArgumentLocInfo ArgInfo; 1714 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1715 } 1716 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1717 &ExplicitArgs); 1718 } 1719 case LOLR_Raw: 1720 case LOLR_Template: 1721 llvm_unreachable("unexpected literal operator lookup result"); 1722 case LOLR_Error: 1723 return ExprError(); 1724 } 1725 llvm_unreachable("unexpected literal operator lookup result"); 1726 } 1727 1728 ExprResult 1729 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1730 SourceLocation Loc, 1731 const CXXScopeSpec *SS) { 1732 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1733 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1734 } 1735 1736 /// BuildDeclRefExpr - Build an expression that references a 1737 /// declaration that does not require a closure capture. 1738 ExprResult 1739 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1740 const DeclarationNameInfo &NameInfo, 1741 const CXXScopeSpec *SS, NamedDecl *FoundD, 1742 const TemplateArgumentListInfo *TemplateArgs) { 1743 if (getLangOpts().CUDA) 1744 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1745 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1746 if (CheckCUDATarget(Caller, Callee)) { 1747 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1748 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1749 << IdentifyCUDATarget(Caller); 1750 Diag(D->getLocation(), diag::note_previous_decl) 1751 << D->getIdentifier(); 1752 return ExprError(); 1753 } 1754 } 1755 1756 bool RefersToCapturedVariable = 1757 isa<VarDecl>(D) && 1758 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1759 1760 DeclRefExpr *E; 1761 if (isa<VarTemplateSpecializationDecl>(D)) { 1762 VarTemplateSpecializationDecl *VarSpec = 1763 cast<VarTemplateSpecializationDecl>(D); 1764 1765 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1766 : NestedNameSpecifierLoc(), 1767 VarSpec->getTemplateKeywordLoc(), D, 1768 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1769 FoundD, TemplateArgs); 1770 } else { 1771 assert(!TemplateArgs && "No template arguments for non-variable" 1772 " template specialization references"); 1773 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1774 : NestedNameSpecifierLoc(), 1775 SourceLocation(), D, RefersToCapturedVariable, 1776 NameInfo, Ty, VK, FoundD); 1777 } 1778 1779 MarkDeclRefReferenced(E); 1780 1781 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1782 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1783 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1784 recordUseOfEvaluatedWeak(E); 1785 1786 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1787 UnusedPrivateFields.remove(FD); 1788 // Just in case we're building an illegal pointer-to-member. 1789 if (FD->isBitField()) 1790 E->setObjectKind(OK_BitField); 1791 } 1792 1793 return E; 1794 } 1795 1796 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1797 /// possibly a list of template arguments. 1798 /// 1799 /// If this produces template arguments, it is permitted to call 1800 /// DecomposeTemplateName. 1801 /// 1802 /// This actually loses a lot of source location information for 1803 /// non-standard name kinds; we should consider preserving that in 1804 /// some way. 1805 void 1806 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1807 TemplateArgumentListInfo &Buffer, 1808 DeclarationNameInfo &NameInfo, 1809 const TemplateArgumentListInfo *&TemplateArgs) { 1810 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1811 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1812 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1813 1814 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1815 Id.TemplateId->NumArgs); 1816 translateTemplateArguments(TemplateArgsPtr, Buffer); 1817 1818 TemplateName TName = Id.TemplateId->Template.get(); 1819 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1820 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1821 TemplateArgs = &Buffer; 1822 } else { 1823 NameInfo = GetNameFromUnqualifiedId(Id); 1824 TemplateArgs = nullptr; 1825 } 1826 } 1827 1828 static void emitEmptyLookupTypoDiagnostic( 1829 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1830 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1831 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1832 DeclContext *Ctx = 1833 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1834 if (!TC) { 1835 // Emit a special diagnostic for failed member lookups. 1836 // FIXME: computing the declaration context might fail here (?) 1837 if (Ctx) 1838 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1839 << SS.getRange(); 1840 else 1841 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1842 return; 1843 } 1844 1845 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1846 bool DroppedSpecifier = 1847 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1848 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1849 ? diag::note_implicit_param_decl 1850 : diag::note_previous_decl; 1851 if (!Ctx) 1852 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1853 SemaRef.PDiag(NoteID)); 1854 else 1855 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1856 << Typo << Ctx << DroppedSpecifier 1857 << SS.getRange(), 1858 SemaRef.PDiag(NoteID)); 1859 } 1860 1861 /// Diagnose an empty lookup. 1862 /// 1863 /// \return false if new lookup candidates were found 1864 bool 1865 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1866 std::unique_ptr<CorrectionCandidateCallback> CCC, 1867 TemplateArgumentListInfo *ExplicitTemplateArgs, 1868 ArrayRef<Expr *> Args, TypoExpr **Out) { 1869 DeclarationName Name = R.getLookupName(); 1870 1871 unsigned diagnostic = diag::err_undeclared_var_use; 1872 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1873 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1874 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1875 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1876 diagnostic = diag::err_undeclared_use; 1877 diagnostic_suggest = diag::err_undeclared_use_suggest; 1878 } 1879 1880 // If the original lookup was an unqualified lookup, fake an 1881 // unqualified lookup. This is useful when (for example) the 1882 // original lookup would not have found something because it was a 1883 // dependent name. 1884 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1885 while (DC) { 1886 if (isa<CXXRecordDecl>(DC)) { 1887 LookupQualifiedName(R, DC); 1888 1889 if (!R.empty()) { 1890 // Don't give errors about ambiguities in this lookup. 1891 R.suppressDiagnostics(); 1892 1893 // During a default argument instantiation the CurContext points 1894 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1895 // function parameter list, hence add an explicit check. 1896 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1897 ActiveTemplateInstantiations.back().Kind == 1898 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1899 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1900 bool isInstance = CurMethod && 1901 CurMethod->isInstance() && 1902 DC == CurMethod->getParent() && !isDefaultArgument; 1903 1904 // Give a code modification hint to insert 'this->'. 1905 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1906 // Actually quite difficult! 1907 if (getLangOpts().MSVCCompat) 1908 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1909 if (isInstance) { 1910 Diag(R.getNameLoc(), diagnostic) << Name 1911 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1912 CheckCXXThisCapture(R.getNameLoc()); 1913 } else { 1914 Diag(R.getNameLoc(), diagnostic) << Name; 1915 } 1916 1917 // Do we really want to note all of these? 1918 for (NamedDecl *D : R) 1919 Diag(D->getLocation(), diag::note_dependent_var_use); 1920 1921 // Return true if we are inside a default argument instantiation 1922 // and the found name refers to an instance member function, otherwise 1923 // the function calling DiagnoseEmptyLookup will try to create an 1924 // implicit member call and this is wrong for default argument. 1925 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1926 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1927 return true; 1928 } 1929 1930 // Tell the callee to try to recover. 1931 return false; 1932 } 1933 1934 R.clear(); 1935 } 1936 1937 // In Microsoft mode, if we are performing lookup from within a friend 1938 // function definition declared at class scope then we must set 1939 // DC to the lexical parent to be able to search into the parent 1940 // class. 1941 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1942 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1943 DC->getLexicalParent()->isRecord()) 1944 DC = DC->getLexicalParent(); 1945 else 1946 DC = DC->getParent(); 1947 } 1948 1949 // We didn't find anything, so try to correct for a typo. 1950 TypoCorrection Corrected; 1951 if (S && Out) { 1952 SourceLocation TypoLoc = R.getNameLoc(); 1953 assert(!ExplicitTemplateArgs && 1954 "Diagnosing an empty lookup with explicit template args!"); 1955 *Out = CorrectTypoDelayed( 1956 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1957 [=](const TypoCorrection &TC) { 1958 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1959 diagnostic, diagnostic_suggest); 1960 }, 1961 nullptr, CTK_ErrorRecovery); 1962 if (*Out) 1963 return true; 1964 } else if (S && (Corrected = 1965 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1966 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1967 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1968 bool DroppedSpecifier = 1969 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1970 R.setLookupName(Corrected.getCorrection()); 1971 1972 bool AcceptableWithRecovery = false; 1973 bool AcceptableWithoutRecovery = false; 1974 NamedDecl *ND = Corrected.getFoundDecl(); 1975 if (ND) { 1976 if (Corrected.isOverloaded()) { 1977 OverloadCandidateSet OCS(R.getNameLoc(), 1978 OverloadCandidateSet::CSK_Normal); 1979 OverloadCandidateSet::iterator Best; 1980 for (NamedDecl *CD : Corrected) { 1981 if (FunctionTemplateDecl *FTD = 1982 dyn_cast<FunctionTemplateDecl>(CD)) 1983 AddTemplateOverloadCandidate( 1984 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1985 Args, OCS); 1986 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1987 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1988 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1989 Args, OCS); 1990 } 1991 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1992 case OR_Success: 1993 ND = Best->FoundDecl; 1994 Corrected.setCorrectionDecl(ND); 1995 break; 1996 default: 1997 // FIXME: Arbitrarily pick the first declaration for the note. 1998 Corrected.setCorrectionDecl(ND); 1999 break; 2000 } 2001 } 2002 R.addDecl(ND); 2003 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2004 CXXRecordDecl *Record = nullptr; 2005 if (Corrected.getCorrectionSpecifier()) { 2006 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2007 Record = Ty->getAsCXXRecordDecl(); 2008 } 2009 if (!Record) 2010 Record = cast<CXXRecordDecl>( 2011 ND->getDeclContext()->getRedeclContext()); 2012 R.setNamingClass(Record); 2013 } 2014 2015 auto *UnderlyingND = ND->getUnderlyingDecl(); 2016 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2017 isa<FunctionTemplateDecl>(UnderlyingND); 2018 // FIXME: If we ended up with a typo for a type name or 2019 // Objective-C class name, we're in trouble because the parser 2020 // is in the wrong place to recover. Suggest the typo 2021 // correction, but don't make it a fix-it since we're not going 2022 // to recover well anyway. 2023 AcceptableWithoutRecovery = 2024 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2025 } else { 2026 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2027 // because we aren't able to recover. 2028 AcceptableWithoutRecovery = true; 2029 } 2030 2031 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2032 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2033 ? diag::note_implicit_param_decl 2034 : diag::note_previous_decl; 2035 if (SS.isEmpty()) 2036 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2037 PDiag(NoteID), AcceptableWithRecovery); 2038 else 2039 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2040 << Name << computeDeclContext(SS, false) 2041 << DroppedSpecifier << SS.getRange(), 2042 PDiag(NoteID), AcceptableWithRecovery); 2043 2044 // Tell the callee whether to try to recover. 2045 return !AcceptableWithRecovery; 2046 } 2047 } 2048 R.clear(); 2049 2050 // Emit a special diagnostic for failed member lookups. 2051 // FIXME: computing the declaration context might fail here (?) 2052 if (!SS.isEmpty()) { 2053 Diag(R.getNameLoc(), diag::err_no_member) 2054 << Name << computeDeclContext(SS, false) 2055 << SS.getRange(); 2056 return true; 2057 } 2058 2059 // Give up, we can't recover. 2060 Diag(R.getNameLoc(), diagnostic) << Name; 2061 return true; 2062 } 2063 2064 /// In Microsoft mode, if we are inside a template class whose parent class has 2065 /// dependent base classes, and we can't resolve an unqualified identifier, then 2066 /// assume the identifier is a member of a dependent base class. We can only 2067 /// recover successfully in static methods, instance methods, and other contexts 2068 /// where 'this' is available. This doesn't precisely match MSVC's 2069 /// instantiation model, but it's close enough. 2070 static Expr * 2071 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2072 DeclarationNameInfo &NameInfo, 2073 SourceLocation TemplateKWLoc, 2074 const TemplateArgumentListInfo *TemplateArgs) { 2075 // Only try to recover from lookup into dependent bases in static methods or 2076 // contexts where 'this' is available. 2077 QualType ThisType = S.getCurrentThisType(); 2078 const CXXRecordDecl *RD = nullptr; 2079 if (!ThisType.isNull()) 2080 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2081 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2082 RD = MD->getParent(); 2083 if (!RD || !RD->hasAnyDependentBases()) 2084 return nullptr; 2085 2086 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2087 // is available, suggest inserting 'this->' as a fixit. 2088 SourceLocation Loc = NameInfo.getLoc(); 2089 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2090 DB << NameInfo.getName() << RD; 2091 2092 if (!ThisType.isNull()) { 2093 DB << FixItHint::CreateInsertion(Loc, "this->"); 2094 return CXXDependentScopeMemberExpr::Create( 2095 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2096 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2097 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2098 } 2099 2100 // Synthesize a fake NNS that points to the derived class. This will 2101 // perform name lookup during template instantiation. 2102 CXXScopeSpec SS; 2103 auto *NNS = 2104 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2105 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2106 return DependentScopeDeclRefExpr::Create( 2107 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2108 TemplateArgs); 2109 } 2110 2111 ExprResult 2112 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2113 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2114 bool HasTrailingLParen, bool IsAddressOfOperand, 2115 std::unique_ptr<CorrectionCandidateCallback> CCC, 2116 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2117 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2118 "cannot be direct & operand and have a trailing lparen"); 2119 if (SS.isInvalid()) 2120 return ExprError(); 2121 2122 TemplateArgumentListInfo TemplateArgsBuffer; 2123 2124 // Decompose the UnqualifiedId into the following data. 2125 DeclarationNameInfo NameInfo; 2126 const TemplateArgumentListInfo *TemplateArgs; 2127 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2128 2129 DeclarationName Name = NameInfo.getName(); 2130 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2131 SourceLocation NameLoc = NameInfo.getLoc(); 2132 2133 // C++ [temp.dep.expr]p3: 2134 // An id-expression is type-dependent if it contains: 2135 // -- an identifier that was declared with a dependent type, 2136 // (note: handled after lookup) 2137 // -- a template-id that is dependent, 2138 // (note: handled in BuildTemplateIdExpr) 2139 // -- a conversion-function-id that specifies a dependent type, 2140 // -- a nested-name-specifier that contains a class-name that 2141 // names a dependent type. 2142 // Determine whether this is a member of an unknown specialization; 2143 // we need to handle these differently. 2144 bool DependentID = false; 2145 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2146 Name.getCXXNameType()->isDependentType()) { 2147 DependentID = true; 2148 } else if (SS.isSet()) { 2149 if (DeclContext *DC = computeDeclContext(SS, false)) { 2150 if (RequireCompleteDeclContext(SS, DC)) 2151 return ExprError(); 2152 } else { 2153 DependentID = true; 2154 } 2155 } 2156 2157 if (DependentID) 2158 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2159 IsAddressOfOperand, TemplateArgs); 2160 2161 // Perform the required lookup. 2162 LookupResult R(*this, NameInfo, 2163 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2164 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2165 if (TemplateArgs) { 2166 // Lookup the template name again to correctly establish the context in 2167 // which it was found. This is really unfortunate as we already did the 2168 // lookup to determine that it was a template name in the first place. If 2169 // this becomes a performance hit, we can work harder to preserve those 2170 // results until we get here but it's likely not worth it. 2171 bool MemberOfUnknownSpecialization; 2172 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2173 MemberOfUnknownSpecialization); 2174 2175 if (MemberOfUnknownSpecialization || 2176 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2177 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2178 IsAddressOfOperand, TemplateArgs); 2179 } else { 2180 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2181 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2182 2183 // If the result might be in a dependent base class, this is a dependent 2184 // id-expression. 2185 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2186 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2187 IsAddressOfOperand, TemplateArgs); 2188 2189 // If this reference is in an Objective-C method, then we need to do 2190 // some special Objective-C lookup, too. 2191 if (IvarLookupFollowUp) { 2192 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2193 if (E.isInvalid()) 2194 return ExprError(); 2195 2196 if (Expr *Ex = E.getAs<Expr>()) 2197 return Ex; 2198 } 2199 } 2200 2201 if (R.isAmbiguous()) 2202 return ExprError(); 2203 2204 // This could be an implicitly declared function reference (legal in C90, 2205 // extension in C99, forbidden in C++). 2206 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2207 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2208 if (D) R.addDecl(D); 2209 } 2210 2211 // Determine whether this name might be a candidate for 2212 // argument-dependent lookup. 2213 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2214 2215 if (R.empty() && !ADL) { 2216 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2217 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2218 TemplateKWLoc, TemplateArgs)) 2219 return E; 2220 } 2221 2222 // Don't diagnose an empty lookup for inline assembly. 2223 if (IsInlineAsmIdentifier) 2224 return ExprError(); 2225 2226 // If this name wasn't predeclared and if this is not a function 2227 // call, diagnose the problem. 2228 TypoExpr *TE = nullptr; 2229 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2230 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2231 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2232 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2233 "Typo correction callback misconfigured"); 2234 if (CCC) { 2235 // Make sure the callback knows what the typo being diagnosed is. 2236 CCC->setTypoName(II); 2237 if (SS.isValid()) 2238 CCC->setTypoNNS(SS.getScopeRep()); 2239 } 2240 if (DiagnoseEmptyLookup(S, SS, R, 2241 CCC ? std::move(CCC) : std::move(DefaultValidator), 2242 nullptr, None, &TE)) { 2243 if (TE && KeywordReplacement) { 2244 auto &State = getTypoExprState(TE); 2245 auto BestTC = State.Consumer->getNextCorrection(); 2246 if (BestTC.isKeyword()) { 2247 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2248 if (State.DiagHandler) 2249 State.DiagHandler(BestTC); 2250 KeywordReplacement->startToken(); 2251 KeywordReplacement->setKind(II->getTokenID()); 2252 KeywordReplacement->setIdentifierInfo(II); 2253 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2254 // Clean up the state associated with the TypoExpr, since it has 2255 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2256 clearDelayedTypo(TE); 2257 // Signal that a correction to a keyword was performed by returning a 2258 // valid-but-null ExprResult. 2259 return (Expr*)nullptr; 2260 } 2261 State.Consumer->resetCorrectionStream(); 2262 } 2263 return TE ? TE : ExprError(); 2264 } 2265 2266 assert(!R.empty() && 2267 "DiagnoseEmptyLookup returned false but added no results"); 2268 2269 // If we found an Objective-C instance variable, let 2270 // LookupInObjCMethod build the appropriate expression to 2271 // reference the ivar. 2272 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2273 R.clear(); 2274 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2275 // In a hopelessly buggy code, Objective-C instance variable 2276 // lookup fails and no expression will be built to reference it. 2277 if (!E.isInvalid() && !E.get()) 2278 return ExprError(); 2279 return E; 2280 } 2281 } 2282 2283 // This is guaranteed from this point on. 2284 assert(!R.empty() || ADL); 2285 2286 // Check whether this might be a C++ implicit instance member access. 2287 // C++ [class.mfct.non-static]p3: 2288 // When an id-expression that is not part of a class member access 2289 // syntax and not used to form a pointer to member is used in the 2290 // body of a non-static member function of class X, if name lookup 2291 // resolves the name in the id-expression to a non-static non-type 2292 // member of some class C, the id-expression is transformed into a 2293 // class member access expression using (*this) as the 2294 // postfix-expression to the left of the . operator. 2295 // 2296 // But we don't actually need to do this for '&' operands if R 2297 // resolved to a function or overloaded function set, because the 2298 // expression is ill-formed if it actually works out to be a 2299 // non-static member function: 2300 // 2301 // C++ [expr.ref]p4: 2302 // Otherwise, if E1.E2 refers to a non-static member function. . . 2303 // [t]he expression can be used only as the left-hand operand of a 2304 // member function call. 2305 // 2306 // There are other safeguards against such uses, but it's important 2307 // to get this right here so that we don't end up making a 2308 // spuriously dependent expression if we're inside a dependent 2309 // instance method. 2310 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2311 bool MightBeImplicitMember; 2312 if (!IsAddressOfOperand) 2313 MightBeImplicitMember = true; 2314 else if (!SS.isEmpty()) 2315 MightBeImplicitMember = false; 2316 else if (R.isOverloadedResult()) 2317 MightBeImplicitMember = false; 2318 else if (R.isUnresolvableResult()) 2319 MightBeImplicitMember = true; 2320 else 2321 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2322 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2323 isa<MSPropertyDecl>(R.getFoundDecl()); 2324 2325 if (MightBeImplicitMember) 2326 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2327 R, TemplateArgs, S); 2328 } 2329 2330 if (TemplateArgs || TemplateKWLoc.isValid()) { 2331 2332 // In C++1y, if this is a variable template id, then check it 2333 // in BuildTemplateIdExpr(). 2334 // The single lookup result must be a variable template declaration. 2335 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2336 Id.TemplateId->Kind == TNK_Var_template) { 2337 assert(R.getAsSingle<VarTemplateDecl>() && 2338 "There should only be one declaration found."); 2339 } 2340 2341 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2342 } 2343 2344 return BuildDeclarationNameExpr(SS, R, ADL); 2345 } 2346 2347 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2348 /// declaration name, generally during template instantiation. 2349 /// There's a large number of things which don't need to be done along 2350 /// this path. 2351 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2352 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2353 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2354 DeclContext *DC = computeDeclContext(SS, false); 2355 if (!DC) 2356 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2357 NameInfo, /*TemplateArgs=*/nullptr); 2358 2359 if (RequireCompleteDeclContext(SS, DC)) 2360 return ExprError(); 2361 2362 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2363 LookupQualifiedName(R, DC); 2364 2365 if (R.isAmbiguous()) 2366 return ExprError(); 2367 2368 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2369 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2370 NameInfo, /*TemplateArgs=*/nullptr); 2371 2372 if (R.empty()) { 2373 Diag(NameInfo.getLoc(), diag::err_no_member) 2374 << NameInfo.getName() << DC << SS.getRange(); 2375 return ExprError(); 2376 } 2377 2378 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2379 // Diagnose a missing typename if this resolved unambiguously to a type in 2380 // a dependent context. If we can recover with a type, downgrade this to 2381 // a warning in Microsoft compatibility mode. 2382 unsigned DiagID = diag::err_typename_missing; 2383 if (RecoveryTSI && getLangOpts().MSVCCompat) 2384 DiagID = diag::ext_typename_missing; 2385 SourceLocation Loc = SS.getBeginLoc(); 2386 auto D = Diag(Loc, DiagID); 2387 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2388 << SourceRange(Loc, NameInfo.getEndLoc()); 2389 2390 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2391 // context. 2392 if (!RecoveryTSI) 2393 return ExprError(); 2394 2395 // Only issue the fixit if we're prepared to recover. 2396 D << FixItHint::CreateInsertion(Loc, "typename "); 2397 2398 // Recover by pretending this was an elaborated type. 2399 QualType Ty = Context.getTypeDeclType(TD); 2400 TypeLocBuilder TLB; 2401 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2402 2403 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2404 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2405 QTL.setElaboratedKeywordLoc(SourceLocation()); 2406 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2407 2408 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2409 2410 return ExprEmpty(); 2411 } 2412 2413 // Defend against this resolving to an implicit member access. We usually 2414 // won't get here if this might be a legitimate a class member (we end up in 2415 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2416 // a pointer-to-member or in an unevaluated context in C++11. 2417 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2418 return BuildPossibleImplicitMemberExpr(SS, 2419 /*TemplateKWLoc=*/SourceLocation(), 2420 R, /*TemplateArgs=*/nullptr, S); 2421 2422 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2423 } 2424 2425 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2426 /// detected that we're currently inside an ObjC method. Perform some 2427 /// additional lookup. 2428 /// 2429 /// Ideally, most of this would be done by lookup, but there's 2430 /// actually quite a lot of extra work involved. 2431 /// 2432 /// Returns a null sentinel to indicate trivial success. 2433 ExprResult 2434 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2435 IdentifierInfo *II, bool AllowBuiltinCreation) { 2436 SourceLocation Loc = Lookup.getNameLoc(); 2437 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2438 2439 // Check for error condition which is already reported. 2440 if (!CurMethod) 2441 return ExprError(); 2442 2443 // There are two cases to handle here. 1) scoped lookup could have failed, 2444 // in which case we should look for an ivar. 2) scoped lookup could have 2445 // found a decl, but that decl is outside the current instance method (i.e. 2446 // a global variable). In these two cases, we do a lookup for an ivar with 2447 // this name, if the lookup sucedes, we replace it our current decl. 2448 2449 // If we're in a class method, we don't normally want to look for 2450 // ivars. But if we don't find anything else, and there's an 2451 // ivar, that's an error. 2452 bool IsClassMethod = CurMethod->isClassMethod(); 2453 2454 bool LookForIvars; 2455 if (Lookup.empty()) 2456 LookForIvars = true; 2457 else if (IsClassMethod) 2458 LookForIvars = false; 2459 else 2460 LookForIvars = (Lookup.isSingleResult() && 2461 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2462 ObjCInterfaceDecl *IFace = nullptr; 2463 if (LookForIvars) { 2464 IFace = CurMethod->getClassInterface(); 2465 ObjCInterfaceDecl *ClassDeclared; 2466 ObjCIvarDecl *IV = nullptr; 2467 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2468 // Diagnose using an ivar in a class method. 2469 if (IsClassMethod) 2470 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2471 << IV->getDeclName()); 2472 2473 // If we're referencing an invalid decl, just return this as a silent 2474 // error node. The error diagnostic was already emitted on the decl. 2475 if (IV->isInvalidDecl()) 2476 return ExprError(); 2477 2478 // Check if referencing a field with __attribute__((deprecated)). 2479 if (DiagnoseUseOfDecl(IV, Loc)) 2480 return ExprError(); 2481 2482 // Diagnose the use of an ivar outside of the declaring class. 2483 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2484 !declaresSameEntity(ClassDeclared, IFace) && 2485 !getLangOpts().DebuggerSupport) 2486 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2487 2488 // FIXME: This should use a new expr for a direct reference, don't 2489 // turn this into Self->ivar, just return a BareIVarExpr or something. 2490 IdentifierInfo &II = Context.Idents.get("self"); 2491 UnqualifiedId SelfName; 2492 SelfName.setIdentifier(&II, SourceLocation()); 2493 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2494 CXXScopeSpec SelfScopeSpec; 2495 SourceLocation TemplateKWLoc; 2496 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2497 SelfName, false, false); 2498 if (SelfExpr.isInvalid()) 2499 return ExprError(); 2500 2501 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2502 if (SelfExpr.isInvalid()) 2503 return ExprError(); 2504 2505 MarkAnyDeclReferenced(Loc, IV, true); 2506 2507 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2508 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2509 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2510 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2511 2512 ObjCIvarRefExpr *Result = new (Context) 2513 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2514 IV->getLocation(), SelfExpr.get(), true, true); 2515 2516 if (getLangOpts().ObjCAutoRefCount) { 2517 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2518 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2519 recordUseOfEvaluatedWeak(Result); 2520 } 2521 if (CurContext->isClosure()) 2522 Diag(Loc, diag::warn_implicitly_retains_self) 2523 << FixItHint::CreateInsertion(Loc, "self->"); 2524 } 2525 2526 return Result; 2527 } 2528 } else if (CurMethod->isInstanceMethod()) { 2529 // We should warn if a local variable hides an ivar. 2530 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2531 ObjCInterfaceDecl *ClassDeclared; 2532 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2533 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2534 declaresSameEntity(IFace, ClassDeclared)) 2535 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2536 } 2537 } 2538 } else if (Lookup.isSingleResult() && 2539 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2540 // If accessing a stand-alone ivar in a class method, this is an error. 2541 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2542 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2543 << IV->getDeclName()); 2544 } 2545 2546 if (Lookup.empty() && II && AllowBuiltinCreation) { 2547 // FIXME. Consolidate this with similar code in LookupName. 2548 if (unsigned BuiltinID = II->getBuiltinID()) { 2549 if (!(getLangOpts().CPlusPlus && 2550 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2551 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2552 S, Lookup.isForRedeclaration(), 2553 Lookup.getNameLoc()); 2554 if (D) Lookup.addDecl(D); 2555 } 2556 } 2557 } 2558 // Sentinel value saying that we didn't do anything special. 2559 return ExprResult((Expr *)nullptr); 2560 } 2561 2562 /// \brief Cast a base object to a member's actual type. 2563 /// 2564 /// Logically this happens in three phases: 2565 /// 2566 /// * First we cast from the base type to the naming class. 2567 /// The naming class is the class into which we were looking 2568 /// when we found the member; it's the qualifier type if a 2569 /// qualifier was provided, and otherwise it's the base type. 2570 /// 2571 /// * Next we cast from the naming class to the declaring class. 2572 /// If the member we found was brought into a class's scope by 2573 /// a using declaration, this is that class; otherwise it's 2574 /// the class declaring the member. 2575 /// 2576 /// * Finally we cast from the declaring class to the "true" 2577 /// declaring class of the member. This conversion does not 2578 /// obey access control. 2579 ExprResult 2580 Sema::PerformObjectMemberConversion(Expr *From, 2581 NestedNameSpecifier *Qualifier, 2582 NamedDecl *FoundDecl, 2583 NamedDecl *Member) { 2584 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2585 if (!RD) 2586 return From; 2587 2588 QualType DestRecordType; 2589 QualType DestType; 2590 QualType FromRecordType; 2591 QualType FromType = From->getType(); 2592 bool PointerConversions = false; 2593 if (isa<FieldDecl>(Member)) { 2594 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2595 2596 if (FromType->getAs<PointerType>()) { 2597 DestType = Context.getPointerType(DestRecordType); 2598 FromRecordType = FromType->getPointeeType(); 2599 PointerConversions = true; 2600 } else { 2601 DestType = DestRecordType; 2602 FromRecordType = FromType; 2603 } 2604 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2605 if (Method->isStatic()) 2606 return From; 2607 2608 DestType = Method->getThisType(Context); 2609 DestRecordType = DestType->getPointeeType(); 2610 2611 if (FromType->getAs<PointerType>()) { 2612 FromRecordType = FromType->getPointeeType(); 2613 PointerConversions = true; 2614 } else { 2615 FromRecordType = FromType; 2616 DestType = DestRecordType; 2617 } 2618 } else { 2619 // No conversion necessary. 2620 return From; 2621 } 2622 2623 if (DestType->isDependentType() || FromType->isDependentType()) 2624 return From; 2625 2626 // If the unqualified types are the same, no conversion is necessary. 2627 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2628 return From; 2629 2630 SourceRange FromRange = From->getSourceRange(); 2631 SourceLocation FromLoc = FromRange.getBegin(); 2632 2633 ExprValueKind VK = From->getValueKind(); 2634 2635 // C++ [class.member.lookup]p8: 2636 // [...] Ambiguities can often be resolved by qualifying a name with its 2637 // class name. 2638 // 2639 // If the member was a qualified name and the qualified referred to a 2640 // specific base subobject type, we'll cast to that intermediate type 2641 // first and then to the object in which the member is declared. That allows 2642 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2643 // 2644 // class Base { public: int x; }; 2645 // class Derived1 : public Base { }; 2646 // class Derived2 : public Base { }; 2647 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2648 // 2649 // void VeryDerived::f() { 2650 // x = 17; // error: ambiguous base subobjects 2651 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2652 // } 2653 if (Qualifier && Qualifier->getAsType()) { 2654 QualType QType = QualType(Qualifier->getAsType(), 0); 2655 assert(QType->isRecordType() && "lookup done with non-record type"); 2656 2657 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2658 2659 // In C++98, the qualifier type doesn't actually have to be a base 2660 // type of the object type, in which case we just ignore it. 2661 // Otherwise build the appropriate casts. 2662 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2663 CXXCastPath BasePath; 2664 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2665 FromLoc, FromRange, &BasePath)) 2666 return ExprError(); 2667 2668 if (PointerConversions) 2669 QType = Context.getPointerType(QType); 2670 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2671 VK, &BasePath).get(); 2672 2673 FromType = QType; 2674 FromRecordType = QRecordType; 2675 2676 // If the qualifier type was the same as the destination type, 2677 // we're done. 2678 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2679 return From; 2680 } 2681 } 2682 2683 bool IgnoreAccess = false; 2684 2685 // If we actually found the member through a using declaration, cast 2686 // down to the using declaration's type. 2687 // 2688 // Pointer equality is fine here because only one declaration of a 2689 // class ever has member declarations. 2690 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2691 assert(isa<UsingShadowDecl>(FoundDecl)); 2692 QualType URecordType = Context.getTypeDeclType( 2693 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2694 2695 // We only need to do this if the naming-class to declaring-class 2696 // conversion is non-trivial. 2697 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2698 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2699 CXXCastPath BasePath; 2700 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2701 FromLoc, FromRange, &BasePath)) 2702 return ExprError(); 2703 2704 QualType UType = URecordType; 2705 if (PointerConversions) 2706 UType = Context.getPointerType(UType); 2707 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2708 VK, &BasePath).get(); 2709 FromType = UType; 2710 FromRecordType = URecordType; 2711 } 2712 2713 // We don't do access control for the conversion from the 2714 // declaring class to the true declaring class. 2715 IgnoreAccess = true; 2716 } 2717 2718 CXXCastPath BasePath; 2719 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2720 FromLoc, FromRange, &BasePath, 2721 IgnoreAccess)) 2722 return ExprError(); 2723 2724 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2725 VK, &BasePath); 2726 } 2727 2728 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2729 const LookupResult &R, 2730 bool HasTrailingLParen) { 2731 // Only when used directly as the postfix-expression of a call. 2732 if (!HasTrailingLParen) 2733 return false; 2734 2735 // Never if a scope specifier was provided. 2736 if (SS.isSet()) 2737 return false; 2738 2739 // Only in C++ or ObjC++. 2740 if (!getLangOpts().CPlusPlus) 2741 return false; 2742 2743 // Turn off ADL when we find certain kinds of declarations during 2744 // normal lookup: 2745 for (NamedDecl *D : R) { 2746 // C++0x [basic.lookup.argdep]p3: 2747 // -- a declaration of a class member 2748 // Since using decls preserve this property, we check this on the 2749 // original decl. 2750 if (D->isCXXClassMember()) 2751 return false; 2752 2753 // C++0x [basic.lookup.argdep]p3: 2754 // -- a block-scope function declaration that is not a 2755 // using-declaration 2756 // NOTE: we also trigger this for function templates (in fact, we 2757 // don't check the decl type at all, since all other decl types 2758 // turn off ADL anyway). 2759 if (isa<UsingShadowDecl>(D)) 2760 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2761 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2762 return false; 2763 2764 // C++0x [basic.lookup.argdep]p3: 2765 // -- a declaration that is neither a function or a function 2766 // template 2767 // And also for builtin functions. 2768 if (isa<FunctionDecl>(D)) { 2769 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2770 2771 // But also builtin functions. 2772 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2773 return false; 2774 } else if (!isa<FunctionTemplateDecl>(D)) 2775 return false; 2776 } 2777 2778 return true; 2779 } 2780 2781 2782 /// Diagnoses obvious problems with the use of the given declaration 2783 /// as an expression. This is only actually called for lookups that 2784 /// were not overloaded, and it doesn't promise that the declaration 2785 /// will in fact be used. 2786 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2787 if (isa<TypedefNameDecl>(D)) { 2788 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2789 return true; 2790 } 2791 2792 if (isa<ObjCInterfaceDecl>(D)) { 2793 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2794 return true; 2795 } 2796 2797 if (isa<NamespaceDecl>(D)) { 2798 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2799 return true; 2800 } 2801 2802 return false; 2803 } 2804 2805 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2806 LookupResult &R, bool NeedsADL, 2807 bool AcceptInvalidDecl) { 2808 // If this is a single, fully-resolved result and we don't need ADL, 2809 // just build an ordinary singleton decl ref. 2810 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2811 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2812 R.getRepresentativeDecl(), nullptr, 2813 AcceptInvalidDecl); 2814 2815 // We only need to check the declaration if there's exactly one 2816 // result, because in the overloaded case the results can only be 2817 // functions and function templates. 2818 if (R.isSingleResult() && 2819 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2820 return ExprError(); 2821 2822 // Otherwise, just build an unresolved lookup expression. Suppress 2823 // any lookup-related diagnostics; we'll hash these out later, when 2824 // we've picked a target. 2825 R.suppressDiagnostics(); 2826 2827 UnresolvedLookupExpr *ULE 2828 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2829 SS.getWithLocInContext(Context), 2830 R.getLookupNameInfo(), 2831 NeedsADL, R.isOverloadedResult(), 2832 R.begin(), R.end()); 2833 2834 return ULE; 2835 } 2836 2837 /// \brief Complete semantic analysis for a reference to the given declaration. 2838 ExprResult Sema::BuildDeclarationNameExpr( 2839 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2840 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2841 bool AcceptInvalidDecl) { 2842 assert(D && "Cannot refer to a NULL declaration"); 2843 assert(!isa<FunctionTemplateDecl>(D) && 2844 "Cannot refer unambiguously to a function template"); 2845 2846 SourceLocation Loc = NameInfo.getLoc(); 2847 if (CheckDeclInExpr(*this, Loc, D)) 2848 return ExprError(); 2849 2850 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2851 // Specifically diagnose references to class templates that are missing 2852 // a template argument list. 2853 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2854 << Template << SS.getRange(); 2855 Diag(Template->getLocation(), diag::note_template_decl_here); 2856 return ExprError(); 2857 } 2858 2859 // Make sure that we're referring to a value. 2860 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2861 if (!VD) { 2862 Diag(Loc, diag::err_ref_non_value) 2863 << D << SS.getRange(); 2864 Diag(D->getLocation(), diag::note_declared_at); 2865 return ExprError(); 2866 } 2867 2868 // Check whether this declaration can be used. Note that we suppress 2869 // this check when we're going to perform argument-dependent lookup 2870 // on this function name, because this might not be the function 2871 // that overload resolution actually selects. 2872 if (DiagnoseUseOfDecl(VD, Loc)) 2873 return ExprError(); 2874 2875 // Only create DeclRefExpr's for valid Decl's. 2876 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2877 return ExprError(); 2878 2879 // Handle members of anonymous structs and unions. If we got here, 2880 // and the reference is to a class member indirect field, then this 2881 // must be the subject of a pointer-to-member expression. 2882 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2883 if (!indirectField->isCXXClassMember()) 2884 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2885 indirectField); 2886 2887 { 2888 QualType type = VD->getType(); 2889 ExprValueKind valueKind = VK_RValue; 2890 2891 switch (D->getKind()) { 2892 // Ignore all the non-ValueDecl kinds. 2893 #define ABSTRACT_DECL(kind) 2894 #define VALUE(type, base) 2895 #define DECL(type, base) \ 2896 case Decl::type: 2897 #include "clang/AST/DeclNodes.inc" 2898 llvm_unreachable("invalid value decl kind"); 2899 2900 // These shouldn't make it here. 2901 case Decl::ObjCAtDefsField: 2902 case Decl::ObjCIvar: 2903 llvm_unreachable("forming non-member reference to ivar?"); 2904 2905 // Enum constants are always r-values and never references. 2906 // Unresolved using declarations are dependent. 2907 case Decl::EnumConstant: 2908 case Decl::UnresolvedUsingValue: 2909 case Decl::OMPDeclareReduction: 2910 valueKind = VK_RValue; 2911 break; 2912 2913 // Fields and indirect fields that got here must be for 2914 // pointer-to-member expressions; we just call them l-values for 2915 // internal consistency, because this subexpression doesn't really 2916 // exist in the high-level semantics. 2917 case Decl::Field: 2918 case Decl::IndirectField: 2919 assert(getLangOpts().CPlusPlus && 2920 "building reference to field in C?"); 2921 2922 // These can't have reference type in well-formed programs, but 2923 // for internal consistency we do this anyway. 2924 type = type.getNonReferenceType(); 2925 valueKind = VK_LValue; 2926 break; 2927 2928 // Non-type template parameters are either l-values or r-values 2929 // depending on the type. 2930 case Decl::NonTypeTemplateParm: { 2931 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2932 type = reftype->getPointeeType(); 2933 valueKind = VK_LValue; // even if the parameter is an r-value reference 2934 break; 2935 } 2936 2937 // For non-references, we need to strip qualifiers just in case 2938 // the template parameter was declared as 'const int' or whatever. 2939 valueKind = VK_RValue; 2940 type = type.getUnqualifiedType(); 2941 break; 2942 } 2943 2944 case Decl::Var: 2945 case Decl::VarTemplateSpecialization: 2946 case Decl::VarTemplatePartialSpecialization: 2947 case Decl::OMPCapturedExpr: 2948 // In C, "extern void blah;" is valid and is an r-value. 2949 if (!getLangOpts().CPlusPlus && 2950 !type.hasQualifiers() && 2951 type->isVoidType()) { 2952 valueKind = VK_RValue; 2953 break; 2954 } 2955 // fallthrough 2956 2957 case Decl::ImplicitParam: 2958 case Decl::ParmVar: { 2959 // These are always l-values. 2960 valueKind = VK_LValue; 2961 type = type.getNonReferenceType(); 2962 2963 // FIXME: Does the addition of const really only apply in 2964 // potentially-evaluated contexts? Since the variable isn't actually 2965 // captured in an unevaluated context, it seems that the answer is no. 2966 if (!isUnevaluatedContext()) { 2967 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2968 if (!CapturedType.isNull()) 2969 type = CapturedType; 2970 } 2971 2972 break; 2973 } 2974 2975 case Decl::Function: { 2976 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2977 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2978 type = Context.BuiltinFnTy; 2979 valueKind = VK_RValue; 2980 break; 2981 } 2982 } 2983 2984 const FunctionType *fty = type->castAs<FunctionType>(); 2985 2986 // If we're referring to a function with an __unknown_anytype 2987 // result type, make the entire expression __unknown_anytype. 2988 if (fty->getReturnType() == Context.UnknownAnyTy) { 2989 type = Context.UnknownAnyTy; 2990 valueKind = VK_RValue; 2991 break; 2992 } 2993 2994 // Functions are l-values in C++. 2995 if (getLangOpts().CPlusPlus) { 2996 valueKind = VK_LValue; 2997 break; 2998 } 2999 3000 // C99 DR 316 says that, if a function type comes from a 3001 // function definition (without a prototype), that type is only 3002 // used for checking compatibility. Therefore, when referencing 3003 // the function, we pretend that we don't have the full function 3004 // type. 3005 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3006 isa<FunctionProtoType>(fty)) 3007 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3008 fty->getExtInfo()); 3009 3010 // Functions are r-values in C. 3011 valueKind = VK_RValue; 3012 break; 3013 } 3014 3015 case Decl::MSProperty: 3016 valueKind = VK_LValue; 3017 break; 3018 3019 case Decl::CXXMethod: 3020 // If we're referring to a method with an __unknown_anytype 3021 // result type, make the entire expression __unknown_anytype. 3022 // This should only be possible with a type written directly. 3023 if (const FunctionProtoType *proto 3024 = dyn_cast<FunctionProtoType>(VD->getType())) 3025 if (proto->getReturnType() == Context.UnknownAnyTy) { 3026 type = Context.UnknownAnyTy; 3027 valueKind = VK_RValue; 3028 break; 3029 } 3030 3031 // C++ methods are l-values if static, r-values if non-static. 3032 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3033 valueKind = VK_LValue; 3034 break; 3035 } 3036 // fallthrough 3037 3038 case Decl::CXXConversion: 3039 case Decl::CXXDestructor: 3040 case Decl::CXXConstructor: 3041 valueKind = VK_RValue; 3042 break; 3043 } 3044 3045 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3046 TemplateArgs); 3047 } 3048 } 3049 3050 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3051 SmallString<32> &Target) { 3052 Target.resize(CharByteWidth * (Source.size() + 1)); 3053 char *ResultPtr = &Target[0]; 3054 const UTF8 *ErrorPtr; 3055 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3056 (void)success; 3057 assert(success); 3058 Target.resize(ResultPtr - &Target[0]); 3059 } 3060 3061 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3062 PredefinedExpr::IdentType IT) { 3063 // Pick the current block, lambda, captured statement or function. 3064 Decl *currentDecl = nullptr; 3065 if (const BlockScopeInfo *BSI = getCurBlock()) 3066 currentDecl = BSI->TheDecl; 3067 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3068 currentDecl = LSI->CallOperator; 3069 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3070 currentDecl = CSI->TheCapturedDecl; 3071 else 3072 currentDecl = getCurFunctionOrMethodDecl(); 3073 3074 if (!currentDecl) { 3075 Diag(Loc, diag::ext_predef_outside_function); 3076 currentDecl = Context.getTranslationUnitDecl(); 3077 } 3078 3079 QualType ResTy; 3080 StringLiteral *SL = nullptr; 3081 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3082 ResTy = Context.DependentTy; 3083 else { 3084 // Pre-defined identifiers are of type char[x], where x is the length of 3085 // the string. 3086 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3087 unsigned Length = Str.length(); 3088 3089 llvm::APInt LengthI(32, Length + 1); 3090 if (IT == PredefinedExpr::LFunction) { 3091 ResTy = Context.WideCharTy.withConst(); 3092 SmallString<32> RawChars; 3093 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3094 Str, RawChars); 3095 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3096 /*IndexTypeQuals*/ 0); 3097 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3098 /*Pascal*/ false, ResTy, Loc); 3099 } else { 3100 ResTy = Context.CharTy.withConst(); 3101 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3102 /*IndexTypeQuals*/ 0); 3103 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3104 /*Pascal*/ false, ResTy, Loc); 3105 } 3106 } 3107 3108 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3109 } 3110 3111 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3112 PredefinedExpr::IdentType IT; 3113 3114 switch (Kind) { 3115 default: llvm_unreachable("Unknown simple primary expr!"); 3116 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3117 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3118 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3119 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3120 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3121 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3122 } 3123 3124 return BuildPredefinedExpr(Loc, IT); 3125 } 3126 3127 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3128 SmallString<16> CharBuffer; 3129 bool Invalid = false; 3130 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3131 if (Invalid) 3132 return ExprError(); 3133 3134 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3135 PP, Tok.getKind()); 3136 if (Literal.hadError()) 3137 return ExprError(); 3138 3139 QualType Ty; 3140 if (Literal.isWide()) 3141 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3142 else if (Literal.isUTF16()) 3143 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3144 else if (Literal.isUTF32()) 3145 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3146 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3147 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3148 else 3149 Ty = Context.CharTy; // 'x' -> char in C++ 3150 3151 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3152 if (Literal.isWide()) 3153 Kind = CharacterLiteral::Wide; 3154 else if (Literal.isUTF16()) 3155 Kind = CharacterLiteral::UTF16; 3156 else if (Literal.isUTF32()) 3157 Kind = CharacterLiteral::UTF32; 3158 else if (Literal.isUTF8()) 3159 Kind = CharacterLiteral::UTF8; 3160 3161 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3162 Tok.getLocation()); 3163 3164 if (Literal.getUDSuffix().empty()) 3165 return Lit; 3166 3167 // We're building a user-defined literal. 3168 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3169 SourceLocation UDSuffixLoc = 3170 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3171 3172 // Make sure we're allowed user-defined literals here. 3173 if (!UDLScope) 3174 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3175 3176 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3177 // operator "" X (ch) 3178 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3179 Lit, Tok.getLocation()); 3180 } 3181 3182 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3183 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3184 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3185 Context.IntTy, Loc); 3186 } 3187 3188 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3189 QualType Ty, SourceLocation Loc) { 3190 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3191 3192 using llvm::APFloat; 3193 APFloat Val(Format); 3194 3195 APFloat::opStatus result = Literal.GetFloatValue(Val); 3196 3197 // Overflow is always an error, but underflow is only an error if 3198 // we underflowed to zero (APFloat reports denormals as underflow). 3199 if ((result & APFloat::opOverflow) || 3200 ((result & APFloat::opUnderflow) && Val.isZero())) { 3201 unsigned diagnostic; 3202 SmallString<20> buffer; 3203 if (result & APFloat::opOverflow) { 3204 diagnostic = diag::warn_float_overflow; 3205 APFloat::getLargest(Format).toString(buffer); 3206 } else { 3207 diagnostic = diag::warn_float_underflow; 3208 APFloat::getSmallest(Format).toString(buffer); 3209 } 3210 3211 S.Diag(Loc, diagnostic) 3212 << Ty 3213 << StringRef(buffer.data(), buffer.size()); 3214 } 3215 3216 bool isExact = (result == APFloat::opOK); 3217 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3218 } 3219 3220 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3221 assert(E && "Invalid expression"); 3222 3223 if (E->isValueDependent()) 3224 return false; 3225 3226 QualType QT = E->getType(); 3227 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3228 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3229 return true; 3230 } 3231 3232 llvm::APSInt ValueAPS; 3233 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3234 3235 if (R.isInvalid()) 3236 return true; 3237 3238 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3239 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3240 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3241 << ValueAPS.toString(10) << ValueIsPositive; 3242 return true; 3243 } 3244 3245 return false; 3246 } 3247 3248 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3249 // Fast path for a single digit (which is quite common). A single digit 3250 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3251 if (Tok.getLength() == 1) { 3252 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3253 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3254 } 3255 3256 SmallString<128> SpellingBuffer; 3257 // NumericLiteralParser wants to overread by one character. Add padding to 3258 // the buffer in case the token is copied to the buffer. If getSpelling() 3259 // returns a StringRef to the memory buffer, it should have a null char at 3260 // the EOF, so it is also safe. 3261 SpellingBuffer.resize(Tok.getLength() + 1); 3262 3263 // Get the spelling of the token, which eliminates trigraphs, etc. 3264 bool Invalid = false; 3265 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3266 if (Invalid) 3267 return ExprError(); 3268 3269 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3270 if (Literal.hadError) 3271 return ExprError(); 3272 3273 if (Literal.hasUDSuffix()) { 3274 // We're building a user-defined literal. 3275 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3276 SourceLocation UDSuffixLoc = 3277 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3278 3279 // Make sure we're allowed user-defined literals here. 3280 if (!UDLScope) 3281 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3282 3283 QualType CookedTy; 3284 if (Literal.isFloatingLiteral()) { 3285 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3286 // long double, the literal is treated as a call of the form 3287 // operator "" X (f L) 3288 CookedTy = Context.LongDoubleTy; 3289 } else { 3290 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3291 // unsigned long long, the literal is treated as a call of the form 3292 // operator "" X (n ULL) 3293 CookedTy = Context.UnsignedLongLongTy; 3294 } 3295 3296 DeclarationName OpName = 3297 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3298 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3299 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3300 3301 SourceLocation TokLoc = Tok.getLocation(); 3302 3303 // Perform literal operator lookup to determine if we're building a raw 3304 // literal or a cooked one. 3305 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3306 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3307 /*AllowRaw*/true, /*AllowTemplate*/true, 3308 /*AllowStringTemplate*/false)) { 3309 case LOLR_Error: 3310 return ExprError(); 3311 3312 case LOLR_Cooked: { 3313 Expr *Lit; 3314 if (Literal.isFloatingLiteral()) { 3315 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3316 } else { 3317 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3318 if (Literal.GetIntegerValue(ResultVal)) 3319 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3320 << /* Unsigned */ 1; 3321 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3322 Tok.getLocation()); 3323 } 3324 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3325 } 3326 3327 case LOLR_Raw: { 3328 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3329 // literal is treated as a call of the form 3330 // operator "" X ("n") 3331 unsigned Length = Literal.getUDSuffixOffset(); 3332 QualType StrTy = Context.getConstantArrayType( 3333 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3334 ArrayType::Normal, 0); 3335 Expr *Lit = StringLiteral::Create( 3336 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3337 /*Pascal*/false, StrTy, &TokLoc, 1); 3338 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3339 } 3340 3341 case LOLR_Template: { 3342 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3343 // template), L is treated as a call fo the form 3344 // operator "" X <'c1', 'c2', ... 'ck'>() 3345 // where n is the source character sequence c1 c2 ... ck. 3346 TemplateArgumentListInfo ExplicitArgs; 3347 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3348 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3349 llvm::APSInt Value(CharBits, CharIsUnsigned); 3350 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3351 Value = TokSpelling[I]; 3352 TemplateArgument Arg(Context, Value, Context.CharTy); 3353 TemplateArgumentLocInfo ArgInfo; 3354 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3355 } 3356 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3357 &ExplicitArgs); 3358 } 3359 case LOLR_StringTemplate: 3360 llvm_unreachable("unexpected literal operator lookup result"); 3361 } 3362 } 3363 3364 Expr *Res; 3365 3366 if (Literal.isFloatingLiteral()) { 3367 QualType Ty; 3368 if (Literal.isHalf){ 3369 if (getOpenCLOptions().cl_khr_fp16) 3370 Ty = Context.HalfTy; 3371 else { 3372 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3373 return ExprError(); 3374 } 3375 } else if (Literal.isFloat) 3376 Ty = Context.FloatTy; 3377 else if (Literal.isLong) 3378 Ty = Context.LongDoubleTy; 3379 else if (Literal.isFloat128) 3380 Ty = Context.Float128Ty; 3381 else 3382 Ty = Context.DoubleTy; 3383 3384 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3385 3386 if (Ty == Context.DoubleTy) { 3387 if (getLangOpts().SinglePrecisionConstants) { 3388 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3389 } else if (getLangOpts().OpenCL && 3390 !((getLangOpts().OpenCLVersion >= 120) || 3391 getOpenCLOptions().cl_khr_fp64)) { 3392 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3393 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3394 } 3395 } 3396 } else if (!Literal.isIntegerLiteral()) { 3397 return ExprError(); 3398 } else { 3399 QualType Ty; 3400 3401 // 'long long' is a C99 or C++11 feature. 3402 if (!getLangOpts().C99 && Literal.isLongLong) { 3403 if (getLangOpts().CPlusPlus) 3404 Diag(Tok.getLocation(), 3405 getLangOpts().CPlusPlus11 ? 3406 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3407 else 3408 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3409 } 3410 3411 // Get the value in the widest-possible width. 3412 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3413 llvm::APInt ResultVal(MaxWidth, 0); 3414 3415 if (Literal.GetIntegerValue(ResultVal)) { 3416 // If this value didn't fit into uintmax_t, error and force to ull. 3417 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3418 << /* Unsigned */ 1; 3419 Ty = Context.UnsignedLongLongTy; 3420 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3421 "long long is not intmax_t?"); 3422 } else { 3423 // If this value fits into a ULL, try to figure out what else it fits into 3424 // according to the rules of C99 6.4.4.1p5. 3425 3426 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3427 // be an unsigned int. 3428 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3429 3430 // Check from smallest to largest, picking the smallest type we can. 3431 unsigned Width = 0; 3432 3433 // Microsoft specific integer suffixes are explicitly sized. 3434 if (Literal.MicrosoftInteger) { 3435 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3436 Width = 8; 3437 Ty = Context.CharTy; 3438 } else { 3439 Width = Literal.MicrosoftInteger; 3440 Ty = Context.getIntTypeForBitwidth(Width, 3441 /*Signed=*/!Literal.isUnsigned); 3442 } 3443 } 3444 3445 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3446 // Are int/unsigned possibilities? 3447 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3448 3449 // Does it fit in a unsigned int? 3450 if (ResultVal.isIntN(IntSize)) { 3451 // Does it fit in a signed int? 3452 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3453 Ty = Context.IntTy; 3454 else if (AllowUnsigned) 3455 Ty = Context.UnsignedIntTy; 3456 Width = IntSize; 3457 } 3458 } 3459 3460 // Are long/unsigned long possibilities? 3461 if (Ty.isNull() && !Literal.isLongLong) { 3462 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3463 3464 // Does it fit in a unsigned long? 3465 if (ResultVal.isIntN(LongSize)) { 3466 // Does it fit in a signed long? 3467 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3468 Ty = Context.LongTy; 3469 else if (AllowUnsigned) 3470 Ty = Context.UnsignedLongTy; 3471 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3472 // is compatible. 3473 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3474 const unsigned LongLongSize = 3475 Context.getTargetInfo().getLongLongWidth(); 3476 Diag(Tok.getLocation(), 3477 getLangOpts().CPlusPlus 3478 ? Literal.isLong 3479 ? diag::warn_old_implicitly_unsigned_long_cxx 3480 : /*C++98 UB*/ diag:: 3481 ext_old_implicitly_unsigned_long_cxx 3482 : diag::warn_old_implicitly_unsigned_long) 3483 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3484 : /*will be ill-formed*/ 1); 3485 Ty = Context.UnsignedLongTy; 3486 } 3487 Width = LongSize; 3488 } 3489 } 3490 3491 // Check long long if needed. 3492 if (Ty.isNull()) { 3493 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3494 3495 // Does it fit in a unsigned long long? 3496 if (ResultVal.isIntN(LongLongSize)) { 3497 // Does it fit in a signed long long? 3498 // To be compatible with MSVC, hex integer literals ending with the 3499 // LL or i64 suffix are always signed in Microsoft mode. 3500 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3501 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3502 Ty = Context.LongLongTy; 3503 else if (AllowUnsigned) 3504 Ty = Context.UnsignedLongLongTy; 3505 Width = LongLongSize; 3506 } 3507 } 3508 3509 // If we still couldn't decide a type, we probably have something that 3510 // does not fit in a signed long long, but has no U suffix. 3511 if (Ty.isNull()) { 3512 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3513 Ty = Context.UnsignedLongLongTy; 3514 Width = Context.getTargetInfo().getLongLongWidth(); 3515 } 3516 3517 if (ResultVal.getBitWidth() != Width) 3518 ResultVal = ResultVal.trunc(Width); 3519 } 3520 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3521 } 3522 3523 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3524 if (Literal.isImaginary) 3525 Res = new (Context) ImaginaryLiteral(Res, 3526 Context.getComplexType(Res->getType())); 3527 3528 return Res; 3529 } 3530 3531 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3532 assert(E && "ActOnParenExpr() missing expr"); 3533 return new (Context) ParenExpr(L, R, E); 3534 } 3535 3536 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3537 SourceLocation Loc, 3538 SourceRange ArgRange) { 3539 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3540 // scalar or vector data type argument..." 3541 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3542 // type (C99 6.2.5p18) or void. 3543 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3544 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3545 << T << ArgRange; 3546 return true; 3547 } 3548 3549 assert((T->isVoidType() || !T->isIncompleteType()) && 3550 "Scalar types should always be complete"); 3551 return false; 3552 } 3553 3554 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3555 SourceLocation Loc, 3556 SourceRange ArgRange, 3557 UnaryExprOrTypeTrait TraitKind) { 3558 // Invalid types must be hard errors for SFINAE in C++. 3559 if (S.LangOpts.CPlusPlus) 3560 return true; 3561 3562 // C99 6.5.3.4p1: 3563 if (T->isFunctionType() && 3564 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3565 // sizeof(function)/alignof(function) is allowed as an extension. 3566 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3567 << TraitKind << ArgRange; 3568 return false; 3569 } 3570 3571 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3572 // this is an error (OpenCL v1.1 s6.3.k) 3573 if (T->isVoidType()) { 3574 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3575 : diag::ext_sizeof_alignof_void_type; 3576 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3577 return false; 3578 } 3579 3580 return true; 3581 } 3582 3583 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3584 SourceLocation Loc, 3585 SourceRange ArgRange, 3586 UnaryExprOrTypeTrait TraitKind) { 3587 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3588 // runtime doesn't allow it. 3589 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3590 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3591 << T << (TraitKind == UETT_SizeOf) 3592 << ArgRange; 3593 return true; 3594 } 3595 3596 return false; 3597 } 3598 3599 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3600 /// pointer type is equal to T) and emit a warning if it is. 3601 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3602 Expr *E) { 3603 // Don't warn if the operation changed the type. 3604 if (T != E->getType()) 3605 return; 3606 3607 // Now look for array decays. 3608 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3609 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3610 return; 3611 3612 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3613 << ICE->getType() 3614 << ICE->getSubExpr()->getType(); 3615 } 3616 3617 /// \brief Check the constraints on expression operands to unary type expression 3618 /// and type traits. 3619 /// 3620 /// Completes any types necessary and validates the constraints on the operand 3621 /// expression. The logic mostly mirrors the type-based overload, but may modify 3622 /// the expression as it completes the type for that expression through template 3623 /// instantiation, etc. 3624 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3625 UnaryExprOrTypeTrait ExprKind) { 3626 QualType ExprTy = E->getType(); 3627 assert(!ExprTy->isReferenceType()); 3628 3629 if (ExprKind == UETT_VecStep) 3630 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3631 E->getSourceRange()); 3632 3633 // Whitelist some types as extensions 3634 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3635 E->getSourceRange(), ExprKind)) 3636 return false; 3637 3638 // 'alignof' applied to an expression only requires the base element type of 3639 // the expression to be complete. 'sizeof' requires the expression's type to 3640 // be complete (and will attempt to complete it if it's an array of unknown 3641 // bound). 3642 if (ExprKind == UETT_AlignOf) { 3643 if (RequireCompleteType(E->getExprLoc(), 3644 Context.getBaseElementType(E->getType()), 3645 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3646 E->getSourceRange())) 3647 return true; 3648 } else { 3649 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3650 ExprKind, E->getSourceRange())) 3651 return true; 3652 } 3653 3654 // Completing the expression's type may have changed it. 3655 ExprTy = E->getType(); 3656 assert(!ExprTy->isReferenceType()); 3657 3658 if (ExprTy->isFunctionType()) { 3659 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3660 << ExprKind << E->getSourceRange(); 3661 return true; 3662 } 3663 3664 // The operand for sizeof and alignof is in an unevaluated expression context, 3665 // so side effects could result in unintended consequences. 3666 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3667 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3668 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3669 3670 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3671 E->getSourceRange(), ExprKind)) 3672 return true; 3673 3674 if (ExprKind == UETT_SizeOf) { 3675 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3676 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3677 QualType OType = PVD->getOriginalType(); 3678 QualType Type = PVD->getType(); 3679 if (Type->isPointerType() && OType->isArrayType()) { 3680 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3681 << Type << OType; 3682 Diag(PVD->getLocation(), diag::note_declared_at); 3683 } 3684 } 3685 } 3686 3687 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3688 // decays into a pointer and returns an unintended result. This is most 3689 // likely a typo for "sizeof(array) op x". 3690 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3691 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3692 BO->getLHS()); 3693 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3694 BO->getRHS()); 3695 } 3696 } 3697 3698 return false; 3699 } 3700 3701 /// \brief Check the constraints on operands to unary expression and type 3702 /// traits. 3703 /// 3704 /// This will complete any types necessary, and validate the various constraints 3705 /// on those operands. 3706 /// 3707 /// The UsualUnaryConversions() function is *not* called by this routine. 3708 /// C99 6.3.2.1p[2-4] all state: 3709 /// Except when it is the operand of the sizeof operator ... 3710 /// 3711 /// C++ [expr.sizeof]p4 3712 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3713 /// standard conversions are not applied to the operand of sizeof. 3714 /// 3715 /// This policy is followed for all of the unary trait expressions. 3716 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3717 SourceLocation OpLoc, 3718 SourceRange ExprRange, 3719 UnaryExprOrTypeTrait ExprKind) { 3720 if (ExprType->isDependentType()) 3721 return false; 3722 3723 // C++ [expr.sizeof]p2: 3724 // When applied to a reference or a reference type, the result 3725 // is the size of the referenced type. 3726 // C++11 [expr.alignof]p3: 3727 // When alignof is applied to a reference type, the result 3728 // shall be the alignment of the referenced type. 3729 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3730 ExprType = Ref->getPointeeType(); 3731 3732 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3733 // When alignof or _Alignof is applied to an array type, the result 3734 // is the alignment of the element type. 3735 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3736 ExprType = Context.getBaseElementType(ExprType); 3737 3738 if (ExprKind == UETT_VecStep) 3739 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3740 3741 // Whitelist some types as extensions 3742 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3743 ExprKind)) 3744 return false; 3745 3746 if (RequireCompleteType(OpLoc, ExprType, 3747 diag::err_sizeof_alignof_incomplete_type, 3748 ExprKind, ExprRange)) 3749 return true; 3750 3751 if (ExprType->isFunctionType()) { 3752 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3753 << ExprKind << ExprRange; 3754 return true; 3755 } 3756 3757 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3758 ExprKind)) 3759 return true; 3760 3761 return false; 3762 } 3763 3764 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3765 E = E->IgnoreParens(); 3766 3767 // Cannot know anything else if the expression is dependent. 3768 if (E->isTypeDependent()) 3769 return false; 3770 3771 if (E->getObjectKind() == OK_BitField) { 3772 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3773 << 1 << E->getSourceRange(); 3774 return true; 3775 } 3776 3777 ValueDecl *D = nullptr; 3778 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3779 D = DRE->getDecl(); 3780 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3781 D = ME->getMemberDecl(); 3782 } 3783 3784 // If it's a field, require the containing struct to have a 3785 // complete definition so that we can compute the layout. 3786 // 3787 // This can happen in C++11 onwards, either by naming the member 3788 // in a way that is not transformed into a member access expression 3789 // (in an unevaluated operand, for instance), or by naming the member 3790 // in a trailing-return-type. 3791 // 3792 // For the record, since __alignof__ on expressions is a GCC 3793 // extension, GCC seems to permit this but always gives the 3794 // nonsensical answer 0. 3795 // 3796 // We don't really need the layout here --- we could instead just 3797 // directly check for all the appropriate alignment-lowing 3798 // attributes --- but that would require duplicating a lot of 3799 // logic that just isn't worth duplicating for such a marginal 3800 // use-case. 3801 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3802 // Fast path this check, since we at least know the record has a 3803 // definition if we can find a member of it. 3804 if (!FD->getParent()->isCompleteDefinition()) { 3805 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3806 << E->getSourceRange(); 3807 return true; 3808 } 3809 3810 // Otherwise, if it's a field, and the field doesn't have 3811 // reference type, then it must have a complete type (or be a 3812 // flexible array member, which we explicitly want to 3813 // white-list anyway), which makes the following checks trivial. 3814 if (!FD->getType()->isReferenceType()) 3815 return false; 3816 } 3817 3818 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3819 } 3820 3821 bool Sema::CheckVecStepExpr(Expr *E) { 3822 E = E->IgnoreParens(); 3823 3824 // Cannot know anything else if the expression is dependent. 3825 if (E->isTypeDependent()) 3826 return false; 3827 3828 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3829 } 3830 3831 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3832 CapturingScopeInfo *CSI) { 3833 assert(T->isVariablyModifiedType()); 3834 assert(CSI != nullptr); 3835 3836 // We're going to walk down into the type and look for VLA expressions. 3837 do { 3838 const Type *Ty = T.getTypePtr(); 3839 switch (Ty->getTypeClass()) { 3840 #define TYPE(Class, Base) 3841 #define ABSTRACT_TYPE(Class, Base) 3842 #define NON_CANONICAL_TYPE(Class, Base) 3843 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3844 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3845 #include "clang/AST/TypeNodes.def" 3846 T = QualType(); 3847 break; 3848 // These types are never variably-modified. 3849 case Type::Builtin: 3850 case Type::Complex: 3851 case Type::Vector: 3852 case Type::ExtVector: 3853 case Type::Record: 3854 case Type::Enum: 3855 case Type::Elaborated: 3856 case Type::TemplateSpecialization: 3857 case Type::ObjCObject: 3858 case Type::ObjCInterface: 3859 case Type::ObjCObjectPointer: 3860 case Type::Pipe: 3861 llvm_unreachable("type class is never variably-modified!"); 3862 case Type::Adjusted: 3863 T = cast<AdjustedType>(Ty)->getOriginalType(); 3864 break; 3865 case Type::Decayed: 3866 T = cast<DecayedType>(Ty)->getPointeeType(); 3867 break; 3868 case Type::Pointer: 3869 T = cast<PointerType>(Ty)->getPointeeType(); 3870 break; 3871 case Type::BlockPointer: 3872 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3873 break; 3874 case Type::LValueReference: 3875 case Type::RValueReference: 3876 T = cast<ReferenceType>(Ty)->getPointeeType(); 3877 break; 3878 case Type::MemberPointer: 3879 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3880 break; 3881 case Type::ConstantArray: 3882 case Type::IncompleteArray: 3883 // Losing element qualification here is fine. 3884 T = cast<ArrayType>(Ty)->getElementType(); 3885 break; 3886 case Type::VariableArray: { 3887 // Losing element qualification here is fine. 3888 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3889 3890 // Unknown size indication requires no size computation. 3891 // Otherwise, evaluate and record it. 3892 if (auto Size = VAT->getSizeExpr()) { 3893 if (!CSI->isVLATypeCaptured(VAT)) { 3894 RecordDecl *CapRecord = nullptr; 3895 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3896 CapRecord = LSI->Lambda; 3897 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3898 CapRecord = CRSI->TheRecordDecl; 3899 } 3900 if (CapRecord) { 3901 auto ExprLoc = Size->getExprLoc(); 3902 auto SizeType = Context.getSizeType(); 3903 // Build the non-static data member. 3904 auto Field = 3905 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3906 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3907 /*BW*/ nullptr, /*Mutable*/ false, 3908 /*InitStyle*/ ICIS_NoInit); 3909 Field->setImplicit(true); 3910 Field->setAccess(AS_private); 3911 Field->setCapturedVLAType(VAT); 3912 CapRecord->addDecl(Field); 3913 3914 CSI->addVLATypeCapture(ExprLoc, SizeType); 3915 } 3916 } 3917 } 3918 T = VAT->getElementType(); 3919 break; 3920 } 3921 case Type::FunctionProto: 3922 case Type::FunctionNoProto: 3923 T = cast<FunctionType>(Ty)->getReturnType(); 3924 break; 3925 case Type::Paren: 3926 case Type::TypeOf: 3927 case Type::UnaryTransform: 3928 case Type::Attributed: 3929 case Type::SubstTemplateTypeParm: 3930 case Type::PackExpansion: 3931 // Keep walking after single level desugaring. 3932 T = T.getSingleStepDesugaredType(Context); 3933 break; 3934 case Type::Typedef: 3935 T = cast<TypedefType>(Ty)->desugar(); 3936 break; 3937 case Type::Decltype: 3938 T = cast<DecltypeType>(Ty)->desugar(); 3939 break; 3940 case Type::Auto: 3941 T = cast<AutoType>(Ty)->getDeducedType(); 3942 break; 3943 case Type::TypeOfExpr: 3944 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3945 break; 3946 case Type::Atomic: 3947 T = cast<AtomicType>(Ty)->getValueType(); 3948 break; 3949 } 3950 } while (!T.isNull() && T->isVariablyModifiedType()); 3951 } 3952 3953 /// \brief Build a sizeof or alignof expression given a type operand. 3954 ExprResult 3955 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3956 SourceLocation OpLoc, 3957 UnaryExprOrTypeTrait ExprKind, 3958 SourceRange R) { 3959 if (!TInfo) 3960 return ExprError(); 3961 3962 QualType T = TInfo->getType(); 3963 3964 if (!T->isDependentType() && 3965 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3966 return ExprError(); 3967 3968 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3969 if (auto *TT = T->getAs<TypedefType>()) { 3970 for (auto I = FunctionScopes.rbegin(), 3971 E = std::prev(FunctionScopes.rend()); 3972 I != E; ++I) { 3973 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3974 if (CSI == nullptr) 3975 break; 3976 DeclContext *DC = nullptr; 3977 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3978 DC = LSI->CallOperator; 3979 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3980 DC = CRSI->TheCapturedDecl; 3981 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3982 DC = BSI->TheDecl; 3983 if (DC) { 3984 if (DC->containsDecl(TT->getDecl())) 3985 break; 3986 captureVariablyModifiedType(Context, T, CSI); 3987 } 3988 } 3989 } 3990 } 3991 3992 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3993 return new (Context) UnaryExprOrTypeTraitExpr( 3994 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3995 } 3996 3997 /// \brief Build a sizeof or alignof expression given an expression 3998 /// operand. 3999 ExprResult 4000 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4001 UnaryExprOrTypeTrait ExprKind) { 4002 ExprResult PE = CheckPlaceholderExpr(E); 4003 if (PE.isInvalid()) 4004 return ExprError(); 4005 4006 E = PE.get(); 4007 4008 // Verify that the operand is valid. 4009 bool isInvalid = false; 4010 if (E->isTypeDependent()) { 4011 // Delay type-checking for type-dependent expressions. 4012 } else if (ExprKind == UETT_AlignOf) { 4013 isInvalid = CheckAlignOfExpr(*this, E); 4014 } else if (ExprKind == UETT_VecStep) { 4015 isInvalid = CheckVecStepExpr(E); 4016 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4017 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4018 isInvalid = true; 4019 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4020 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4021 isInvalid = true; 4022 } else { 4023 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4024 } 4025 4026 if (isInvalid) 4027 return ExprError(); 4028 4029 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4030 PE = TransformToPotentiallyEvaluated(E); 4031 if (PE.isInvalid()) return ExprError(); 4032 E = PE.get(); 4033 } 4034 4035 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4036 return new (Context) UnaryExprOrTypeTraitExpr( 4037 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4038 } 4039 4040 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4041 /// expr and the same for @c alignof and @c __alignof 4042 /// Note that the ArgRange is invalid if isType is false. 4043 ExprResult 4044 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4045 UnaryExprOrTypeTrait ExprKind, bool IsType, 4046 void *TyOrEx, SourceRange ArgRange) { 4047 // If error parsing type, ignore. 4048 if (!TyOrEx) return ExprError(); 4049 4050 if (IsType) { 4051 TypeSourceInfo *TInfo; 4052 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4053 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4054 } 4055 4056 Expr *ArgEx = (Expr *)TyOrEx; 4057 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4058 return Result; 4059 } 4060 4061 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4062 bool IsReal) { 4063 if (V.get()->isTypeDependent()) 4064 return S.Context.DependentTy; 4065 4066 // _Real and _Imag are only l-values for normal l-values. 4067 if (V.get()->getObjectKind() != OK_Ordinary) { 4068 V = S.DefaultLvalueConversion(V.get()); 4069 if (V.isInvalid()) 4070 return QualType(); 4071 } 4072 4073 // These operators return the element type of a complex type. 4074 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4075 return CT->getElementType(); 4076 4077 // Otherwise they pass through real integer and floating point types here. 4078 if (V.get()->getType()->isArithmeticType()) 4079 return V.get()->getType(); 4080 4081 // Test for placeholders. 4082 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4083 if (PR.isInvalid()) return QualType(); 4084 if (PR.get() != V.get()) { 4085 V = PR; 4086 return CheckRealImagOperand(S, V, Loc, IsReal); 4087 } 4088 4089 // Reject anything else. 4090 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4091 << (IsReal ? "__real" : "__imag"); 4092 return QualType(); 4093 } 4094 4095 4096 4097 ExprResult 4098 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4099 tok::TokenKind Kind, Expr *Input) { 4100 UnaryOperatorKind Opc; 4101 switch (Kind) { 4102 default: llvm_unreachable("Unknown unary op!"); 4103 case tok::plusplus: Opc = UO_PostInc; break; 4104 case tok::minusminus: Opc = UO_PostDec; break; 4105 } 4106 4107 // Since this might is a postfix expression, get rid of ParenListExprs. 4108 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4109 if (Result.isInvalid()) return ExprError(); 4110 Input = Result.get(); 4111 4112 return BuildUnaryOp(S, OpLoc, Opc, Input); 4113 } 4114 4115 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4116 /// 4117 /// \return true on error 4118 static bool checkArithmeticOnObjCPointer(Sema &S, 4119 SourceLocation opLoc, 4120 Expr *op) { 4121 assert(op->getType()->isObjCObjectPointerType()); 4122 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4123 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4124 return false; 4125 4126 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4127 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4128 << op->getSourceRange(); 4129 return true; 4130 } 4131 4132 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4133 auto *BaseNoParens = Base->IgnoreParens(); 4134 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4135 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4136 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4137 } 4138 4139 ExprResult 4140 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4141 Expr *idx, SourceLocation rbLoc) { 4142 if (base && !base->getType().isNull() && 4143 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4144 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4145 /*Length=*/nullptr, rbLoc); 4146 4147 // Since this might be a postfix expression, get rid of ParenListExprs. 4148 if (isa<ParenListExpr>(base)) { 4149 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4150 if (result.isInvalid()) return ExprError(); 4151 base = result.get(); 4152 } 4153 4154 // Handle any non-overload placeholder types in the base and index 4155 // expressions. We can't handle overloads here because the other 4156 // operand might be an overloadable type, in which case the overload 4157 // resolution for the operator overload should get the first crack 4158 // at the overload. 4159 bool IsMSPropertySubscript = false; 4160 if (base->getType()->isNonOverloadPlaceholderType()) { 4161 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4162 if (!IsMSPropertySubscript) { 4163 ExprResult result = CheckPlaceholderExpr(base); 4164 if (result.isInvalid()) 4165 return ExprError(); 4166 base = result.get(); 4167 } 4168 } 4169 if (idx->getType()->isNonOverloadPlaceholderType()) { 4170 ExprResult result = CheckPlaceholderExpr(idx); 4171 if (result.isInvalid()) return ExprError(); 4172 idx = result.get(); 4173 } 4174 4175 // Build an unanalyzed expression if either operand is type-dependent. 4176 if (getLangOpts().CPlusPlus && 4177 (base->isTypeDependent() || idx->isTypeDependent())) { 4178 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4179 VK_LValue, OK_Ordinary, rbLoc); 4180 } 4181 4182 // MSDN, property (C++) 4183 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4184 // This attribute can also be used in the declaration of an empty array in a 4185 // class or structure definition. For example: 4186 // __declspec(property(get=GetX, put=PutX)) int x[]; 4187 // The above statement indicates that x[] can be used with one or more array 4188 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4189 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4190 if (IsMSPropertySubscript) { 4191 // Build MS property subscript expression if base is MS property reference 4192 // or MS property subscript. 4193 return new (Context) MSPropertySubscriptExpr( 4194 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4195 } 4196 4197 // Use C++ overloaded-operator rules if either operand has record 4198 // type. The spec says to do this if either type is *overloadable*, 4199 // but enum types can't declare subscript operators or conversion 4200 // operators, so there's nothing interesting for overload resolution 4201 // to do if there aren't any record types involved. 4202 // 4203 // ObjC pointers have their own subscripting logic that is not tied 4204 // to overload resolution and so should not take this path. 4205 if (getLangOpts().CPlusPlus && 4206 (base->getType()->isRecordType() || 4207 (!base->getType()->isObjCObjectPointerType() && 4208 idx->getType()->isRecordType()))) { 4209 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4210 } 4211 4212 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4213 } 4214 4215 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4216 Expr *LowerBound, 4217 SourceLocation ColonLoc, Expr *Length, 4218 SourceLocation RBLoc) { 4219 if (Base->getType()->isPlaceholderType() && 4220 !Base->getType()->isSpecificPlaceholderType( 4221 BuiltinType::OMPArraySection)) { 4222 ExprResult Result = CheckPlaceholderExpr(Base); 4223 if (Result.isInvalid()) 4224 return ExprError(); 4225 Base = Result.get(); 4226 } 4227 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4228 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4229 if (Result.isInvalid()) 4230 return ExprError(); 4231 Result = DefaultLvalueConversion(Result.get()); 4232 if (Result.isInvalid()) 4233 return ExprError(); 4234 LowerBound = Result.get(); 4235 } 4236 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4237 ExprResult Result = CheckPlaceholderExpr(Length); 4238 if (Result.isInvalid()) 4239 return ExprError(); 4240 Result = DefaultLvalueConversion(Result.get()); 4241 if (Result.isInvalid()) 4242 return ExprError(); 4243 Length = Result.get(); 4244 } 4245 4246 // Build an unanalyzed expression if either operand is type-dependent. 4247 if (Base->isTypeDependent() || 4248 (LowerBound && 4249 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4250 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4251 return new (Context) 4252 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4253 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4254 } 4255 4256 // Perform default conversions. 4257 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4258 QualType ResultTy; 4259 if (OriginalTy->isAnyPointerType()) { 4260 ResultTy = OriginalTy->getPointeeType(); 4261 } else if (OriginalTy->isArrayType()) { 4262 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4263 } else { 4264 return ExprError( 4265 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4266 << Base->getSourceRange()); 4267 } 4268 // C99 6.5.2.1p1 4269 if (LowerBound) { 4270 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4271 LowerBound); 4272 if (Res.isInvalid()) 4273 return ExprError(Diag(LowerBound->getExprLoc(), 4274 diag::err_omp_typecheck_section_not_integer) 4275 << 0 << LowerBound->getSourceRange()); 4276 LowerBound = Res.get(); 4277 4278 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4279 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4280 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4281 << 0 << LowerBound->getSourceRange(); 4282 } 4283 if (Length) { 4284 auto Res = 4285 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4286 if (Res.isInvalid()) 4287 return ExprError(Diag(Length->getExprLoc(), 4288 diag::err_omp_typecheck_section_not_integer) 4289 << 1 << Length->getSourceRange()); 4290 Length = Res.get(); 4291 4292 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4293 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4294 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4295 << 1 << Length->getSourceRange(); 4296 } 4297 4298 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4299 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4300 // type. Note that functions are not objects, and that (in C99 parlance) 4301 // incomplete types are not object types. 4302 if (ResultTy->isFunctionType()) { 4303 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4304 << ResultTy << Base->getSourceRange(); 4305 return ExprError(); 4306 } 4307 4308 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4309 diag::err_omp_section_incomplete_type, Base)) 4310 return ExprError(); 4311 4312 if (LowerBound) { 4313 llvm::APSInt LowerBoundValue; 4314 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4315 // OpenMP 4.0, [2.4 Array Sections] 4316 // The lower-bound and length must evaluate to non-negative integers. 4317 if (LowerBoundValue.isNegative()) { 4318 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4319 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4320 << LowerBound->getSourceRange(); 4321 return ExprError(); 4322 } 4323 } 4324 } 4325 4326 if (Length) { 4327 llvm::APSInt LengthValue; 4328 if (Length->EvaluateAsInt(LengthValue, Context)) { 4329 // OpenMP 4.0, [2.4 Array Sections] 4330 // The lower-bound and length must evaluate to non-negative integers. 4331 if (LengthValue.isNegative()) { 4332 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4333 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4334 << Length->getSourceRange(); 4335 return ExprError(); 4336 } 4337 } 4338 } else if (ColonLoc.isValid() && 4339 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4340 !OriginalTy->isVariableArrayType()))) { 4341 // OpenMP 4.0, [2.4 Array Sections] 4342 // When the size of the array dimension is not known, the length must be 4343 // specified explicitly. 4344 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4345 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4346 return ExprError(); 4347 } 4348 4349 if (!Base->getType()->isSpecificPlaceholderType( 4350 BuiltinType::OMPArraySection)) { 4351 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4352 if (Result.isInvalid()) 4353 return ExprError(); 4354 Base = Result.get(); 4355 } 4356 return new (Context) 4357 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4358 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4359 } 4360 4361 ExprResult 4362 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4363 Expr *Idx, SourceLocation RLoc) { 4364 Expr *LHSExp = Base; 4365 Expr *RHSExp = Idx; 4366 4367 // Perform default conversions. 4368 if (!LHSExp->getType()->getAs<VectorType>()) { 4369 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4370 if (Result.isInvalid()) 4371 return ExprError(); 4372 LHSExp = Result.get(); 4373 } 4374 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4375 if (Result.isInvalid()) 4376 return ExprError(); 4377 RHSExp = Result.get(); 4378 4379 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4380 ExprValueKind VK = VK_LValue; 4381 ExprObjectKind OK = OK_Ordinary; 4382 4383 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4384 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4385 // in the subscript position. As a result, we need to derive the array base 4386 // and index from the expression types. 4387 Expr *BaseExpr, *IndexExpr; 4388 QualType ResultType; 4389 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4390 BaseExpr = LHSExp; 4391 IndexExpr = RHSExp; 4392 ResultType = Context.DependentTy; 4393 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4394 BaseExpr = LHSExp; 4395 IndexExpr = RHSExp; 4396 ResultType = PTy->getPointeeType(); 4397 } else if (const ObjCObjectPointerType *PTy = 4398 LHSTy->getAs<ObjCObjectPointerType>()) { 4399 BaseExpr = LHSExp; 4400 IndexExpr = RHSExp; 4401 4402 // Use custom logic if this should be the pseudo-object subscript 4403 // expression. 4404 if (!LangOpts.isSubscriptPointerArithmetic()) 4405 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4406 nullptr); 4407 4408 ResultType = PTy->getPointeeType(); 4409 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4410 // Handle the uncommon case of "123[Ptr]". 4411 BaseExpr = RHSExp; 4412 IndexExpr = LHSExp; 4413 ResultType = PTy->getPointeeType(); 4414 } else if (const ObjCObjectPointerType *PTy = 4415 RHSTy->getAs<ObjCObjectPointerType>()) { 4416 // Handle the uncommon case of "123[Ptr]". 4417 BaseExpr = RHSExp; 4418 IndexExpr = LHSExp; 4419 ResultType = PTy->getPointeeType(); 4420 if (!LangOpts.isSubscriptPointerArithmetic()) { 4421 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4422 << ResultType << BaseExpr->getSourceRange(); 4423 return ExprError(); 4424 } 4425 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4426 BaseExpr = LHSExp; // vectors: V[123] 4427 IndexExpr = RHSExp; 4428 VK = LHSExp->getValueKind(); 4429 if (VK != VK_RValue) 4430 OK = OK_VectorComponent; 4431 4432 // FIXME: need to deal with const... 4433 ResultType = VTy->getElementType(); 4434 } else if (LHSTy->isArrayType()) { 4435 // If we see an array that wasn't promoted by 4436 // DefaultFunctionArrayLvalueConversion, it must be an array that 4437 // wasn't promoted because of the C90 rule that doesn't 4438 // allow promoting non-lvalue arrays. Warn, then 4439 // force the promotion here. 4440 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4441 LHSExp->getSourceRange(); 4442 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4443 CK_ArrayToPointerDecay).get(); 4444 LHSTy = LHSExp->getType(); 4445 4446 BaseExpr = LHSExp; 4447 IndexExpr = RHSExp; 4448 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4449 } else if (RHSTy->isArrayType()) { 4450 // Same as previous, except for 123[f().a] case 4451 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4452 RHSExp->getSourceRange(); 4453 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4454 CK_ArrayToPointerDecay).get(); 4455 RHSTy = RHSExp->getType(); 4456 4457 BaseExpr = RHSExp; 4458 IndexExpr = LHSExp; 4459 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4460 } else { 4461 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4462 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4463 } 4464 // C99 6.5.2.1p1 4465 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4466 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4467 << IndexExpr->getSourceRange()); 4468 4469 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4470 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4471 && !IndexExpr->isTypeDependent()) 4472 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4473 4474 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4475 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4476 // type. Note that Functions are not objects, and that (in C99 parlance) 4477 // incomplete types are not object types. 4478 if (ResultType->isFunctionType()) { 4479 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4480 << ResultType << BaseExpr->getSourceRange(); 4481 return ExprError(); 4482 } 4483 4484 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4485 // GNU extension: subscripting on pointer to void 4486 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4487 << BaseExpr->getSourceRange(); 4488 4489 // C forbids expressions of unqualified void type from being l-values. 4490 // See IsCForbiddenLValueType. 4491 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4492 } else if (!ResultType->isDependentType() && 4493 RequireCompleteType(LLoc, ResultType, 4494 diag::err_subscript_incomplete_type, BaseExpr)) 4495 return ExprError(); 4496 4497 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4498 !ResultType.isCForbiddenLValueType()); 4499 4500 return new (Context) 4501 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4502 } 4503 4504 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4505 FunctionDecl *FD, 4506 ParmVarDecl *Param) { 4507 if (Param->hasUnparsedDefaultArg()) { 4508 Diag(CallLoc, 4509 diag::err_use_of_default_argument_to_function_declared_later) << 4510 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4511 Diag(UnparsedDefaultArgLocs[Param], 4512 diag::note_default_argument_declared_here); 4513 return ExprError(); 4514 } 4515 4516 if (Param->hasUninstantiatedDefaultArg()) { 4517 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4518 4519 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4520 Param); 4521 4522 // Instantiate the expression. 4523 MultiLevelTemplateArgumentList MutiLevelArgList 4524 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4525 4526 InstantiatingTemplate Inst(*this, CallLoc, Param, 4527 MutiLevelArgList.getInnermost()); 4528 if (Inst.isInvalid()) 4529 return ExprError(); 4530 4531 ExprResult Result; 4532 { 4533 // C++ [dcl.fct.default]p5: 4534 // The names in the [default argument] expression are bound, and 4535 // the semantic constraints are checked, at the point where the 4536 // default argument expression appears. 4537 ContextRAII SavedContext(*this, FD); 4538 LocalInstantiationScope Local(*this); 4539 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4540 } 4541 if (Result.isInvalid()) 4542 return ExprError(); 4543 4544 // Check the expression as an initializer for the parameter. 4545 InitializedEntity Entity 4546 = InitializedEntity::InitializeParameter(Context, Param); 4547 InitializationKind Kind 4548 = InitializationKind::CreateCopy(Param->getLocation(), 4549 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4550 Expr *ResultE = Result.getAs<Expr>(); 4551 4552 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4553 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4554 if (Result.isInvalid()) 4555 return ExprError(); 4556 4557 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4558 Param->getOuterLocStart()); 4559 if (Result.isInvalid()) 4560 return ExprError(); 4561 4562 // Remember the instantiated default argument. 4563 Param->setDefaultArg(Result.getAs<Expr>()); 4564 if (ASTMutationListener *L = getASTMutationListener()) { 4565 L->DefaultArgumentInstantiated(Param); 4566 } 4567 } 4568 4569 // If the default argument expression is not set yet, we are building it now. 4570 if (!Param->hasInit()) { 4571 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4572 Param->setInvalidDecl(); 4573 return ExprError(); 4574 } 4575 4576 // If the default expression creates temporaries, we need to 4577 // push them to the current stack of expression temporaries so they'll 4578 // be properly destroyed. 4579 // FIXME: We should really be rebuilding the default argument with new 4580 // bound temporaries; see the comment in PR5810. 4581 // We don't need to do that with block decls, though, because 4582 // blocks in default argument expression can never capture anything. 4583 if (isa<ExprWithCleanups>(Param->getInit())) { 4584 // Set the "needs cleanups" bit regardless of whether there are 4585 // any explicit objects. 4586 ExprNeedsCleanups = true; 4587 4588 // Append all the objects to the cleanup list. Right now, this 4589 // should always be a no-op, because blocks in default argument 4590 // expressions should never be able to capture anything. 4591 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4592 "default argument expression has capturing blocks?"); 4593 } 4594 4595 // We already type-checked the argument, so we know it works. 4596 // Just mark all of the declarations in this potentially-evaluated expression 4597 // as being "referenced". 4598 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4599 /*SkipLocalVariables=*/true); 4600 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4601 } 4602 4603 4604 Sema::VariadicCallType 4605 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4606 Expr *Fn) { 4607 if (Proto && Proto->isVariadic()) { 4608 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4609 return VariadicConstructor; 4610 else if (Fn && Fn->getType()->isBlockPointerType()) 4611 return VariadicBlock; 4612 else if (FDecl) { 4613 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4614 if (Method->isInstance()) 4615 return VariadicMethod; 4616 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4617 return VariadicMethod; 4618 return VariadicFunction; 4619 } 4620 return VariadicDoesNotApply; 4621 } 4622 4623 namespace { 4624 class FunctionCallCCC : public FunctionCallFilterCCC { 4625 public: 4626 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4627 unsigned NumArgs, MemberExpr *ME) 4628 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4629 FunctionName(FuncName) {} 4630 4631 bool ValidateCandidate(const TypoCorrection &candidate) override { 4632 if (!candidate.getCorrectionSpecifier() || 4633 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4634 return false; 4635 } 4636 4637 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4638 } 4639 4640 private: 4641 const IdentifierInfo *const FunctionName; 4642 }; 4643 } 4644 4645 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4646 FunctionDecl *FDecl, 4647 ArrayRef<Expr *> Args) { 4648 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4649 DeclarationName FuncName = FDecl->getDeclName(); 4650 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4651 4652 if (TypoCorrection Corrected = S.CorrectTypo( 4653 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4654 S.getScopeForContext(S.CurContext), nullptr, 4655 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4656 Args.size(), ME), 4657 Sema::CTK_ErrorRecovery)) { 4658 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4659 if (Corrected.isOverloaded()) { 4660 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4661 OverloadCandidateSet::iterator Best; 4662 for (NamedDecl *CD : Corrected) { 4663 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4664 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4665 OCS); 4666 } 4667 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4668 case OR_Success: 4669 ND = Best->FoundDecl; 4670 Corrected.setCorrectionDecl(ND); 4671 break; 4672 default: 4673 break; 4674 } 4675 } 4676 ND = ND->getUnderlyingDecl(); 4677 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4678 return Corrected; 4679 } 4680 } 4681 return TypoCorrection(); 4682 } 4683 4684 /// ConvertArgumentsForCall - Converts the arguments specified in 4685 /// Args/NumArgs to the parameter types of the function FDecl with 4686 /// function prototype Proto. Call is the call expression itself, and 4687 /// Fn is the function expression. For a C++ member function, this 4688 /// routine does not attempt to convert the object argument. Returns 4689 /// true if the call is ill-formed. 4690 bool 4691 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4692 FunctionDecl *FDecl, 4693 const FunctionProtoType *Proto, 4694 ArrayRef<Expr *> Args, 4695 SourceLocation RParenLoc, 4696 bool IsExecConfig) { 4697 // Bail out early if calling a builtin with custom typechecking. 4698 if (FDecl) 4699 if (unsigned ID = FDecl->getBuiltinID()) 4700 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4701 return false; 4702 4703 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4704 // assignment, to the types of the corresponding parameter, ... 4705 unsigned NumParams = Proto->getNumParams(); 4706 bool Invalid = false; 4707 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4708 unsigned FnKind = Fn->getType()->isBlockPointerType() 4709 ? 1 /* block */ 4710 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4711 : 0 /* function */); 4712 4713 // If too few arguments are available (and we don't have default 4714 // arguments for the remaining parameters), don't make the call. 4715 if (Args.size() < NumParams) { 4716 if (Args.size() < MinArgs) { 4717 TypoCorrection TC; 4718 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4719 unsigned diag_id = 4720 MinArgs == NumParams && !Proto->isVariadic() 4721 ? diag::err_typecheck_call_too_few_args_suggest 4722 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4723 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4724 << static_cast<unsigned>(Args.size()) 4725 << TC.getCorrectionRange()); 4726 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4727 Diag(RParenLoc, 4728 MinArgs == NumParams && !Proto->isVariadic() 4729 ? diag::err_typecheck_call_too_few_args_one 4730 : diag::err_typecheck_call_too_few_args_at_least_one) 4731 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4732 else 4733 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4734 ? diag::err_typecheck_call_too_few_args 4735 : diag::err_typecheck_call_too_few_args_at_least) 4736 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4737 << Fn->getSourceRange(); 4738 4739 // Emit the location of the prototype. 4740 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4741 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4742 << FDecl; 4743 4744 return true; 4745 } 4746 Call->setNumArgs(Context, NumParams); 4747 } 4748 4749 // If too many are passed and not variadic, error on the extras and drop 4750 // them. 4751 if (Args.size() > NumParams) { 4752 if (!Proto->isVariadic()) { 4753 TypoCorrection TC; 4754 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4755 unsigned diag_id = 4756 MinArgs == NumParams && !Proto->isVariadic() 4757 ? diag::err_typecheck_call_too_many_args_suggest 4758 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4759 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4760 << static_cast<unsigned>(Args.size()) 4761 << TC.getCorrectionRange()); 4762 } else if (NumParams == 1 && FDecl && 4763 FDecl->getParamDecl(0)->getDeclName()) 4764 Diag(Args[NumParams]->getLocStart(), 4765 MinArgs == NumParams 4766 ? diag::err_typecheck_call_too_many_args_one 4767 : diag::err_typecheck_call_too_many_args_at_most_one) 4768 << FnKind << FDecl->getParamDecl(0) 4769 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4770 << SourceRange(Args[NumParams]->getLocStart(), 4771 Args.back()->getLocEnd()); 4772 else 4773 Diag(Args[NumParams]->getLocStart(), 4774 MinArgs == NumParams 4775 ? diag::err_typecheck_call_too_many_args 4776 : diag::err_typecheck_call_too_many_args_at_most) 4777 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4778 << Fn->getSourceRange() 4779 << SourceRange(Args[NumParams]->getLocStart(), 4780 Args.back()->getLocEnd()); 4781 4782 // Emit the location of the prototype. 4783 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4784 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4785 << FDecl; 4786 4787 // This deletes the extra arguments. 4788 Call->setNumArgs(Context, NumParams); 4789 return true; 4790 } 4791 } 4792 SmallVector<Expr *, 8> AllArgs; 4793 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4794 4795 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4796 Proto, 0, Args, AllArgs, CallType); 4797 if (Invalid) 4798 return true; 4799 unsigned TotalNumArgs = AllArgs.size(); 4800 for (unsigned i = 0; i < TotalNumArgs; ++i) 4801 Call->setArg(i, AllArgs[i]); 4802 4803 return false; 4804 } 4805 4806 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4807 const FunctionProtoType *Proto, 4808 unsigned FirstParam, ArrayRef<Expr *> Args, 4809 SmallVectorImpl<Expr *> &AllArgs, 4810 VariadicCallType CallType, bool AllowExplicit, 4811 bool IsListInitialization) { 4812 unsigned NumParams = Proto->getNumParams(); 4813 bool Invalid = false; 4814 size_t ArgIx = 0; 4815 // Continue to check argument types (even if we have too few/many args). 4816 for (unsigned i = FirstParam; i < NumParams; i++) { 4817 QualType ProtoArgType = Proto->getParamType(i); 4818 4819 Expr *Arg; 4820 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4821 if (ArgIx < Args.size()) { 4822 Arg = Args[ArgIx++]; 4823 4824 if (RequireCompleteType(Arg->getLocStart(), 4825 ProtoArgType, 4826 diag::err_call_incomplete_argument, Arg)) 4827 return true; 4828 4829 // Strip the unbridged-cast placeholder expression off, if applicable. 4830 bool CFAudited = false; 4831 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4832 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4833 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4834 Arg = stripARCUnbridgedCast(Arg); 4835 else if (getLangOpts().ObjCAutoRefCount && 4836 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4837 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4838 CFAudited = true; 4839 4840 InitializedEntity Entity = 4841 Param ? InitializedEntity::InitializeParameter(Context, Param, 4842 ProtoArgType) 4843 : InitializedEntity::InitializeParameter( 4844 Context, ProtoArgType, Proto->isParamConsumed(i)); 4845 4846 // Remember that parameter belongs to a CF audited API. 4847 if (CFAudited) 4848 Entity.setParameterCFAudited(); 4849 4850 ExprResult ArgE = PerformCopyInitialization( 4851 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4852 if (ArgE.isInvalid()) 4853 return true; 4854 4855 Arg = ArgE.getAs<Expr>(); 4856 } else { 4857 assert(Param && "can't use default arguments without a known callee"); 4858 4859 ExprResult ArgExpr = 4860 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4861 if (ArgExpr.isInvalid()) 4862 return true; 4863 4864 Arg = ArgExpr.getAs<Expr>(); 4865 } 4866 4867 // Check for array bounds violations for each argument to the call. This 4868 // check only triggers warnings when the argument isn't a more complex Expr 4869 // with its own checking, such as a BinaryOperator. 4870 CheckArrayAccess(Arg); 4871 4872 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4873 CheckStaticArrayArgument(CallLoc, Param, Arg); 4874 4875 AllArgs.push_back(Arg); 4876 } 4877 4878 // If this is a variadic call, handle args passed through "...". 4879 if (CallType != VariadicDoesNotApply) { 4880 // Assume that extern "C" functions with variadic arguments that 4881 // return __unknown_anytype aren't *really* variadic. 4882 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4883 FDecl->isExternC()) { 4884 for (Expr *A : Args.slice(ArgIx)) { 4885 QualType paramType; // ignored 4886 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4887 Invalid |= arg.isInvalid(); 4888 AllArgs.push_back(arg.get()); 4889 } 4890 4891 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4892 } else { 4893 for (Expr *A : Args.slice(ArgIx)) { 4894 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4895 Invalid |= Arg.isInvalid(); 4896 AllArgs.push_back(Arg.get()); 4897 } 4898 } 4899 4900 // Check for array bounds violations. 4901 for (Expr *A : Args.slice(ArgIx)) 4902 CheckArrayAccess(A); 4903 } 4904 return Invalid; 4905 } 4906 4907 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4908 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4909 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4910 TL = DTL.getOriginalLoc(); 4911 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4912 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4913 << ATL.getLocalSourceRange(); 4914 } 4915 4916 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4917 /// array parameter, check that it is non-null, and that if it is formed by 4918 /// array-to-pointer decay, the underlying array is sufficiently large. 4919 /// 4920 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4921 /// array type derivation, then for each call to the function, the value of the 4922 /// corresponding actual argument shall provide access to the first element of 4923 /// an array with at least as many elements as specified by the size expression. 4924 void 4925 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4926 ParmVarDecl *Param, 4927 const Expr *ArgExpr) { 4928 // Static array parameters are not supported in C++. 4929 if (!Param || getLangOpts().CPlusPlus) 4930 return; 4931 4932 QualType OrigTy = Param->getOriginalType(); 4933 4934 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4935 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4936 return; 4937 4938 if (ArgExpr->isNullPointerConstant(Context, 4939 Expr::NPC_NeverValueDependent)) { 4940 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4941 DiagnoseCalleeStaticArrayParam(*this, Param); 4942 return; 4943 } 4944 4945 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4946 if (!CAT) 4947 return; 4948 4949 const ConstantArrayType *ArgCAT = 4950 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4951 if (!ArgCAT) 4952 return; 4953 4954 if (ArgCAT->getSize().ult(CAT->getSize())) { 4955 Diag(CallLoc, diag::warn_static_array_too_small) 4956 << ArgExpr->getSourceRange() 4957 << (unsigned) ArgCAT->getSize().getZExtValue() 4958 << (unsigned) CAT->getSize().getZExtValue(); 4959 DiagnoseCalleeStaticArrayParam(*this, Param); 4960 } 4961 } 4962 4963 /// Given a function expression of unknown-any type, try to rebuild it 4964 /// to have a function type. 4965 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4966 4967 /// Is the given type a placeholder that we need to lower out 4968 /// immediately during argument processing? 4969 static bool isPlaceholderToRemoveAsArg(QualType type) { 4970 // Placeholders are never sugared. 4971 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4972 if (!placeholder) return false; 4973 4974 switch (placeholder->getKind()) { 4975 // Ignore all the non-placeholder types. 4976 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4977 case BuiltinType::Id: 4978 #include "clang/Basic/OpenCLImageTypes.def" 4979 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4980 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4981 #include "clang/AST/BuiltinTypes.def" 4982 return false; 4983 4984 // We cannot lower out overload sets; they might validly be resolved 4985 // by the call machinery. 4986 case BuiltinType::Overload: 4987 return false; 4988 4989 // Unbridged casts in ARC can be handled in some call positions and 4990 // should be left in place. 4991 case BuiltinType::ARCUnbridgedCast: 4992 return false; 4993 4994 // Pseudo-objects should be converted as soon as possible. 4995 case BuiltinType::PseudoObject: 4996 return true; 4997 4998 // The debugger mode could theoretically but currently does not try 4999 // to resolve unknown-typed arguments based on known parameter types. 5000 case BuiltinType::UnknownAny: 5001 return true; 5002 5003 // These are always invalid as call arguments and should be reported. 5004 case BuiltinType::BoundMember: 5005 case BuiltinType::BuiltinFn: 5006 case BuiltinType::OMPArraySection: 5007 return true; 5008 5009 } 5010 llvm_unreachable("bad builtin type kind"); 5011 } 5012 5013 /// Check an argument list for placeholders that we won't try to 5014 /// handle later. 5015 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5016 // Apply this processing to all the arguments at once instead of 5017 // dying at the first failure. 5018 bool hasInvalid = false; 5019 for (size_t i = 0, e = args.size(); i != e; i++) { 5020 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5021 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5022 if (result.isInvalid()) hasInvalid = true; 5023 else args[i] = result.get(); 5024 } else if (hasInvalid) { 5025 (void)S.CorrectDelayedTyposInExpr(args[i]); 5026 } 5027 } 5028 return hasInvalid; 5029 } 5030 5031 /// If a builtin function has a pointer argument with no explicit address 5032 /// space, then it should be able to accept a pointer to any address 5033 /// space as input. In order to do this, we need to replace the 5034 /// standard builtin declaration with one that uses the same address space 5035 /// as the call. 5036 /// 5037 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5038 /// it does not contain any pointer arguments without 5039 /// an address space qualifer. Otherwise the rewritten 5040 /// FunctionDecl is returned. 5041 /// TODO: Handle pointer return types. 5042 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5043 const FunctionDecl *FDecl, 5044 MultiExprArg ArgExprs) { 5045 5046 QualType DeclType = FDecl->getType(); 5047 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5048 5049 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5050 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5051 return nullptr; 5052 5053 bool NeedsNewDecl = false; 5054 unsigned i = 0; 5055 SmallVector<QualType, 8> OverloadParams; 5056 5057 for (QualType ParamType : FT->param_types()) { 5058 5059 // Convert array arguments to pointer to simplify type lookup. 5060 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 5061 QualType ArgType = Arg->getType(); 5062 if (!ParamType->isPointerType() || 5063 ParamType.getQualifiers().hasAddressSpace() || 5064 !ArgType->isPointerType() || 5065 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5066 OverloadParams.push_back(ParamType); 5067 continue; 5068 } 5069 5070 NeedsNewDecl = true; 5071 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5072 5073 QualType PointeeType = ParamType->getPointeeType(); 5074 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5075 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5076 } 5077 5078 if (!NeedsNewDecl) 5079 return nullptr; 5080 5081 FunctionProtoType::ExtProtoInfo EPI; 5082 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5083 OverloadParams, EPI); 5084 DeclContext *Parent = Context.getTranslationUnitDecl(); 5085 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5086 FDecl->getLocation(), 5087 FDecl->getLocation(), 5088 FDecl->getIdentifier(), 5089 OverloadTy, 5090 /*TInfo=*/nullptr, 5091 SC_Extern, false, 5092 /*hasPrototype=*/true); 5093 SmallVector<ParmVarDecl*, 16> Params; 5094 FT = cast<FunctionProtoType>(OverloadTy); 5095 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5096 QualType ParamType = FT->getParamType(i); 5097 ParmVarDecl *Parm = 5098 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5099 SourceLocation(), nullptr, ParamType, 5100 /*TInfo=*/nullptr, SC_None, nullptr); 5101 Parm->setScopeInfo(0, i); 5102 Params.push_back(Parm); 5103 } 5104 OverloadDecl->setParams(Params); 5105 return OverloadDecl; 5106 } 5107 5108 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5109 std::size_t NumArgs) { 5110 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5111 /*PartialOverloading=*/false)) 5112 return Callee->isVariadic(); 5113 return Callee->getMinRequiredArguments() <= NumArgs; 5114 } 5115 5116 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5117 /// This provides the location of the left/right parens and a list of comma 5118 /// locations. 5119 ExprResult 5120 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5121 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5122 Expr *ExecConfig, bool IsExecConfig) { 5123 // Since this might be a postfix expression, get rid of ParenListExprs. 5124 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5125 if (Result.isInvalid()) return ExprError(); 5126 Fn = Result.get(); 5127 5128 if (checkArgsForPlaceholders(*this, ArgExprs)) 5129 return ExprError(); 5130 5131 if (getLangOpts().CPlusPlus) { 5132 // If this is a pseudo-destructor expression, build the call immediately. 5133 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5134 if (!ArgExprs.empty()) { 5135 // Pseudo-destructor calls should not have any arguments. 5136 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5137 << FixItHint::CreateRemoval( 5138 SourceRange(ArgExprs.front()->getLocStart(), 5139 ArgExprs.back()->getLocEnd())); 5140 } 5141 5142 return new (Context) 5143 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5144 } 5145 if (Fn->getType() == Context.PseudoObjectTy) { 5146 ExprResult result = CheckPlaceholderExpr(Fn); 5147 if (result.isInvalid()) return ExprError(); 5148 Fn = result.get(); 5149 } 5150 5151 // Determine whether this is a dependent call inside a C++ template, 5152 // in which case we won't do any semantic analysis now. 5153 bool Dependent = false; 5154 if (Fn->isTypeDependent()) 5155 Dependent = true; 5156 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5157 Dependent = true; 5158 5159 if (Dependent) { 5160 if (ExecConfig) { 5161 return new (Context) CUDAKernelCallExpr( 5162 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5163 Context.DependentTy, VK_RValue, RParenLoc); 5164 } else { 5165 return new (Context) CallExpr( 5166 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5167 } 5168 } 5169 5170 // Determine whether this is a call to an object (C++ [over.call.object]). 5171 if (Fn->getType()->isRecordType()) 5172 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5173 RParenLoc); 5174 5175 if (Fn->getType() == Context.UnknownAnyTy) { 5176 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5177 if (result.isInvalid()) return ExprError(); 5178 Fn = result.get(); 5179 } 5180 5181 if (Fn->getType() == Context.BoundMemberTy) { 5182 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5183 } 5184 } 5185 5186 // Check for overloaded calls. This can happen even in C due to extensions. 5187 if (Fn->getType() == Context.OverloadTy) { 5188 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5189 5190 // We aren't supposed to apply this logic for if there's an '&' involved. 5191 if (!find.HasFormOfMemberPointer) { 5192 OverloadExpr *ovl = find.Expression; 5193 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5194 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5195 RParenLoc, ExecConfig, 5196 /*AllowTypoCorrection=*/true, 5197 find.IsAddressOfOperand); 5198 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5199 } 5200 } 5201 5202 // If we're directly calling a function, get the appropriate declaration. 5203 if (Fn->getType() == Context.UnknownAnyTy) { 5204 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5205 if (result.isInvalid()) return ExprError(); 5206 Fn = result.get(); 5207 } 5208 5209 Expr *NakedFn = Fn->IgnoreParens(); 5210 5211 bool CallingNDeclIndirectly = false; 5212 NamedDecl *NDecl = nullptr; 5213 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5214 if (UnOp->getOpcode() == UO_AddrOf) { 5215 CallingNDeclIndirectly = true; 5216 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5217 } 5218 } 5219 5220 if (isa<DeclRefExpr>(NakedFn)) { 5221 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5222 5223 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5224 if (FDecl && FDecl->getBuiltinID()) { 5225 // Rewrite the function decl for this builtin by replacing parameters 5226 // with no explicit address space with the address space of the arguments 5227 // in ArgExprs. 5228 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5229 NDecl = FDecl; 5230 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5231 SourceLocation(), FDecl, false, 5232 SourceLocation(), FDecl->getType(), 5233 Fn->getValueKind(), FDecl); 5234 } 5235 } 5236 } else if (isa<MemberExpr>(NakedFn)) 5237 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5238 5239 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5240 if (CallingNDeclIndirectly && 5241 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5242 Fn->getLocStart())) 5243 return ExprError(); 5244 5245 // CheckEnableIf assumes that the we're passing in a sane number of args for 5246 // FD, but that doesn't always hold true here. This is because, in some 5247 // cases, we'll emit a diag about an ill-formed function call, but then 5248 // we'll continue on as if the function call wasn't ill-formed. So, if the 5249 // number of args looks incorrect, don't do enable_if checks; we should've 5250 // already emitted an error about the bad call. 5251 if (FD->hasAttr<EnableIfAttr>() && 5252 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5253 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5254 Diag(Fn->getLocStart(), 5255 isa<CXXMethodDecl>(FD) ? 5256 diag::err_ovl_no_viable_member_function_in_call : 5257 diag::err_ovl_no_viable_function_in_call) 5258 << FD << FD->getSourceRange(); 5259 Diag(FD->getLocation(), 5260 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5261 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5262 } 5263 } 5264 } 5265 5266 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5267 ExecConfig, IsExecConfig); 5268 } 5269 5270 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5271 /// 5272 /// __builtin_astype( value, dst type ) 5273 /// 5274 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5275 SourceLocation BuiltinLoc, 5276 SourceLocation RParenLoc) { 5277 ExprValueKind VK = VK_RValue; 5278 ExprObjectKind OK = OK_Ordinary; 5279 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5280 QualType SrcTy = E->getType(); 5281 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5282 return ExprError(Diag(BuiltinLoc, 5283 diag::err_invalid_astype_of_different_size) 5284 << DstTy 5285 << SrcTy 5286 << E->getSourceRange()); 5287 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5288 } 5289 5290 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5291 /// provided arguments. 5292 /// 5293 /// __builtin_convertvector( value, dst type ) 5294 /// 5295 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5296 SourceLocation BuiltinLoc, 5297 SourceLocation RParenLoc) { 5298 TypeSourceInfo *TInfo; 5299 GetTypeFromParser(ParsedDestTy, &TInfo); 5300 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5301 } 5302 5303 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5304 /// i.e. an expression not of \p OverloadTy. The expression should 5305 /// unary-convert to an expression of function-pointer or 5306 /// block-pointer type. 5307 /// 5308 /// \param NDecl the declaration being called, if available 5309 ExprResult 5310 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5311 SourceLocation LParenLoc, 5312 ArrayRef<Expr *> Args, 5313 SourceLocation RParenLoc, 5314 Expr *Config, bool IsExecConfig) { 5315 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5316 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5317 5318 // Functions with 'interrupt' attribute cannot be called directly. 5319 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5320 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5321 return ExprError(); 5322 } 5323 5324 // Promote the function operand. 5325 // We special-case function promotion here because we only allow promoting 5326 // builtin functions to function pointers in the callee of a call. 5327 ExprResult Result; 5328 if (BuiltinID && 5329 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5330 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5331 CK_BuiltinFnToFnPtr).get(); 5332 } else { 5333 Result = CallExprUnaryConversions(Fn); 5334 } 5335 if (Result.isInvalid()) 5336 return ExprError(); 5337 Fn = Result.get(); 5338 5339 // Make the call expr early, before semantic checks. This guarantees cleanup 5340 // of arguments and function on error. 5341 CallExpr *TheCall; 5342 if (Config) 5343 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5344 cast<CallExpr>(Config), Args, 5345 Context.BoolTy, VK_RValue, 5346 RParenLoc); 5347 else 5348 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5349 VK_RValue, RParenLoc); 5350 5351 if (!getLangOpts().CPlusPlus) { 5352 // C cannot always handle TypoExpr nodes in builtin calls and direct 5353 // function calls as their argument checking don't necessarily handle 5354 // dependent types properly, so make sure any TypoExprs have been 5355 // dealt with. 5356 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5357 if (!Result.isUsable()) return ExprError(); 5358 TheCall = dyn_cast<CallExpr>(Result.get()); 5359 if (!TheCall) return Result; 5360 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5361 } 5362 5363 // Bail out early if calling a builtin with custom typechecking. 5364 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5365 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5366 5367 retry: 5368 const FunctionType *FuncT; 5369 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5370 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5371 // have type pointer to function". 5372 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5373 if (!FuncT) 5374 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5375 << Fn->getType() << Fn->getSourceRange()); 5376 } else if (const BlockPointerType *BPT = 5377 Fn->getType()->getAs<BlockPointerType>()) { 5378 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5379 } else { 5380 // Handle calls to expressions of unknown-any type. 5381 if (Fn->getType() == Context.UnknownAnyTy) { 5382 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5383 if (rewrite.isInvalid()) return ExprError(); 5384 Fn = rewrite.get(); 5385 TheCall->setCallee(Fn); 5386 goto retry; 5387 } 5388 5389 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5390 << Fn->getType() << Fn->getSourceRange()); 5391 } 5392 5393 if (getLangOpts().CUDA) { 5394 if (Config) { 5395 // CUDA: Kernel calls must be to global functions 5396 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5397 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5398 << FDecl->getName() << Fn->getSourceRange()); 5399 5400 // CUDA: Kernel function must have 'void' return type 5401 if (!FuncT->getReturnType()->isVoidType()) 5402 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5403 << Fn->getType() << Fn->getSourceRange()); 5404 } else { 5405 // CUDA: Calls to global functions must be configured 5406 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5407 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5408 << FDecl->getName() << Fn->getSourceRange()); 5409 } 5410 } 5411 5412 // Check for a valid return type 5413 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5414 FDecl)) 5415 return ExprError(); 5416 5417 // We know the result type of the call, set it. 5418 TheCall->setType(FuncT->getCallResultType(Context)); 5419 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5420 5421 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5422 if (Proto) { 5423 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5424 IsExecConfig)) 5425 return ExprError(); 5426 } else { 5427 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5428 5429 if (FDecl) { 5430 // Check if we have too few/too many template arguments, based 5431 // on our knowledge of the function definition. 5432 const FunctionDecl *Def = nullptr; 5433 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5434 Proto = Def->getType()->getAs<FunctionProtoType>(); 5435 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5436 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5437 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5438 } 5439 5440 // If the function we're calling isn't a function prototype, but we have 5441 // a function prototype from a prior declaratiom, use that prototype. 5442 if (!FDecl->hasPrototype()) 5443 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5444 } 5445 5446 // Promote the arguments (C99 6.5.2.2p6). 5447 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5448 Expr *Arg = Args[i]; 5449 5450 if (Proto && i < Proto->getNumParams()) { 5451 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5452 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5453 ExprResult ArgE = 5454 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5455 if (ArgE.isInvalid()) 5456 return true; 5457 5458 Arg = ArgE.getAs<Expr>(); 5459 5460 } else { 5461 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5462 5463 if (ArgE.isInvalid()) 5464 return true; 5465 5466 Arg = ArgE.getAs<Expr>(); 5467 } 5468 5469 if (RequireCompleteType(Arg->getLocStart(), 5470 Arg->getType(), 5471 diag::err_call_incomplete_argument, Arg)) 5472 return ExprError(); 5473 5474 TheCall->setArg(i, Arg); 5475 } 5476 } 5477 5478 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5479 if (!Method->isStatic()) 5480 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5481 << Fn->getSourceRange()); 5482 5483 // Check for sentinels 5484 if (NDecl) 5485 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5486 5487 // Do special checking on direct calls to functions. 5488 if (FDecl) { 5489 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5490 return ExprError(); 5491 5492 if (BuiltinID) 5493 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5494 } else if (NDecl) { 5495 if (CheckPointerCall(NDecl, TheCall, Proto)) 5496 return ExprError(); 5497 } else { 5498 if (CheckOtherCall(TheCall, Proto)) 5499 return ExprError(); 5500 } 5501 5502 return MaybeBindToTemporary(TheCall); 5503 } 5504 5505 ExprResult 5506 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5507 SourceLocation RParenLoc, Expr *InitExpr) { 5508 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5509 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5510 5511 TypeSourceInfo *TInfo; 5512 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5513 if (!TInfo) 5514 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5515 5516 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5517 } 5518 5519 ExprResult 5520 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5521 SourceLocation RParenLoc, Expr *LiteralExpr) { 5522 QualType literalType = TInfo->getType(); 5523 5524 if (literalType->isArrayType()) { 5525 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5526 diag::err_illegal_decl_array_incomplete_type, 5527 SourceRange(LParenLoc, 5528 LiteralExpr->getSourceRange().getEnd()))) 5529 return ExprError(); 5530 if (literalType->isVariableArrayType()) 5531 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5532 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5533 } else if (!literalType->isDependentType() && 5534 RequireCompleteType(LParenLoc, literalType, 5535 diag::err_typecheck_decl_incomplete_type, 5536 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5537 return ExprError(); 5538 5539 InitializedEntity Entity 5540 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5541 InitializationKind Kind 5542 = InitializationKind::CreateCStyleCast(LParenLoc, 5543 SourceRange(LParenLoc, RParenLoc), 5544 /*InitList=*/true); 5545 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5546 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5547 &literalType); 5548 if (Result.isInvalid()) 5549 return ExprError(); 5550 LiteralExpr = Result.get(); 5551 5552 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5553 if (isFileScope && 5554 !LiteralExpr->isTypeDependent() && 5555 !LiteralExpr->isValueDependent() && 5556 !literalType->isDependentType()) { // 6.5.2.5p3 5557 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5558 return ExprError(); 5559 } 5560 5561 // In C, compound literals are l-values for some reason. 5562 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5563 5564 return MaybeBindToTemporary( 5565 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5566 VK, LiteralExpr, isFileScope)); 5567 } 5568 5569 ExprResult 5570 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5571 SourceLocation RBraceLoc) { 5572 // Immediately handle non-overload placeholders. Overloads can be 5573 // resolved contextually, but everything else here can't. 5574 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5575 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5576 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5577 5578 // Ignore failures; dropping the entire initializer list because 5579 // of one failure would be terrible for indexing/etc. 5580 if (result.isInvalid()) continue; 5581 5582 InitArgList[I] = result.get(); 5583 } 5584 } 5585 5586 // Semantic analysis for initializers is done by ActOnDeclarator() and 5587 // CheckInitializer() - it requires knowledge of the object being intialized. 5588 5589 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5590 RBraceLoc); 5591 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5592 return E; 5593 } 5594 5595 /// Do an explicit extend of the given block pointer if we're in ARC. 5596 void Sema::maybeExtendBlockObject(ExprResult &E) { 5597 assert(E.get()->getType()->isBlockPointerType()); 5598 assert(E.get()->isRValue()); 5599 5600 // Only do this in an r-value context. 5601 if (!getLangOpts().ObjCAutoRefCount) return; 5602 5603 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5604 CK_ARCExtendBlockObject, E.get(), 5605 /*base path*/ nullptr, VK_RValue); 5606 ExprNeedsCleanups = true; 5607 } 5608 5609 /// Prepare a conversion of the given expression to an ObjC object 5610 /// pointer type. 5611 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5612 QualType type = E.get()->getType(); 5613 if (type->isObjCObjectPointerType()) { 5614 return CK_BitCast; 5615 } else if (type->isBlockPointerType()) { 5616 maybeExtendBlockObject(E); 5617 return CK_BlockPointerToObjCPointerCast; 5618 } else { 5619 assert(type->isPointerType()); 5620 return CK_CPointerToObjCPointerCast; 5621 } 5622 } 5623 5624 /// Prepares for a scalar cast, performing all the necessary stages 5625 /// except the final cast and returning the kind required. 5626 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5627 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5628 // Also, callers should have filtered out the invalid cases with 5629 // pointers. Everything else should be possible. 5630 5631 QualType SrcTy = Src.get()->getType(); 5632 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5633 return CK_NoOp; 5634 5635 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5636 case Type::STK_MemberPointer: 5637 llvm_unreachable("member pointer type in C"); 5638 5639 case Type::STK_CPointer: 5640 case Type::STK_BlockPointer: 5641 case Type::STK_ObjCObjectPointer: 5642 switch (DestTy->getScalarTypeKind()) { 5643 case Type::STK_CPointer: { 5644 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5645 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5646 if (SrcAS != DestAS) 5647 return CK_AddressSpaceConversion; 5648 return CK_BitCast; 5649 } 5650 case Type::STK_BlockPointer: 5651 return (SrcKind == Type::STK_BlockPointer 5652 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5653 case Type::STK_ObjCObjectPointer: 5654 if (SrcKind == Type::STK_ObjCObjectPointer) 5655 return CK_BitCast; 5656 if (SrcKind == Type::STK_CPointer) 5657 return CK_CPointerToObjCPointerCast; 5658 maybeExtendBlockObject(Src); 5659 return CK_BlockPointerToObjCPointerCast; 5660 case Type::STK_Bool: 5661 return CK_PointerToBoolean; 5662 case Type::STK_Integral: 5663 return CK_PointerToIntegral; 5664 case Type::STK_Floating: 5665 case Type::STK_FloatingComplex: 5666 case Type::STK_IntegralComplex: 5667 case Type::STK_MemberPointer: 5668 llvm_unreachable("illegal cast from pointer"); 5669 } 5670 llvm_unreachable("Should have returned before this"); 5671 5672 case Type::STK_Bool: // casting from bool is like casting from an integer 5673 case Type::STK_Integral: 5674 switch (DestTy->getScalarTypeKind()) { 5675 case Type::STK_CPointer: 5676 case Type::STK_ObjCObjectPointer: 5677 case Type::STK_BlockPointer: 5678 if (Src.get()->isNullPointerConstant(Context, 5679 Expr::NPC_ValueDependentIsNull)) 5680 return CK_NullToPointer; 5681 return CK_IntegralToPointer; 5682 case Type::STK_Bool: 5683 return CK_IntegralToBoolean; 5684 case Type::STK_Integral: 5685 return CK_IntegralCast; 5686 case Type::STK_Floating: 5687 return CK_IntegralToFloating; 5688 case Type::STK_IntegralComplex: 5689 Src = ImpCastExprToType(Src.get(), 5690 DestTy->castAs<ComplexType>()->getElementType(), 5691 CK_IntegralCast); 5692 return CK_IntegralRealToComplex; 5693 case Type::STK_FloatingComplex: 5694 Src = ImpCastExprToType(Src.get(), 5695 DestTy->castAs<ComplexType>()->getElementType(), 5696 CK_IntegralToFloating); 5697 return CK_FloatingRealToComplex; 5698 case Type::STK_MemberPointer: 5699 llvm_unreachable("member pointer type in C"); 5700 } 5701 llvm_unreachable("Should have returned before this"); 5702 5703 case Type::STK_Floating: 5704 switch (DestTy->getScalarTypeKind()) { 5705 case Type::STK_Floating: 5706 return CK_FloatingCast; 5707 case Type::STK_Bool: 5708 return CK_FloatingToBoolean; 5709 case Type::STK_Integral: 5710 return CK_FloatingToIntegral; 5711 case Type::STK_FloatingComplex: 5712 Src = ImpCastExprToType(Src.get(), 5713 DestTy->castAs<ComplexType>()->getElementType(), 5714 CK_FloatingCast); 5715 return CK_FloatingRealToComplex; 5716 case Type::STK_IntegralComplex: 5717 Src = ImpCastExprToType(Src.get(), 5718 DestTy->castAs<ComplexType>()->getElementType(), 5719 CK_FloatingToIntegral); 5720 return CK_IntegralRealToComplex; 5721 case Type::STK_CPointer: 5722 case Type::STK_ObjCObjectPointer: 5723 case Type::STK_BlockPointer: 5724 llvm_unreachable("valid float->pointer cast?"); 5725 case Type::STK_MemberPointer: 5726 llvm_unreachable("member pointer type in C"); 5727 } 5728 llvm_unreachable("Should have returned before this"); 5729 5730 case Type::STK_FloatingComplex: 5731 switch (DestTy->getScalarTypeKind()) { 5732 case Type::STK_FloatingComplex: 5733 return CK_FloatingComplexCast; 5734 case Type::STK_IntegralComplex: 5735 return CK_FloatingComplexToIntegralComplex; 5736 case Type::STK_Floating: { 5737 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5738 if (Context.hasSameType(ET, DestTy)) 5739 return CK_FloatingComplexToReal; 5740 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5741 return CK_FloatingCast; 5742 } 5743 case Type::STK_Bool: 5744 return CK_FloatingComplexToBoolean; 5745 case Type::STK_Integral: 5746 Src = ImpCastExprToType(Src.get(), 5747 SrcTy->castAs<ComplexType>()->getElementType(), 5748 CK_FloatingComplexToReal); 5749 return CK_FloatingToIntegral; 5750 case Type::STK_CPointer: 5751 case Type::STK_ObjCObjectPointer: 5752 case Type::STK_BlockPointer: 5753 llvm_unreachable("valid complex float->pointer cast?"); 5754 case Type::STK_MemberPointer: 5755 llvm_unreachable("member pointer type in C"); 5756 } 5757 llvm_unreachable("Should have returned before this"); 5758 5759 case Type::STK_IntegralComplex: 5760 switch (DestTy->getScalarTypeKind()) { 5761 case Type::STK_FloatingComplex: 5762 return CK_IntegralComplexToFloatingComplex; 5763 case Type::STK_IntegralComplex: 5764 return CK_IntegralComplexCast; 5765 case Type::STK_Integral: { 5766 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5767 if (Context.hasSameType(ET, DestTy)) 5768 return CK_IntegralComplexToReal; 5769 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5770 return CK_IntegralCast; 5771 } 5772 case Type::STK_Bool: 5773 return CK_IntegralComplexToBoolean; 5774 case Type::STK_Floating: 5775 Src = ImpCastExprToType(Src.get(), 5776 SrcTy->castAs<ComplexType>()->getElementType(), 5777 CK_IntegralComplexToReal); 5778 return CK_IntegralToFloating; 5779 case Type::STK_CPointer: 5780 case Type::STK_ObjCObjectPointer: 5781 case Type::STK_BlockPointer: 5782 llvm_unreachable("valid complex int->pointer cast?"); 5783 case Type::STK_MemberPointer: 5784 llvm_unreachable("member pointer type in C"); 5785 } 5786 llvm_unreachable("Should have returned before this"); 5787 } 5788 5789 llvm_unreachable("Unhandled scalar cast"); 5790 } 5791 5792 static bool breakDownVectorType(QualType type, uint64_t &len, 5793 QualType &eltType) { 5794 // Vectors are simple. 5795 if (const VectorType *vecType = type->getAs<VectorType>()) { 5796 len = vecType->getNumElements(); 5797 eltType = vecType->getElementType(); 5798 assert(eltType->isScalarType()); 5799 return true; 5800 } 5801 5802 // We allow lax conversion to and from non-vector types, but only if 5803 // they're real types (i.e. non-complex, non-pointer scalar types). 5804 if (!type->isRealType()) return false; 5805 5806 len = 1; 5807 eltType = type; 5808 return true; 5809 } 5810 5811 /// Are the two types lax-compatible vector types? That is, given 5812 /// that one of them is a vector, do they have equal storage sizes, 5813 /// where the storage size is the number of elements times the element 5814 /// size? 5815 /// 5816 /// This will also return false if either of the types is neither a 5817 /// vector nor a real type. 5818 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5819 assert(destTy->isVectorType() || srcTy->isVectorType()); 5820 5821 // Disallow lax conversions between scalars and ExtVectors (these 5822 // conversions are allowed for other vector types because common headers 5823 // depend on them). Most scalar OP ExtVector cases are handled by the 5824 // splat path anyway, which does what we want (convert, not bitcast). 5825 // What this rules out for ExtVectors is crazy things like char4*float. 5826 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5827 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5828 5829 uint64_t srcLen, destLen; 5830 QualType srcEltTy, destEltTy; 5831 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5832 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5833 5834 // ASTContext::getTypeSize will return the size rounded up to a 5835 // power of 2, so instead of using that, we need to use the raw 5836 // element size multiplied by the element count. 5837 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5838 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5839 5840 return (srcLen * srcEltSize == destLen * destEltSize); 5841 } 5842 5843 /// Is this a legal conversion between two types, one of which is 5844 /// known to be a vector type? 5845 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5846 assert(destTy->isVectorType() || srcTy->isVectorType()); 5847 5848 if (!Context.getLangOpts().LaxVectorConversions) 5849 return false; 5850 return areLaxCompatibleVectorTypes(srcTy, destTy); 5851 } 5852 5853 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5854 CastKind &Kind) { 5855 assert(VectorTy->isVectorType() && "Not a vector type!"); 5856 5857 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5858 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5859 return Diag(R.getBegin(), 5860 Ty->isVectorType() ? 5861 diag::err_invalid_conversion_between_vectors : 5862 diag::err_invalid_conversion_between_vector_and_integer) 5863 << VectorTy << Ty << R; 5864 } else 5865 return Diag(R.getBegin(), 5866 diag::err_invalid_conversion_between_vector_and_scalar) 5867 << VectorTy << Ty << R; 5868 5869 Kind = CK_BitCast; 5870 return false; 5871 } 5872 5873 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5874 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5875 5876 if (DestElemTy == SplattedExpr->getType()) 5877 return SplattedExpr; 5878 5879 assert(DestElemTy->isFloatingType() || 5880 DestElemTy->isIntegralOrEnumerationType()); 5881 5882 CastKind CK; 5883 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5884 // OpenCL requires that we convert `true` boolean expressions to -1, but 5885 // only when splatting vectors. 5886 if (DestElemTy->isFloatingType()) { 5887 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5888 // in two steps: boolean to signed integral, then to floating. 5889 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5890 CK_BooleanToSignedIntegral); 5891 SplattedExpr = CastExprRes.get(); 5892 CK = CK_IntegralToFloating; 5893 } else { 5894 CK = CK_BooleanToSignedIntegral; 5895 } 5896 } else { 5897 ExprResult CastExprRes = SplattedExpr; 5898 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5899 if (CastExprRes.isInvalid()) 5900 return ExprError(); 5901 SplattedExpr = CastExprRes.get(); 5902 } 5903 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5904 } 5905 5906 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5907 Expr *CastExpr, CastKind &Kind) { 5908 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5909 5910 QualType SrcTy = CastExpr->getType(); 5911 5912 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5913 // an ExtVectorType. 5914 // In OpenCL, casts between vectors of different types are not allowed. 5915 // (See OpenCL 6.2). 5916 if (SrcTy->isVectorType()) { 5917 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5918 || (getLangOpts().OpenCL && 5919 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5920 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5921 << DestTy << SrcTy << R; 5922 return ExprError(); 5923 } 5924 Kind = CK_BitCast; 5925 return CastExpr; 5926 } 5927 5928 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5929 // conversion will take place first from scalar to elt type, and then 5930 // splat from elt type to vector. 5931 if (SrcTy->isPointerType()) 5932 return Diag(R.getBegin(), 5933 diag::err_invalid_conversion_between_vector_and_scalar) 5934 << DestTy << SrcTy << R; 5935 5936 Kind = CK_VectorSplat; 5937 return prepareVectorSplat(DestTy, CastExpr); 5938 } 5939 5940 ExprResult 5941 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5942 Declarator &D, ParsedType &Ty, 5943 SourceLocation RParenLoc, Expr *CastExpr) { 5944 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5945 "ActOnCastExpr(): missing type or expr"); 5946 5947 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5948 if (D.isInvalidType()) 5949 return ExprError(); 5950 5951 if (getLangOpts().CPlusPlus) { 5952 // Check that there are no default arguments (C++ only). 5953 CheckExtraCXXDefaultArguments(D); 5954 } else { 5955 // Make sure any TypoExprs have been dealt with. 5956 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5957 if (!Res.isUsable()) 5958 return ExprError(); 5959 CastExpr = Res.get(); 5960 } 5961 5962 checkUnusedDeclAttributes(D); 5963 5964 QualType castType = castTInfo->getType(); 5965 Ty = CreateParsedType(castType, castTInfo); 5966 5967 bool isVectorLiteral = false; 5968 5969 // Check for an altivec or OpenCL literal, 5970 // i.e. all the elements are integer constants. 5971 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5972 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5973 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5974 && castType->isVectorType() && (PE || PLE)) { 5975 if (PLE && PLE->getNumExprs() == 0) { 5976 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5977 return ExprError(); 5978 } 5979 if (PE || PLE->getNumExprs() == 1) { 5980 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5981 if (!E->getType()->isVectorType()) 5982 isVectorLiteral = true; 5983 } 5984 else 5985 isVectorLiteral = true; 5986 } 5987 5988 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5989 // then handle it as such. 5990 if (isVectorLiteral) 5991 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5992 5993 // If the Expr being casted is a ParenListExpr, handle it specially. 5994 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5995 // sequence of BinOp comma operators. 5996 if (isa<ParenListExpr>(CastExpr)) { 5997 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5998 if (Result.isInvalid()) return ExprError(); 5999 CastExpr = Result.get(); 6000 } 6001 6002 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6003 !getSourceManager().isInSystemMacro(LParenLoc)) 6004 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6005 6006 CheckTollFreeBridgeCast(castType, CastExpr); 6007 6008 CheckObjCBridgeRelatedCast(castType, CastExpr); 6009 6010 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6011 } 6012 6013 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6014 SourceLocation RParenLoc, Expr *E, 6015 TypeSourceInfo *TInfo) { 6016 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6017 "Expected paren or paren list expression"); 6018 6019 Expr **exprs; 6020 unsigned numExprs; 6021 Expr *subExpr; 6022 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6023 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6024 LiteralLParenLoc = PE->getLParenLoc(); 6025 LiteralRParenLoc = PE->getRParenLoc(); 6026 exprs = PE->getExprs(); 6027 numExprs = PE->getNumExprs(); 6028 } else { // isa<ParenExpr> by assertion at function entrance 6029 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6030 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6031 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6032 exprs = &subExpr; 6033 numExprs = 1; 6034 } 6035 6036 QualType Ty = TInfo->getType(); 6037 assert(Ty->isVectorType() && "Expected vector type"); 6038 6039 SmallVector<Expr *, 8> initExprs; 6040 const VectorType *VTy = Ty->getAs<VectorType>(); 6041 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6042 6043 // '(...)' form of vector initialization in AltiVec: the number of 6044 // initializers must be one or must match the size of the vector. 6045 // If a single value is specified in the initializer then it will be 6046 // replicated to all the components of the vector 6047 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6048 // The number of initializers must be one or must match the size of the 6049 // vector. If a single value is specified in the initializer then it will 6050 // be replicated to all the components of the vector 6051 if (numExprs == 1) { 6052 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6053 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6054 if (Literal.isInvalid()) 6055 return ExprError(); 6056 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6057 PrepareScalarCast(Literal, ElemTy)); 6058 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6059 } 6060 else if (numExprs < numElems) { 6061 Diag(E->getExprLoc(), 6062 diag::err_incorrect_number_of_vector_initializers); 6063 return ExprError(); 6064 } 6065 else 6066 initExprs.append(exprs, exprs + numExprs); 6067 } 6068 else { 6069 // For OpenCL, when the number of initializers is a single value, 6070 // it will be replicated to all components of the vector. 6071 if (getLangOpts().OpenCL && 6072 VTy->getVectorKind() == VectorType::GenericVector && 6073 numExprs == 1) { 6074 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6075 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6076 if (Literal.isInvalid()) 6077 return ExprError(); 6078 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6079 PrepareScalarCast(Literal, ElemTy)); 6080 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6081 } 6082 6083 initExprs.append(exprs, exprs + numExprs); 6084 } 6085 // FIXME: This means that pretty-printing the final AST will produce curly 6086 // braces instead of the original commas. 6087 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6088 initExprs, LiteralRParenLoc); 6089 initE->setType(Ty); 6090 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6091 } 6092 6093 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6094 /// the ParenListExpr into a sequence of comma binary operators. 6095 ExprResult 6096 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6097 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6098 if (!E) 6099 return OrigExpr; 6100 6101 ExprResult Result(E->getExpr(0)); 6102 6103 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6104 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6105 E->getExpr(i)); 6106 6107 if (Result.isInvalid()) return ExprError(); 6108 6109 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6110 } 6111 6112 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6113 SourceLocation R, 6114 MultiExprArg Val) { 6115 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6116 return expr; 6117 } 6118 6119 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6120 /// constant and the other is not a pointer. Returns true if a diagnostic is 6121 /// emitted. 6122 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6123 SourceLocation QuestionLoc) { 6124 Expr *NullExpr = LHSExpr; 6125 Expr *NonPointerExpr = RHSExpr; 6126 Expr::NullPointerConstantKind NullKind = 6127 NullExpr->isNullPointerConstant(Context, 6128 Expr::NPC_ValueDependentIsNotNull); 6129 6130 if (NullKind == Expr::NPCK_NotNull) { 6131 NullExpr = RHSExpr; 6132 NonPointerExpr = LHSExpr; 6133 NullKind = 6134 NullExpr->isNullPointerConstant(Context, 6135 Expr::NPC_ValueDependentIsNotNull); 6136 } 6137 6138 if (NullKind == Expr::NPCK_NotNull) 6139 return false; 6140 6141 if (NullKind == Expr::NPCK_ZeroExpression) 6142 return false; 6143 6144 if (NullKind == Expr::NPCK_ZeroLiteral) { 6145 // In this case, check to make sure that we got here from a "NULL" 6146 // string in the source code. 6147 NullExpr = NullExpr->IgnoreParenImpCasts(); 6148 SourceLocation loc = NullExpr->getExprLoc(); 6149 if (!findMacroSpelling(loc, "NULL")) 6150 return false; 6151 } 6152 6153 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6154 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6155 << NonPointerExpr->getType() << DiagType 6156 << NonPointerExpr->getSourceRange(); 6157 return true; 6158 } 6159 6160 /// \brief Return false if the condition expression is valid, true otherwise. 6161 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6162 QualType CondTy = Cond->getType(); 6163 6164 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6165 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6166 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6167 << CondTy << Cond->getSourceRange(); 6168 return true; 6169 } 6170 6171 // C99 6.5.15p2 6172 if (CondTy->isScalarType()) return false; 6173 6174 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6175 << CondTy << Cond->getSourceRange(); 6176 return true; 6177 } 6178 6179 /// \brief Handle when one or both operands are void type. 6180 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6181 ExprResult &RHS) { 6182 Expr *LHSExpr = LHS.get(); 6183 Expr *RHSExpr = RHS.get(); 6184 6185 if (!LHSExpr->getType()->isVoidType()) 6186 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6187 << RHSExpr->getSourceRange(); 6188 if (!RHSExpr->getType()->isVoidType()) 6189 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6190 << LHSExpr->getSourceRange(); 6191 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6192 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6193 return S.Context.VoidTy; 6194 } 6195 6196 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6197 /// true otherwise. 6198 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6199 QualType PointerTy) { 6200 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6201 !NullExpr.get()->isNullPointerConstant(S.Context, 6202 Expr::NPC_ValueDependentIsNull)) 6203 return true; 6204 6205 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6206 return false; 6207 } 6208 6209 /// \brief Checks compatibility between two pointers and return the resulting 6210 /// type. 6211 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6212 ExprResult &RHS, 6213 SourceLocation Loc) { 6214 QualType LHSTy = LHS.get()->getType(); 6215 QualType RHSTy = RHS.get()->getType(); 6216 6217 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6218 // Two identical pointers types are always compatible. 6219 return LHSTy; 6220 } 6221 6222 QualType lhptee, rhptee; 6223 6224 // Get the pointee types. 6225 bool IsBlockPointer = false; 6226 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6227 lhptee = LHSBTy->getPointeeType(); 6228 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6229 IsBlockPointer = true; 6230 } else { 6231 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6232 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6233 } 6234 6235 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6236 // differently qualified versions of compatible types, the result type is 6237 // a pointer to an appropriately qualified version of the composite 6238 // type. 6239 6240 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6241 // clause doesn't make sense for our extensions. E.g. address space 2 should 6242 // be incompatible with address space 3: they may live on different devices or 6243 // anything. 6244 Qualifiers lhQual = lhptee.getQualifiers(); 6245 Qualifiers rhQual = rhptee.getQualifiers(); 6246 6247 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6248 lhQual.removeCVRQualifiers(); 6249 rhQual.removeCVRQualifiers(); 6250 6251 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6252 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6253 6254 // For OpenCL: 6255 // 1. If LHS and RHS types match exactly and: 6256 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6257 // (b) AS overlap => generate addrspacecast 6258 // (c) AS don't overlap => give an error 6259 // 2. if LHS and RHS types don't match: 6260 // (a) AS match => use standard C rules, generate bitcast 6261 // (b) AS overlap => generate addrspacecast instead of bitcast 6262 // (c) AS don't overlap => give an error 6263 6264 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6265 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6266 6267 // OpenCL cases 1c, 2a, 2b, and 2c. 6268 if (CompositeTy.isNull()) { 6269 // In this situation, we assume void* type. No especially good 6270 // reason, but this is what gcc does, and we do have to pick 6271 // to get a consistent AST. 6272 QualType incompatTy; 6273 if (S.getLangOpts().OpenCL) { 6274 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6275 // spaces is disallowed. 6276 unsigned ResultAddrSpace; 6277 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6278 // Cases 2a and 2b. 6279 ResultAddrSpace = lhQual.getAddressSpace(); 6280 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6281 // Cases 2a and 2b. 6282 ResultAddrSpace = rhQual.getAddressSpace(); 6283 } else { 6284 // Cases 1c and 2c. 6285 S.Diag(Loc, 6286 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6287 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6288 << RHS.get()->getSourceRange(); 6289 return QualType(); 6290 } 6291 6292 // Continue handling cases 2a and 2b. 6293 incompatTy = S.Context.getPointerType( 6294 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6295 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6296 (lhQual.getAddressSpace() != ResultAddrSpace) 6297 ? CK_AddressSpaceConversion /* 2b */ 6298 : CK_BitCast /* 2a */); 6299 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6300 (rhQual.getAddressSpace() != ResultAddrSpace) 6301 ? CK_AddressSpaceConversion /* 2b */ 6302 : CK_BitCast /* 2a */); 6303 } else { 6304 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6305 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6306 << RHS.get()->getSourceRange(); 6307 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6308 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6309 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6310 } 6311 return incompatTy; 6312 } 6313 6314 // The pointer types are compatible. 6315 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6316 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6317 if (IsBlockPointer) 6318 ResultTy = S.Context.getBlockPointerType(ResultTy); 6319 else { 6320 // Cases 1a and 1b for OpenCL. 6321 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6322 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6323 ? CK_BitCast /* 1a */ 6324 : CK_AddressSpaceConversion /* 1b */; 6325 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6326 ? CK_BitCast /* 1a */ 6327 : CK_AddressSpaceConversion /* 1b */; 6328 ResultTy = S.Context.getPointerType(ResultTy); 6329 } 6330 6331 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6332 // if the target type does not change. 6333 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6334 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6335 return ResultTy; 6336 } 6337 6338 /// \brief Return the resulting type when the operands are both block pointers. 6339 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6340 ExprResult &LHS, 6341 ExprResult &RHS, 6342 SourceLocation Loc) { 6343 QualType LHSTy = LHS.get()->getType(); 6344 QualType RHSTy = RHS.get()->getType(); 6345 6346 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6347 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6348 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6349 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6350 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6351 return destType; 6352 } 6353 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6354 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6355 << RHS.get()->getSourceRange(); 6356 return QualType(); 6357 } 6358 6359 // We have 2 block pointer types. 6360 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6361 } 6362 6363 /// \brief Return the resulting type when the operands are both pointers. 6364 static QualType 6365 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6366 ExprResult &RHS, 6367 SourceLocation Loc) { 6368 // get the pointer types 6369 QualType LHSTy = LHS.get()->getType(); 6370 QualType RHSTy = RHS.get()->getType(); 6371 6372 // get the "pointed to" types 6373 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6374 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6375 6376 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6377 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6378 // Figure out necessary qualifiers (C99 6.5.15p6) 6379 QualType destPointee 6380 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6381 QualType destType = S.Context.getPointerType(destPointee); 6382 // Add qualifiers if necessary. 6383 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6384 // Promote to void*. 6385 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6386 return destType; 6387 } 6388 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6389 QualType destPointee 6390 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6391 QualType destType = S.Context.getPointerType(destPointee); 6392 // Add qualifiers if necessary. 6393 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6394 // Promote to void*. 6395 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6396 return destType; 6397 } 6398 6399 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6400 } 6401 6402 /// \brief Return false if the first expression is not an integer and the second 6403 /// expression is not a pointer, true otherwise. 6404 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6405 Expr* PointerExpr, SourceLocation Loc, 6406 bool IsIntFirstExpr) { 6407 if (!PointerExpr->getType()->isPointerType() || 6408 !Int.get()->getType()->isIntegerType()) 6409 return false; 6410 6411 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6412 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6413 6414 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6415 << Expr1->getType() << Expr2->getType() 6416 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6417 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6418 CK_IntegralToPointer); 6419 return true; 6420 } 6421 6422 /// \brief Simple conversion between integer and floating point types. 6423 /// 6424 /// Used when handling the OpenCL conditional operator where the 6425 /// condition is a vector while the other operands are scalar. 6426 /// 6427 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6428 /// types are either integer or floating type. Between the two 6429 /// operands, the type with the higher rank is defined as the "result 6430 /// type". The other operand needs to be promoted to the same type. No 6431 /// other type promotion is allowed. We cannot use 6432 /// UsualArithmeticConversions() for this purpose, since it always 6433 /// promotes promotable types. 6434 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6435 ExprResult &RHS, 6436 SourceLocation QuestionLoc) { 6437 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6438 if (LHS.isInvalid()) 6439 return QualType(); 6440 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6441 if (RHS.isInvalid()) 6442 return QualType(); 6443 6444 // For conversion purposes, we ignore any qualifiers. 6445 // For example, "const float" and "float" are equivalent. 6446 QualType LHSType = 6447 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6448 QualType RHSType = 6449 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6450 6451 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6452 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6453 << LHSType << LHS.get()->getSourceRange(); 6454 return QualType(); 6455 } 6456 6457 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6458 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6459 << RHSType << RHS.get()->getSourceRange(); 6460 return QualType(); 6461 } 6462 6463 // If both types are identical, no conversion is needed. 6464 if (LHSType == RHSType) 6465 return LHSType; 6466 6467 // Now handle "real" floating types (i.e. float, double, long double). 6468 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6469 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6470 /*IsCompAssign = */ false); 6471 6472 // Finally, we have two differing integer types. 6473 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6474 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6475 } 6476 6477 /// \brief Convert scalar operands to a vector that matches the 6478 /// condition in length. 6479 /// 6480 /// Used when handling the OpenCL conditional operator where the 6481 /// condition is a vector while the other operands are scalar. 6482 /// 6483 /// We first compute the "result type" for the scalar operands 6484 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6485 /// into a vector of that type where the length matches the condition 6486 /// vector type. s6.11.6 requires that the element types of the result 6487 /// and the condition must have the same number of bits. 6488 static QualType 6489 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6490 QualType CondTy, SourceLocation QuestionLoc) { 6491 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6492 if (ResTy.isNull()) return QualType(); 6493 6494 const VectorType *CV = CondTy->getAs<VectorType>(); 6495 assert(CV); 6496 6497 // Determine the vector result type 6498 unsigned NumElements = CV->getNumElements(); 6499 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6500 6501 // Ensure that all types have the same number of bits 6502 if (S.Context.getTypeSize(CV->getElementType()) 6503 != S.Context.getTypeSize(ResTy)) { 6504 // Since VectorTy is created internally, it does not pretty print 6505 // with an OpenCL name. Instead, we just print a description. 6506 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6507 SmallString<64> Str; 6508 llvm::raw_svector_ostream OS(Str); 6509 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6510 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6511 << CondTy << OS.str(); 6512 return QualType(); 6513 } 6514 6515 // Convert operands to the vector result type 6516 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6517 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6518 6519 return VectorTy; 6520 } 6521 6522 /// \brief Return false if this is a valid OpenCL condition vector 6523 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6524 SourceLocation QuestionLoc) { 6525 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6526 // integral type. 6527 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6528 assert(CondTy); 6529 QualType EleTy = CondTy->getElementType(); 6530 if (EleTy->isIntegerType()) return false; 6531 6532 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6533 << Cond->getType() << Cond->getSourceRange(); 6534 return true; 6535 } 6536 6537 /// \brief Return false if the vector condition type and the vector 6538 /// result type are compatible. 6539 /// 6540 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6541 /// number of elements, and their element types have the same number 6542 /// of bits. 6543 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6544 SourceLocation QuestionLoc) { 6545 const VectorType *CV = CondTy->getAs<VectorType>(); 6546 const VectorType *RV = VecResTy->getAs<VectorType>(); 6547 assert(CV && RV); 6548 6549 if (CV->getNumElements() != RV->getNumElements()) { 6550 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6551 << CondTy << VecResTy; 6552 return true; 6553 } 6554 6555 QualType CVE = CV->getElementType(); 6556 QualType RVE = RV->getElementType(); 6557 6558 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6559 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6560 << CondTy << VecResTy; 6561 return true; 6562 } 6563 6564 return false; 6565 } 6566 6567 /// \brief Return the resulting type for the conditional operator in 6568 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6569 /// s6.3.i) when the condition is a vector type. 6570 static QualType 6571 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6572 ExprResult &LHS, ExprResult &RHS, 6573 SourceLocation QuestionLoc) { 6574 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6575 if (Cond.isInvalid()) 6576 return QualType(); 6577 QualType CondTy = Cond.get()->getType(); 6578 6579 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6580 return QualType(); 6581 6582 // If either operand is a vector then find the vector type of the 6583 // result as specified in OpenCL v1.1 s6.3.i. 6584 if (LHS.get()->getType()->isVectorType() || 6585 RHS.get()->getType()->isVectorType()) { 6586 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6587 /*isCompAssign*/false, 6588 /*AllowBothBool*/true, 6589 /*AllowBoolConversions*/false); 6590 if (VecResTy.isNull()) return QualType(); 6591 // The result type must match the condition type as specified in 6592 // OpenCL v1.1 s6.11.6. 6593 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6594 return QualType(); 6595 return VecResTy; 6596 } 6597 6598 // Both operands are scalar. 6599 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6600 } 6601 6602 /// \brief Return true if the Expr is block type 6603 static bool checkBlockType(Sema &S, const Expr *E) { 6604 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6605 QualType Ty = CE->getCallee()->getType(); 6606 if (Ty->isBlockPointerType()) { 6607 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6608 return true; 6609 } 6610 } 6611 return false; 6612 } 6613 6614 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6615 /// In that case, LHS = cond. 6616 /// C99 6.5.15 6617 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6618 ExprResult &RHS, ExprValueKind &VK, 6619 ExprObjectKind &OK, 6620 SourceLocation QuestionLoc) { 6621 6622 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6623 if (!LHSResult.isUsable()) return QualType(); 6624 LHS = LHSResult; 6625 6626 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6627 if (!RHSResult.isUsable()) return QualType(); 6628 RHS = RHSResult; 6629 6630 // C++ is sufficiently different to merit its own checker. 6631 if (getLangOpts().CPlusPlus) 6632 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6633 6634 VK = VK_RValue; 6635 OK = OK_Ordinary; 6636 6637 // The OpenCL operator with a vector condition is sufficiently 6638 // different to merit its own checker. 6639 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6640 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6641 6642 // First, check the condition. 6643 Cond = UsualUnaryConversions(Cond.get()); 6644 if (Cond.isInvalid()) 6645 return QualType(); 6646 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6647 return QualType(); 6648 6649 // Now check the two expressions. 6650 if (LHS.get()->getType()->isVectorType() || 6651 RHS.get()->getType()->isVectorType()) 6652 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6653 /*AllowBothBool*/true, 6654 /*AllowBoolConversions*/false); 6655 6656 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6657 if (LHS.isInvalid() || RHS.isInvalid()) 6658 return QualType(); 6659 6660 QualType LHSTy = LHS.get()->getType(); 6661 QualType RHSTy = RHS.get()->getType(); 6662 6663 // Diagnose attempts to convert between __float128 and long double where 6664 // such conversions currently can't be handled. 6665 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6666 Diag(QuestionLoc, 6667 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6668 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6669 return QualType(); 6670 } 6671 6672 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6673 // selection operator (?:). 6674 if (getLangOpts().OpenCL && 6675 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6676 return QualType(); 6677 } 6678 6679 // If both operands have arithmetic type, do the usual arithmetic conversions 6680 // to find a common type: C99 6.5.15p3,5. 6681 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6682 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6683 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6684 6685 return ResTy; 6686 } 6687 6688 // If both operands are the same structure or union type, the result is that 6689 // type. 6690 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6691 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6692 if (LHSRT->getDecl() == RHSRT->getDecl()) 6693 // "If both the operands have structure or union type, the result has 6694 // that type." This implies that CV qualifiers are dropped. 6695 return LHSTy.getUnqualifiedType(); 6696 // FIXME: Type of conditional expression must be complete in C mode. 6697 } 6698 6699 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6700 // The following || allows only one side to be void (a GCC-ism). 6701 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6702 return checkConditionalVoidType(*this, LHS, RHS); 6703 } 6704 6705 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6706 // the type of the other operand." 6707 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6708 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6709 6710 // All objective-c pointer type analysis is done here. 6711 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6712 QuestionLoc); 6713 if (LHS.isInvalid() || RHS.isInvalid()) 6714 return QualType(); 6715 if (!compositeType.isNull()) 6716 return compositeType; 6717 6718 6719 // Handle block pointer types. 6720 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6721 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6722 QuestionLoc); 6723 6724 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6725 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6726 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6727 QuestionLoc); 6728 6729 // GCC compatibility: soften pointer/integer mismatch. Note that 6730 // null pointers have been filtered out by this point. 6731 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6732 /*isIntFirstExpr=*/true)) 6733 return RHSTy; 6734 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6735 /*isIntFirstExpr=*/false)) 6736 return LHSTy; 6737 6738 // Emit a better diagnostic if one of the expressions is a null pointer 6739 // constant and the other is not a pointer type. In this case, the user most 6740 // likely forgot to take the address of the other expression. 6741 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6742 return QualType(); 6743 6744 // Otherwise, the operands are not compatible. 6745 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6746 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6747 << RHS.get()->getSourceRange(); 6748 return QualType(); 6749 } 6750 6751 /// FindCompositeObjCPointerType - Helper method to find composite type of 6752 /// two objective-c pointer types of the two input expressions. 6753 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6754 SourceLocation QuestionLoc) { 6755 QualType LHSTy = LHS.get()->getType(); 6756 QualType RHSTy = RHS.get()->getType(); 6757 6758 // Handle things like Class and struct objc_class*. Here we case the result 6759 // to the pseudo-builtin, because that will be implicitly cast back to the 6760 // redefinition type if an attempt is made to access its fields. 6761 if (LHSTy->isObjCClassType() && 6762 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6763 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6764 return LHSTy; 6765 } 6766 if (RHSTy->isObjCClassType() && 6767 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6768 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6769 return RHSTy; 6770 } 6771 // And the same for struct objc_object* / id 6772 if (LHSTy->isObjCIdType() && 6773 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6774 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6775 return LHSTy; 6776 } 6777 if (RHSTy->isObjCIdType() && 6778 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6779 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6780 return RHSTy; 6781 } 6782 // And the same for struct objc_selector* / SEL 6783 if (Context.isObjCSelType(LHSTy) && 6784 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6785 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6786 return LHSTy; 6787 } 6788 if (Context.isObjCSelType(RHSTy) && 6789 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6790 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6791 return RHSTy; 6792 } 6793 // Check constraints for Objective-C object pointers types. 6794 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6795 6796 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6797 // Two identical object pointer types are always compatible. 6798 return LHSTy; 6799 } 6800 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6801 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6802 QualType compositeType = LHSTy; 6803 6804 // If both operands are interfaces and either operand can be 6805 // assigned to the other, use that type as the composite 6806 // type. This allows 6807 // xxx ? (A*) a : (B*) b 6808 // where B is a subclass of A. 6809 // 6810 // Additionally, as for assignment, if either type is 'id' 6811 // allow silent coercion. Finally, if the types are 6812 // incompatible then make sure to use 'id' as the composite 6813 // type so the result is acceptable for sending messages to. 6814 6815 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6816 // It could return the composite type. 6817 if (!(compositeType = 6818 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6819 // Nothing more to do. 6820 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6821 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6822 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6823 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6824 } else if ((LHSTy->isObjCQualifiedIdType() || 6825 RHSTy->isObjCQualifiedIdType()) && 6826 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6827 // Need to handle "id<xx>" explicitly. 6828 // GCC allows qualified id and any Objective-C type to devolve to 6829 // id. Currently localizing to here until clear this should be 6830 // part of ObjCQualifiedIdTypesAreCompatible. 6831 compositeType = Context.getObjCIdType(); 6832 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6833 compositeType = Context.getObjCIdType(); 6834 } else { 6835 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6836 << LHSTy << RHSTy 6837 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6838 QualType incompatTy = Context.getObjCIdType(); 6839 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6840 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6841 return incompatTy; 6842 } 6843 // The object pointer types are compatible. 6844 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6845 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6846 return compositeType; 6847 } 6848 // Check Objective-C object pointer types and 'void *' 6849 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6850 if (getLangOpts().ObjCAutoRefCount) { 6851 // ARC forbids the implicit conversion of object pointers to 'void *', 6852 // so these types are not compatible. 6853 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6855 LHS = RHS = true; 6856 return QualType(); 6857 } 6858 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6859 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6860 QualType destPointee 6861 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6862 QualType destType = Context.getPointerType(destPointee); 6863 // Add qualifiers if necessary. 6864 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6865 // Promote to void*. 6866 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6867 return destType; 6868 } 6869 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6870 if (getLangOpts().ObjCAutoRefCount) { 6871 // ARC forbids the implicit conversion of object pointers to 'void *', 6872 // so these types are not compatible. 6873 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6874 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6875 LHS = RHS = true; 6876 return QualType(); 6877 } 6878 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6879 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6880 QualType destPointee 6881 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6882 QualType destType = Context.getPointerType(destPointee); 6883 // Add qualifiers if necessary. 6884 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6885 // Promote to void*. 6886 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6887 return destType; 6888 } 6889 return QualType(); 6890 } 6891 6892 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6893 /// ParenRange in parentheses. 6894 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6895 const PartialDiagnostic &Note, 6896 SourceRange ParenRange) { 6897 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6898 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6899 EndLoc.isValid()) { 6900 Self.Diag(Loc, Note) 6901 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6902 << FixItHint::CreateInsertion(EndLoc, ")"); 6903 } else { 6904 // We can't display the parentheses, so just show the bare note. 6905 Self.Diag(Loc, Note) << ParenRange; 6906 } 6907 } 6908 6909 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6910 return BinaryOperator::isAdditiveOp(Opc) || 6911 BinaryOperator::isMultiplicativeOp(Opc) || 6912 BinaryOperator::isShiftOp(Opc); 6913 } 6914 6915 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6916 /// expression, either using a built-in or overloaded operator, 6917 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6918 /// expression. 6919 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6920 Expr **RHSExprs) { 6921 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6922 E = E->IgnoreImpCasts(); 6923 E = E->IgnoreConversionOperator(); 6924 E = E->IgnoreImpCasts(); 6925 6926 // Built-in binary operator. 6927 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6928 if (IsArithmeticOp(OP->getOpcode())) { 6929 *Opcode = OP->getOpcode(); 6930 *RHSExprs = OP->getRHS(); 6931 return true; 6932 } 6933 } 6934 6935 // Overloaded operator. 6936 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6937 if (Call->getNumArgs() != 2) 6938 return false; 6939 6940 // Make sure this is really a binary operator that is safe to pass into 6941 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6942 OverloadedOperatorKind OO = Call->getOperator(); 6943 if (OO < OO_Plus || OO > OO_Arrow || 6944 OO == OO_PlusPlus || OO == OO_MinusMinus) 6945 return false; 6946 6947 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6948 if (IsArithmeticOp(OpKind)) { 6949 *Opcode = OpKind; 6950 *RHSExprs = Call->getArg(1); 6951 return true; 6952 } 6953 } 6954 6955 return false; 6956 } 6957 6958 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6959 /// or is a logical expression such as (x==y) which has int type, but is 6960 /// commonly interpreted as boolean. 6961 static bool ExprLooksBoolean(Expr *E) { 6962 E = E->IgnoreParenImpCasts(); 6963 6964 if (E->getType()->isBooleanType()) 6965 return true; 6966 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6967 return OP->isComparisonOp() || OP->isLogicalOp(); 6968 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6969 return OP->getOpcode() == UO_LNot; 6970 if (E->getType()->isPointerType()) 6971 return true; 6972 6973 return false; 6974 } 6975 6976 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6977 /// and binary operator are mixed in a way that suggests the programmer assumed 6978 /// the conditional operator has higher precedence, for example: 6979 /// "int x = a + someBinaryCondition ? 1 : 2". 6980 static void DiagnoseConditionalPrecedence(Sema &Self, 6981 SourceLocation OpLoc, 6982 Expr *Condition, 6983 Expr *LHSExpr, 6984 Expr *RHSExpr) { 6985 BinaryOperatorKind CondOpcode; 6986 Expr *CondRHS; 6987 6988 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6989 return; 6990 if (!ExprLooksBoolean(CondRHS)) 6991 return; 6992 6993 // The condition is an arithmetic binary expression, with a right- 6994 // hand side that looks boolean, so warn. 6995 6996 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6997 << Condition->getSourceRange() 6998 << BinaryOperator::getOpcodeStr(CondOpcode); 6999 7000 SuggestParentheses(Self, OpLoc, 7001 Self.PDiag(diag::note_precedence_silence) 7002 << BinaryOperator::getOpcodeStr(CondOpcode), 7003 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7004 7005 SuggestParentheses(Self, OpLoc, 7006 Self.PDiag(diag::note_precedence_conditional_first), 7007 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7008 } 7009 7010 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7011 /// in the case of a the GNU conditional expr extension. 7012 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7013 SourceLocation ColonLoc, 7014 Expr *CondExpr, Expr *LHSExpr, 7015 Expr *RHSExpr) { 7016 if (!getLangOpts().CPlusPlus) { 7017 // C cannot handle TypoExpr nodes in the condition because it 7018 // doesn't handle dependent types properly, so make sure any TypoExprs have 7019 // been dealt with before checking the operands. 7020 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7021 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7022 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7023 7024 if (!CondResult.isUsable()) 7025 return ExprError(); 7026 7027 if (LHSExpr) { 7028 if (!LHSResult.isUsable()) 7029 return ExprError(); 7030 } 7031 7032 if (!RHSResult.isUsable()) 7033 return ExprError(); 7034 7035 CondExpr = CondResult.get(); 7036 LHSExpr = LHSResult.get(); 7037 RHSExpr = RHSResult.get(); 7038 } 7039 7040 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7041 // was the condition. 7042 OpaqueValueExpr *opaqueValue = nullptr; 7043 Expr *commonExpr = nullptr; 7044 if (!LHSExpr) { 7045 commonExpr = CondExpr; 7046 // Lower out placeholder types first. This is important so that we don't 7047 // try to capture a placeholder. This happens in few cases in C++; such 7048 // as Objective-C++'s dictionary subscripting syntax. 7049 if (commonExpr->hasPlaceholderType()) { 7050 ExprResult result = CheckPlaceholderExpr(commonExpr); 7051 if (!result.isUsable()) return ExprError(); 7052 commonExpr = result.get(); 7053 } 7054 // We usually want to apply unary conversions *before* saving, except 7055 // in the special case of a C++ l-value conditional. 7056 if (!(getLangOpts().CPlusPlus 7057 && !commonExpr->isTypeDependent() 7058 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7059 && commonExpr->isGLValue() 7060 && commonExpr->isOrdinaryOrBitFieldObject() 7061 && RHSExpr->isOrdinaryOrBitFieldObject() 7062 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7063 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7064 if (commonRes.isInvalid()) 7065 return ExprError(); 7066 commonExpr = commonRes.get(); 7067 } 7068 7069 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7070 commonExpr->getType(), 7071 commonExpr->getValueKind(), 7072 commonExpr->getObjectKind(), 7073 commonExpr); 7074 LHSExpr = CondExpr = opaqueValue; 7075 } 7076 7077 ExprValueKind VK = VK_RValue; 7078 ExprObjectKind OK = OK_Ordinary; 7079 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7080 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7081 VK, OK, QuestionLoc); 7082 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7083 RHS.isInvalid()) 7084 return ExprError(); 7085 7086 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7087 RHS.get()); 7088 7089 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7090 7091 if (!commonExpr) 7092 return new (Context) 7093 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7094 RHS.get(), result, VK, OK); 7095 7096 return new (Context) BinaryConditionalOperator( 7097 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7098 ColonLoc, result, VK, OK); 7099 } 7100 7101 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7102 // being closely modeled after the C99 spec:-). The odd characteristic of this 7103 // routine is it effectively iqnores the qualifiers on the top level pointee. 7104 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7105 // FIXME: add a couple examples in this comment. 7106 static Sema::AssignConvertType 7107 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7108 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7109 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7110 7111 // get the "pointed to" type (ignoring qualifiers at the top level) 7112 const Type *lhptee, *rhptee; 7113 Qualifiers lhq, rhq; 7114 std::tie(lhptee, lhq) = 7115 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7116 std::tie(rhptee, rhq) = 7117 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7118 7119 Sema::AssignConvertType ConvTy = Sema::Compatible; 7120 7121 // C99 6.5.16.1p1: This following citation is common to constraints 7122 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7123 // qualifiers of the type *pointed to* by the right; 7124 7125 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7126 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7127 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7128 // Ignore lifetime for further calculation. 7129 lhq.removeObjCLifetime(); 7130 rhq.removeObjCLifetime(); 7131 } 7132 7133 if (!lhq.compatiblyIncludes(rhq)) { 7134 // Treat address-space mismatches as fatal. TODO: address subspaces 7135 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7136 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7137 7138 // It's okay to add or remove GC or lifetime qualifiers when converting to 7139 // and from void*. 7140 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7141 .compatiblyIncludes( 7142 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7143 && (lhptee->isVoidType() || rhptee->isVoidType())) 7144 ; // keep old 7145 7146 // Treat lifetime mismatches as fatal. 7147 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7148 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7149 7150 // For GCC/MS compatibility, other qualifier mismatches are treated 7151 // as still compatible in C. 7152 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7153 } 7154 7155 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7156 // incomplete type and the other is a pointer to a qualified or unqualified 7157 // version of void... 7158 if (lhptee->isVoidType()) { 7159 if (rhptee->isIncompleteOrObjectType()) 7160 return ConvTy; 7161 7162 // As an extension, we allow cast to/from void* to function pointer. 7163 assert(rhptee->isFunctionType()); 7164 return Sema::FunctionVoidPointer; 7165 } 7166 7167 if (rhptee->isVoidType()) { 7168 if (lhptee->isIncompleteOrObjectType()) 7169 return ConvTy; 7170 7171 // As an extension, we allow cast to/from void* to function pointer. 7172 assert(lhptee->isFunctionType()); 7173 return Sema::FunctionVoidPointer; 7174 } 7175 7176 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7177 // unqualified versions of compatible types, ... 7178 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7179 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7180 // Check if the pointee types are compatible ignoring the sign. 7181 // We explicitly check for char so that we catch "char" vs 7182 // "unsigned char" on systems where "char" is unsigned. 7183 if (lhptee->isCharType()) 7184 ltrans = S.Context.UnsignedCharTy; 7185 else if (lhptee->hasSignedIntegerRepresentation()) 7186 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7187 7188 if (rhptee->isCharType()) 7189 rtrans = S.Context.UnsignedCharTy; 7190 else if (rhptee->hasSignedIntegerRepresentation()) 7191 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7192 7193 if (ltrans == rtrans) { 7194 // Types are compatible ignoring the sign. Qualifier incompatibility 7195 // takes priority over sign incompatibility because the sign 7196 // warning can be disabled. 7197 if (ConvTy != Sema::Compatible) 7198 return ConvTy; 7199 7200 return Sema::IncompatiblePointerSign; 7201 } 7202 7203 // If we are a multi-level pointer, it's possible that our issue is simply 7204 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7205 // the eventual target type is the same and the pointers have the same 7206 // level of indirection, this must be the issue. 7207 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7208 do { 7209 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7210 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7211 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7212 7213 if (lhptee == rhptee) 7214 return Sema::IncompatibleNestedPointerQualifiers; 7215 } 7216 7217 // General pointer incompatibility takes priority over qualifiers. 7218 return Sema::IncompatiblePointer; 7219 } 7220 if (!S.getLangOpts().CPlusPlus && 7221 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7222 return Sema::IncompatiblePointer; 7223 return ConvTy; 7224 } 7225 7226 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7227 /// block pointer types are compatible or whether a block and normal pointer 7228 /// are compatible. It is more restrict than comparing two function pointer 7229 // types. 7230 static Sema::AssignConvertType 7231 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7232 QualType RHSType) { 7233 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7234 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7235 7236 QualType lhptee, rhptee; 7237 7238 // get the "pointed to" type (ignoring qualifiers at the top level) 7239 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7240 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7241 7242 // In C++, the types have to match exactly. 7243 if (S.getLangOpts().CPlusPlus) 7244 return Sema::IncompatibleBlockPointer; 7245 7246 Sema::AssignConvertType ConvTy = Sema::Compatible; 7247 7248 // For blocks we enforce that qualifiers are identical. 7249 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7250 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7251 7252 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7253 return Sema::IncompatibleBlockPointer; 7254 7255 return ConvTy; 7256 } 7257 7258 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7259 /// for assignment compatibility. 7260 static Sema::AssignConvertType 7261 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7262 QualType RHSType) { 7263 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7264 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7265 7266 if (LHSType->isObjCBuiltinType()) { 7267 // Class is not compatible with ObjC object pointers. 7268 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7269 !RHSType->isObjCQualifiedClassType()) 7270 return Sema::IncompatiblePointer; 7271 return Sema::Compatible; 7272 } 7273 if (RHSType->isObjCBuiltinType()) { 7274 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7275 !LHSType->isObjCQualifiedClassType()) 7276 return Sema::IncompatiblePointer; 7277 return Sema::Compatible; 7278 } 7279 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7280 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7281 7282 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7283 // make an exception for id<P> 7284 !LHSType->isObjCQualifiedIdType()) 7285 return Sema::CompatiblePointerDiscardsQualifiers; 7286 7287 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7288 return Sema::Compatible; 7289 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7290 return Sema::IncompatibleObjCQualifiedId; 7291 return Sema::IncompatiblePointer; 7292 } 7293 7294 Sema::AssignConvertType 7295 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7296 QualType LHSType, QualType RHSType) { 7297 // Fake up an opaque expression. We don't actually care about what 7298 // cast operations are required, so if CheckAssignmentConstraints 7299 // adds casts to this they'll be wasted, but fortunately that doesn't 7300 // usually happen on valid code. 7301 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7302 ExprResult RHSPtr = &RHSExpr; 7303 CastKind K = CK_Invalid; 7304 7305 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7306 } 7307 7308 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7309 /// has code to accommodate several GCC extensions when type checking 7310 /// pointers. Here are some objectionable examples that GCC considers warnings: 7311 /// 7312 /// int a, *pint; 7313 /// short *pshort; 7314 /// struct foo *pfoo; 7315 /// 7316 /// pint = pshort; // warning: assignment from incompatible pointer type 7317 /// a = pint; // warning: assignment makes integer from pointer without a cast 7318 /// pint = a; // warning: assignment makes pointer from integer without a cast 7319 /// pint = pfoo; // warning: assignment from incompatible pointer type 7320 /// 7321 /// As a result, the code for dealing with pointers is more complex than the 7322 /// C99 spec dictates. 7323 /// 7324 /// Sets 'Kind' for any result kind except Incompatible. 7325 Sema::AssignConvertType 7326 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7327 CastKind &Kind, bool ConvertRHS) { 7328 QualType RHSType = RHS.get()->getType(); 7329 QualType OrigLHSType = LHSType; 7330 7331 // Get canonical types. We're not formatting these types, just comparing 7332 // them. 7333 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7334 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7335 7336 // Common case: no conversion required. 7337 if (LHSType == RHSType) { 7338 Kind = CK_NoOp; 7339 return Compatible; 7340 } 7341 7342 // If we have an atomic type, try a non-atomic assignment, then just add an 7343 // atomic qualification step. 7344 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7345 Sema::AssignConvertType result = 7346 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7347 if (result != Compatible) 7348 return result; 7349 if (Kind != CK_NoOp && ConvertRHS) 7350 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7351 Kind = CK_NonAtomicToAtomic; 7352 return Compatible; 7353 } 7354 7355 // If the left-hand side is a reference type, then we are in a 7356 // (rare!) case where we've allowed the use of references in C, 7357 // e.g., as a parameter type in a built-in function. In this case, 7358 // just make sure that the type referenced is compatible with the 7359 // right-hand side type. The caller is responsible for adjusting 7360 // LHSType so that the resulting expression does not have reference 7361 // type. 7362 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7363 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7364 Kind = CK_LValueBitCast; 7365 return Compatible; 7366 } 7367 return Incompatible; 7368 } 7369 7370 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7371 // to the same ExtVector type. 7372 if (LHSType->isExtVectorType()) { 7373 if (RHSType->isExtVectorType()) 7374 return Incompatible; 7375 if (RHSType->isArithmeticType()) { 7376 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7377 if (ConvertRHS) 7378 RHS = prepareVectorSplat(LHSType, RHS.get()); 7379 Kind = CK_VectorSplat; 7380 return Compatible; 7381 } 7382 } 7383 7384 // Conversions to or from vector type. 7385 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7386 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7387 // Allow assignments of an AltiVec vector type to an equivalent GCC 7388 // vector type and vice versa 7389 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7390 Kind = CK_BitCast; 7391 return Compatible; 7392 } 7393 7394 // If we are allowing lax vector conversions, and LHS and RHS are both 7395 // vectors, the total size only needs to be the same. This is a bitcast; 7396 // no bits are changed but the result type is different. 7397 if (isLaxVectorConversion(RHSType, LHSType)) { 7398 Kind = CK_BitCast; 7399 return IncompatibleVectors; 7400 } 7401 } 7402 return Incompatible; 7403 } 7404 7405 // Diagnose attempts to convert between __float128 and long double where 7406 // such conversions currently can't be handled. 7407 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7408 return Incompatible; 7409 7410 // Arithmetic conversions. 7411 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7412 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7413 if (ConvertRHS) 7414 Kind = PrepareScalarCast(RHS, LHSType); 7415 return Compatible; 7416 } 7417 7418 // Conversions to normal pointers. 7419 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7420 // U* -> T* 7421 if (isa<PointerType>(RHSType)) { 7422 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7423 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7424 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7425 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7426 } 7427 7428 // int -> T* 7429 if (RHSType->isIntegerType()) { 7430 Kind = CK_IntegralToPointer; // FIXME: null? 7431 return IntToPointer; 7432 } 7433 7434 // C pointers are not compatible with ObjC object pointers, 7435 // with two exceptions: 7436 if (isa<ObjCObjectPointerType>(RHSType)) { 7437 // - conversions to void* 7438 if (LHSPointer->getPointeeType()->isVoidType()) { 7439 Kind = CK_BitCast; 7440 return Compatible; 7441 } 7442 7443 // - conversions from 'Class' to the redefinition type 7444 if (RHSType->isObjCClassType() && 7445 Context.hasSameType(LHSType, 7446 Context.getObjCClassRedefinitionType())) { 7447 Kind = CK_BitCast; 7448 return Compatible; 7449 } 7450 7451 Kind = CK_BitCast; 7452 return IncompatiblePointer; 7453 } 7454 7455 // U^ -> void* 7456 if (RHSType->getAs<BlockPointerType>()) { 7457 if (LHSPointer->getPointeeType()->isVoidType()) { 7458 Kind = CK_BitCast; 7459 return Compatible; 7460 } 7461 } 7462 7463 return Incompatible; 7464 } 7465 7466 // Conversions to block pointers. 7467 if (isa<BlockPointerType>(LHSType)) { 7468 // U^ -> T^ 7469 if (RHSType->isBlockPointerType()) { 7470 Kind = CK_BitCast; 7471 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7472 } 7473 7474 // int or null -> T^ 7475 if (RHSType->isIntegerType()) { 7476 Kind = CK_IntegralToPointer; // FIXME: null 7477 return IntToBlockPointer; 7478 } 7479 7480 // id -> T^ 7481 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7482 Kind = CK_AnyPointerToBlockPointerCast; 7483 return Compatible; 7484 } 7485 7486 // void* -> T^ 7487 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7488 if (RHSPT->getPointeeType()->isVoidType()) { 7489 Kind = CK_AnyPointerToBlockPointerCast; 7490 return Compatible; 7491 } 7492 7493 return Incompatible; 7494 } 7495 7496 // Conversions to Objective-C pointers. 7497 if (isa<ObjCObjectPointerType>(LHSType)) { 7498 // A* -> B* 7499 if (RHSType->isObjCObjectPointerType()) { 7500 Kind = CK_BitCast; 7501 Sema::AssignConvertType result = 7502 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7503 if (getLangOpts().ObjCAutoRefCount && 7504 result == Compatible && 7505 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7506 result = IncompatibleObjCWeakRef; 7507 return result; 7508 } 7509 7510 // int or null -> A* 7511 if (RHSType->isIntegerType()) { 7512 Kind = CK_IntegralToPointer; // FIXME: null 7513 return IntToPointer; 7514 } 7515 7516 // In general, C pointers are not compatible with ObjC object pointers, 7517 // with two exceptions: 7518 if (isa<PointerType>(RHSType)) { 7519 Kind = CK_CPointerToObjCPointerCast; 7520 7521 // - conversions from 'void*' 7522 if (RHSType->isVoidPointerType()) { 7523 return Compatible; 7524 } 7525 7526 // - conversions to 'Class' from its redefinition type 7527 if (LHSType->isObjCClassType() && 7528 Context.hasSameType(RHSType, 7529 Context.getObjCClassRedefinitionType())) { 7530 return Compatible; 7531 } 7532 7533 return IncompatiblePointer; 7534 } 7535 7536 // Only under strict condition T^ is compatible with an Objective-C pointer. 7537 if (RHSType->isBlockPointerType() && 7538 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7539 if (ConvertRHS) 7540 maybeExtendBlockObject(RHS); 7541 Kind = CK_BlockPointerToObjCPointerCast; 7542 return Compatible; 7543 } 7544 7545 return Incompatible; 7546 } 7547 7548 // Conversions from pointers that are not covered by the above. 7549 if (isa<PointerType>(RHSType)) { 7550 // T* -> _Bool 7551 if (LHSType == Context.BoolTy) { 7552 Kind = CK_PointerToBoolean; 7553 return Compatible; 7554 } 7555 7556 // T* -> int 7557 if (LHSType->isIntegerType()) { 7558 Kind = CK_PointerToIntegral; 7559 return PointerToInt; 7560 } 7561 7562 return Incompatible; 7563 } 7564 7565 // Conversions from Objective-C pointers that are not covered by the above. 7566 if (isa<ObjCObjectPointerType>(RHSType)) { 7567 // T* -> _Bool 7568 if (LHSType == Context.BoolTy) { 7569 Kind = CK_PointerToBoolean; 7570 return Compatible; 7571 } 7572 7573 // T* -> int 7574 if (LHSType->isIntegerType()) { 7575 Kind = CK_PointerToIntegral; 7576 return PointerToInt; 7577 } 7578 7579 return Incompatible; 7580 } 7581 7582 // struct A -> struct B 7583 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7584 if (Context.typesAreCompatible(LHSType, RHSType)) { 7585 Kind = CK_NoOp; 7586 return Compatible; 7587 } 7588 } 7589 7590 return Incompatible; 7591 } 7592 7593 /// \brief Constructs a transparent union from an expression that is 7594 /// used to initialize the transparent union. 7595 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7596 ExprResult &EResult, QualType UnionType, 7597 FieldDecl *Field) { 7598 // Build an initializer list that designates the appropriate member 7599 // of the transparent union. 7600 Expr *E = EResult.get(); 7601 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7602 E, SourceLocation()); 7603 Initializer->setType(UnionType); 7604 Initializer->setInitializedFieldInUnion(Field); 7605 7606 // Build a compound literal constructing a value of the transparent 7607 // union type from this initializer list. 7608 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7609 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7610 VK_RValue, Initializer, false); 7611 } 7612 7613 Sema::AssignConvertType 7614 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7615 ExprResult &RHS) { 7616 QualType RHSType = RHS.get()->getType(); 7617 7618 // If the ArgType is a Union type, we want to handle a potential 7619 // transparent_union GCC extension. 7620 const RecordType *UT = ArgType->getAsUnionType(); 7621 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7622 return Incompatible; 7623 7624 // The field to initialize within the transparent union. 7625 RecordDecl *UD = UT->getDecl(); 7626 FieldDecl *InitField = nullptr; 7627 // It's compatible if the expression matches any of the fields. 7628 for (auto *it : UD->fields()) { 7629 if (it->getType()->isPointerType()) { 7630 // If the transparent union contains a pointer type, we allow: 7631 // 1) void pointer 7632 // 2) null pointer constant 7633 if (RHSType->isPointerType()) 7634 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7635 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7636 InitField = it; 7637 break; 7638 } 7639 7640 if (RHS.get()->isNullPointerConstant(Context, 7641 Expr::NPC_ValueDependentIsNull)) { 7642 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7643 CK_NullToPointer); 7644 InitField = it; 7645 break; 7646 } 7647 } 7648 7649 CastKind Kind = CK_Invalid; 7650 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7651 == Compatible) { 7652 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7653 InitField = it; 7654 break; 7655 } 7656 } 7657 7658 if (!InitField) 7659 return Incompatible; 7660 7661 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7662 return Compatible; 7663 } 7664 7665 Sema::AssignConvertType 7666 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7667 bool Diagnose, 7668 bool DiagnoseCFAudited, 7669 bool ConvertRHS) { 7670 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7671 // we can't avoid *all* modifications at the moment, so we need some somewhere 7672 // to put the updated value. 7673 ExprResult LocalRHS = CallerRHS; 7674 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7675 7676 if (getLangOpts().CPlusPlus) { 7677 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7678 // C++ 5.17p3: If the left operand is not of class type, the 7679 // expression is implicitly converted (C++ 4) to the 7680 // cv-unqualified type of the left operand. 7681 ExprResult Res; 7682 if (Diagnose) { 7683 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7684 AA_Assigning); 7685 } else { 7686 ImplicitConversionSequence ICS = 7687 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7688 /*SuppressUserConversions=*/false, 7689 /*AllowExplicit=*/false, 7690 /*InOverloadResolution=*/false, 7691 /*CStyle=*/false, 7692 /*AllowObjCWritebackConversion=*/false); 7693 if (ICS.isFailure()) 7694 return Incompatible; 7695 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7696 ICS, AA_Assigning); 7697 } 7698 if (Res.isInvalid()) 7699 return Incompatible; 7700 Sema::AssignConvertType result = Compatible; 7701 if (getLangOpts().ObjCAutoRefCount && 7702 !CheckObjCARCUnavailableWeakConversion(LHSType, 7703 RHS.get()->getType())) 7704 result = IncompatibleObjCWeakRef; 7705 RHS = Res; 7706 return result; 7707 } 7708 7709 // FIXME: Currently, we fall through and treat C++ classes like C 7710 // structures. 7711 // FIXME: We also fall through for atomics; not sure what should 7712 // happen there, though. 7713 } else if (RHS.get()->getType() == Context.OverloadTy) { 7714 // As a set of extensions to C, we support overloading on functions. These 7715 // functions need to be resolved here. 7716 DeclAccessPair DAP; 7717 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7718 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7719 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7720 else 7721 return Incompatible; 7722 } 7723 7724 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7725 // a null pointer constant. 7726 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7727 LHSType->isBlockPointerType()) && 7728 RHS.get()->isNullPointerConstant(Context, 7729 Expr::NPC_ValueDependentIsNull)) { 7730 if (Diagnose || ConvertRHS) { 7731 CastKind Kind; 7732 CXXCastPath Path; 7733 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7734 /*IgnoreBaseAccess=*/false, Diagnose); 7735 if (ConvertRHS) 7736 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7737 } 7738 return Compatible; 7739 } 7740 7741 // This check seems unnatural, however it is necessary to ensure the proper 7742 // conversion of functions/arrays. If the conversion were done for all 7743 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7744 // expressions that suppress this implicit conversion (&, sizeof). 7745 // 7746 // Suppress this for references: C++ 8.5.3p5. 7747 if (!LHSType->isReferenceType()) { 7748 // FIXME: We potentially allocate here even if ConvertRHS is false. 7749 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7750 if (RHS.isInvalid()) 7751 return Incompatible; 7752 } 7753 7754 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7755 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7756 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7757 if (PDecl && !PDecl->hasDefinition()) { 7758 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7759 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7760 } 7761 } 7762 7763 CastKind Kind = CK_Invalid; 7764 Sema::AssignConvertType result = 7765 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7766 7767 // C99 6.5.16.1p2: The value of the right operand is converted to the 7768 // type of the assignment expression. 7769 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7770 // so that we can use references in built-in functions even in C. 7771 // The getNonReferenceType() call makes sure that the resulting expression 7772 // does not have reference type. 7773 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7774 QualType Ty = LHSType.getNonLValueExprType(Context); 7775 Expr *E = RHS.get(); 7776 7777 // Check for various Objective-C errors. If we are not reporting 7778 // diagnostics and just checking for errors, e.g., during overload 7779 // resolution, return Incompatible to indicate the failure. 7780 if (getLangOpts().ObjCAutoRefCount && 7781 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7782 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7783 if (!Diagnose) 7784 return Incompatible; 7785 } 7786 if (getLangOpts().ObjC1 && 7787 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7788 E->getType(), E, Diagnose) || 7789 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7790 if (!Diagnose) 7791 return Incompatible; 7792 // Replace the expression with a corrected version and continue so we 7793 // can find further errors. 7794 RHS = E; 7795 return Compatible; 7796 } 7797 7798 if (ConvertRHS) 7799 RHS = ImpCastExprToType(E, Ty, Kind); 7800 } 7801 return result; 7802 } 7803 7804 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7805 ExprResult &RHS) { 7806 Diag(Loc, diag::err_typecheck_invalid_operands) 7807 << LHS.get()->getType() << RHS.get()->getType() 7808 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7809 return QualType(); 7810 } 7811 7812 /// Try to convert a value of non-vector type to a vector type by converting 7813 /// the type to the element type of the vector and then performing a splat. 7814 /// If the language is OpenCL, we only use conversions that promote scalar 7815 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7816 /// for float->int. 7817 /// 7818 /// \param scalar - if non-null, actually perform the conversions 7819 /// \return true if the operation fails (but without diagnosing the failure) 7820 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7821 QualType scalarTy, 7822 QualType vectorEltTy, 7823 QualType vectorTy) { 7824 // The conversion to apply to the scalar before splatting it, 7825 // if necessary. 7826 CastKind scalarCast = CK_Invalid; 7827 7828 if (vectorEltTy->isIntegralType(S.Context)) { 7829 if (!scalarTy->isIntegralType(S.Context)) 7830 return true; 7831 if (S.getLangOpts().OpenCL && 7832 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7833 return true; 7834 scalarCast = CK_IntegralCast; 7835 } else if (vectorEltTy->isRealFloatingType()) { 7836 if (scalarTy->isRealFloatingType()) { 7837 if (S.getLangOpts().OpenCL && 7838 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7839 return true; 7840 scalarCast = CK_FloatingCast; 7841 } 7842 else if (scalarTy->isIntegralType(S.Context)) 7843 scalarCast = CK_IntegralToFloating; 7844 else 7845 return true; 7846 } else { 7847 return true; 7848 } 7849 7850 // Adjust scalar if desired. 7851 if (scalar) { 7852 if (scalarCast != CK_Invalid) 7853 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7854 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7855 } 7856 return false; 7857 } 7858 7859 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7860 SourceLocation Loc, bool IsCompAssign, 7861 bool AllowBothBool, 7862 bool AllowBoolConversions) { 7863 if (!IsCompAssign) { 7864 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7865 if (LHS.isInvalid()) 7866 return QualType(); 7867 } 7868 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7869 if (RHS.isInvalid()) 7870 return QualType(); 7871 7872 // For conversion purposes, we ignore any qualifiers. 7873 // For example, "const float" and "float" are equivalent. 7874 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7875 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7876 7877 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7878 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7879 assert(LHSVecType || RHSVecType); 7880 7881 // AltiVec-style "vector bool op vector bool" combinations are allowed 7882 // for some operators but not others. 7883 if (!AllowBothBool && 7884 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7885 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7886 return InvalidOperands(Loc, LHS, RHS); 7887 7888 // If the vector types are identical, return. 7889 if (Context.hasSameType(LHSType, RHSType)) 7890 return LHSType; 7891 7892 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7893 if (LHSVecType && RHSVecType && 7894 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7895 if (isa<ExtVectorType>(LHSVecType)) { 7896 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7897 return LHSType; 7898 } 7899 7900 if (!IsCompAssign) 7901 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7902 return RHSType; 7903 } 7904 7905 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7906 // can be mixed, with the result being the non-bool type. The non-bool 7907 // operand must have integer element type. 7908 if (AllowBoolConversions && LHSVecType && RHSVecType && 7909 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7910 (Context.getTypeSize(LHSVecType->getElementType()) == 7911 Context.getTypeSize(RHSVecType->getElementType()))) { 7912 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7913 LHSVecType->getElementType()->isIntegerType() && 7914 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7915 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7916 return LHSType; 7917 } 7918 if (!IsCompAssign && 7919 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7920 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7921 RHSVecType->getElementType()->isIntegerType()) { 7922 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7923 return RHSType; 7924 } 7925 } 7926 7927 // If there's an ext-vector type and a scalar, try to convert the scalar to 7928 // the vector element type and splat. 7929 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7930 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7931 LHSVecType->getElementType(), LHSType)) 7932 return LHSType; 7933 } 7934 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7935 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7936 LHSType, RHSVecType->getElementType(), 7937 RHSType)) 7938 return RHSType; 7939 } 7940 7941 // If we're allowing lax vector conversions, only the total (data) size needs 7942 // to be the same. If one of the types is scalar, the result is always the 7943 // vector type. Don't allow this if the scalar operand is an lvalue. 7944 QualType VecType = LHSVecType ? LHSType : RHSType; 7945 QualType ScalarType = LHSVecType ? RHSType : LHSType; 7946 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS; 7947 if (isLaxVectorConversion(ScalarType, VecType) && 7948 !ScalarExpr->get()->isLValue()) { 7949 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast); 7950 return VecType; 7951 } 7952 7953 // Okay, the expression is invalid. 7954 7955 // If there's a non-vector, non-real operand, diagnose that. 7956 if ((!RHSVecType && !RHSType->isRealType()) || 7957 (!LHSVecType && !LHSType->isRealType())) { 7958 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7959 << LHSType << RHSType 7960 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7961 return QualType(); 7962 } 7963 7964 // OpenCL V1.1 6.2.6.p1: 7965 // If the operands are of more than one vector type, then an error shall 7966 // occur. Implicit conversions between vector types are not permitted, per 7967 // section 6.2.1. 7968 if (getLangOpts().OpenCL && 7969 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7970 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7971 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7972 << RHSType; 7973 return QualType(); 7974 } 7975 7976 // Otherwise, use the generic diagnostic. 7977 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7978 << LHSType << RHSType 7979 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7980 return QualType(); 7981 } 7982 7983 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7984 // expression. These are mainly cases where the null pointer is used as an 7985 // integer instead of a pointer. 7986 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7987 SourceLocation Loc, bool IsCompare) { 7988 // The canonical way to check for a GNU null is with isNullPointerConstant, 7989 // but we use a bit of a hack here for speed; this is a relatively 7990 // hot path, and isNullPointerConstant is slow. 7991 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7992 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7993 7994 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7995 7996 // Avoid analyzing cases where the result will either be invalid (and 7997 // diagnosed as such) or entirely valid and not something to warn about. 7998 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7999 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8000 return; 8001 8002 // Comparison operations would not make sense with a null pointer no matter 8003 // what the other expression is. 8004 if (!IsCompare) { 8005 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8006 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8007 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8008 return; 8009 } 8010 8011 // The rest of the operations only make sense with a null pointer 8012 // if the other expression is a pointer. 8013 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8014 NonNullType->canDecayToPointerType()) 8015 return; 8016 8017 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8018 << LHSNull /* LHS is NULL */ << NonNullType 8019 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8020 } 8021 8022 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8023 ExprResult &RHS, 8024 SourceLocation Loc, bool IsDiv) { 8025 // Check for division/remainder by zero. 8026 llvm::APSInt RHSValue; 8027 if (!RHS.get()->isValueDependent() && 8028 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8029 S.DiagRuntimeBehavior(Loc, RHS.get(), 8030 S.PDiag(diag::warn_remainder_division_by_zero) 8031 << IsDiv << RHS.get()->getSourceRange()); 8032 } 8033 8034 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8035 SourceLocation Loc, 8036 bool IsCompAssign, bool IsDiv) { 8037 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8038 8039 if (LHS.get()->getType()->isVectorType() || 8040 RHS.get()->getType()->isVectorType()) 8041 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8042 /*AllowBothBool*/getLangOpts().AltiVec, 8043 /*AllowBoolConversions*/false); 8044 8045 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8046 if (LHS.isInvalid() || RHS.isInvalid()) 8047 return QualType(); 8048 8049 8050 if (compType.isNull() || !compType->isArithmeticType()) 8051 return InvalidOperands(Loc, LHS, RHS); 8052 if (IsDiv) 8053 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8054 return compType; 8055 } 8056 8057 QualType Sema::CheckRemainderOperands( 8058 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8059 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8060 8061 if (LHS.get()->getType()->isVectorType() || 8062 RHS.get()->getType()->isVectorType()) { 8063 if (LHS.get()->getType()->hasIntegerRepresentation() && 8064 RHS.get()->getType()->hasIntegerRepresentation()) 8065 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8066 /*AllowBothBool*/getLangOpts().AltiVec, 8067 /*AllowBoolConversions*/false); 8068 return InvalidOperands(Loc, LHS, RHS); 8069 } 8070 8071 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8072 if (LHS.isInvalid() || RHS.isInvalid()) 8073 return QualType(); 8074 8075 if (compType.isNull() || !compType->isIntegerType()) 8076 return InvalidOperands(Loc, LHS, RHS); 8077 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8078 return compType; 8079 } 8080 8081 /// \brief Diagnose invalid arithmetic on two void pointers. 8082 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8083 Expr *LHSExpr, Expr *RHSExpr) { 8084 S.Diag(Loc, S.getLangOpts().CPlusPlus 8085 ? diag::err_typecheck_pointer_arith_void_type 8086 : diag::ext_gnu_void_ptr) 8087 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8088 << RHSExpr->getSourceRange(); 8089 } 8090 8091 /// \brief Diagnose invalid arithmetic on a void pointer. 8092 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8093 Expr *Pointer) { 8094 S.Diag(Loc, S.getLangOpts().CPlusPlus 8095 ? diag::err_typecheck_pointer_arith_void_type 8096 : diag::ext_gnu_void_ptr) 8097 << 0 /* one pointer */ << Pointer->getSourceRange(); 8098 } 8099 8100 /// \brief Diagnose invalid arithmetic on two function pointers. 8101 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8102 Expr *LHS, Expr *RHS) { 8103 assert(LHS->getType()->isAnyPointerType()); 8104 assert(RHS->getType()->isAnyPointerType()); 8105 S.Diag(Loc, S.getLangOpts().CPlusPlus 8106 ? diag::err_typecheck_pointer_arith_function_type 8107 : diag::ext_gnu_ptr_func_arith) 8108 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8109 // We only show the second type if it differs from the first. 8110 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8111 RHS->getType()) 8112 << RHS->getType()->getPointeeType() 8113 << LHS->getSourceRange() << RHS->getSourceRange(); 8114 } 8115 8116 /// \brief Diagnose invalid arithmetic on a function pointer. 8117 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8118 Expr *Pointer) { 8119 assert(Pointer->getType()->isAnyPointerType()); 8120 S.Diag(Loc, S.getLangOpts().CPlusPlus 8121 ? diag::err_typecheck_pointer_arith_function_type 8122 : diag::ext_gnu_ptr_func_arith) 8123 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8124 << 0 /* one pointer, so only one type */ 8125 << Pointer->getSourceRange(); 8126 } 8127 8128 /// \brief Emit error if Operand is incomplete pointer type 8129 /// 8130 /// \returns True if pointer has incomplete type 8131 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8132 Expr *Operand) { 8133 QualType ResType = Operand->getType(); 8134 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8135 ResType = ResAtomicType->getValueType(); 8136 8137 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8138 QualType PointeeTy = ResType->getPointeeType(); 8139 return S.RequireCompleteType(Loc, PointeeTy, 8140 diag::err_typecheck_arithmetic_incomplete_type, 8141 PointeeTy, Operand->getSourceRange()); 8142 } 8143 8144 /// \brief Check the validity of an arithmetic pointer operand. 8145 /// 8146 /// If the operand has pointer type, this code will check for pointer types 8147 /// which are invalid in arithmetic operations. These will be diagnosed 8148 /// appropriately, including whether or not the use is supported as an 8149 /// extension. 8150 /// 8151 /// \returns True when the operand is valid to use (even if as an extension). 8152 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8153 Expr *Operand) { 8154 QualType ResType = Operand->getType(); 8155 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8156 ResType = ResAtomicType->getValueType(); 8157 8158 if (!ResType->isAnyPointerType()) return true; 8159 8160 QualType PointeeTy = ResType->getPointeeType(); 8161 if (PointeeTy->isVoidType()) { 8162 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8163 return !S.getLangOpts().CPlusPlus; 8164 } 8165 if (PointeeTy->isFunctionType()) { 8166 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8167 return !S.getLangOpts().CPlusPlus; 8168 } 8169 8170 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8171 8172 return true; 8173 } 8174 8175 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8176 /// operands. 8177 /// 8178 /// This routine will diagnose any invalid arithmetic on pointer operands much 8179 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8180 /// for emitting a single diagnostic even for operations where both LHS and RHS 8181 /// are (potentially problematic) pointers. 8182 /// 8183 /// \returns True when the operand is valid to use (even if as an extension). 8184 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8185 Expr *LHSExpr, Expr *RHSExpr) { 8186 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8187 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8188 if (!isLHSPointer && !isRHSPointer) return true; 8189 8190 QualType LHSPointeeTy, RHSPointeeTy; 8191 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8192 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8193 8194 // if both are pointers check if operation is valid wrt address spaces 8195 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8196 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8197 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8198 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8199 S.Diag(Loc, 8200 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8201 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8202 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8203 return false; 8204 } 8205 } 8206 8207 // Check for arithmetic on pointers to incomplete types. 8208 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8209 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8210 if (isLHSVoidPtr || isRHSVoidPtr) { 8211 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8212 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8213 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8214 8215 return !S.getLangOpts().CPlusPlus; 8216 } 8217 8218 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8219 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8220 if (isLHSFuncPtr || isRHSFuncPtr) { 8221 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8222 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8223 RHSExpr); 8224 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8225 8226 return !S.getLangOpts().CPlusPlus; 8227 } 8228 8229 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8230 return false; 8231 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8232 return false; 8233 8234 return true; 8235 } 8236 8237 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8238 /// literal. 8239 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8240 Expr *LHSExpr, Expr *RHSExpr) { 8241 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8242 Expr* IndexExpr = RHSExpr; 8243 if (!StrExpr) { 8244 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8245 IndexExpr = LHSExpr; 8246 } 8247 8248 bool IsStringPlusInt = StrExpr && 8249 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8250 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8251 return; 8252 8253 llvm::APSInt index; 8254 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8255 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8256 if (index.isNonNegative() && 8257 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8258 index.isUnsigned())) 8259 return; 8260 } 8261 8262 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8263 Self.Diag(OpLoc, diag::warn_string_plus_int) 8264 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8265 8266 // Only print a fixit for "str" + int, not for int + "str". 8267 if (IndexExpr == RHSExpr) { 8268 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8269 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8270 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8271 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8272 << FixItHint::CreateInsertion(EndLoc, "]"); 8273 } else 8274 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8275 } 8276 8277 /// \brief Emit a warning when adding a char literal to a string. 8278 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8279 Expr *LHSExpr, Expr *RHSExpr) { 8280 const Expr *StringRefExpr = LHSExpr; 8281 const CharacterLiteral *CharExpr = 8282 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8283 8284 if (!CharExpr) { 8285 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8286 StringRefExpr = RHSExpr; 8287 } 8288 8289 if (!CharExpr || !StringRefExpr) 8290 return; 8291 8292 const QualType StringType = StringRefExpr->getType(); 8293 8294 // Return if not a PointerType. 8295 if (!StringType->isAnyPointerType()) 8296 return; 8297 8298 // Return if not a CharacterType. 8299 if (!StringType->getPointeeType()->isAnyCharacterType()) 8300 return; 8301 8302 ASTContext &Ctx = Self.getASTContext(); 8303 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8304 8305 const QualType CharType = CharExpr->getType(); 8306 if (!CharType->isAnyCharacterType() && 8307 CharType->isIntegerType() && 8308 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8309 Self.Diag(OpLoc, diag::warn_string_plus_char) 8310 << DiagRange << Ctx.CharTy; 8311 } else { 8312 Self.Diag(OpLoc, diag::warn_string_plus_char) 8313 << DiagRange << CharExpr->getType(); 8314 } 8315 8316 // Only print a fixit for str + char, not for char + str. 8317 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8318 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8319 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8320 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8321 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8322 << FixItHint::CreateInsertion(EndLoc, "]"); 8323 } else { 8324 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8325 } 8326 } 8327 8328 /// \brief Emit error when two pointers are incompatible. 8329 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8330 Expr *LHSExpr, Expr *RHSExpr) { 8331 assert(LHSExpr->getType()->isAnyPointerType()); 8332 assert(RHSExpr->getType()->isAnyPointerType()); 8333 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8334 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8335 << RHSExpr->getSourceRange(); 8336 } 8337 8338 // C99 6.5.6 8339 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8340 SourceLocation Loc, BinaryOperatorKind Opc, 8341 QualType* CompLHSTy) { 8342 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8343 8344 if (LHS.get()->getType()->isVectorType() || 8345 RHS.get()->getType()->isVectorType()) { 8346 QualType compType = CheckVectorOperands( 8347 LHS, RHS, Loc, CompLHSTy, 8348 /*AllowBothBool*/getLangOpts().AltiVec, 8349 /*AllowBoolConversions*/getLangOpts().ZVector); 8350 if (CompLHSTy) *CompLHSTy = compType; 8351 return compType; 8352 } 8353 8354 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8355 if (LHS.isInvalid() || RHS.isInvalid()) 8356 return QualType(); 8357 8358 // Diagnose "string literal" '+' int and string '+' "char literal". 8359 if (Opc == BO_Add) { 8360 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8361 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8362 } 8363 8364 // handle the common case first (both operands are arithmetic). 8365 if (!compType.isNull() && compType->isArithmeticType()) { 8366 if (CompLHSTy) *CompLHSTy = compType; 8367 return compType; 8368 } 8369 8370 // Type-checking. Ultimately the pointer's going to be in PExp; 8371 // note that we bias towards the LHS being the pointer. 8372 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8373 8374 bool isObjCPointer; 8375 if (PExp->getType()->isPointerType()) { 8376 isObjCPointer = false; 8377 } else if (PExp->getType()->isObjCObjectPointerType()) { 8378 isObjCPointer = true; 8379 } else { 8380 std::swap(PExp, IExp); 8381 if (PExp->getType()->isPointerType()) { 8382 isObjCPointer = false; 8383 } else if (PExp->getType()->isObjCObjectPointerType()) { 8384 isObjCPointer = true; 8385 } else { 8386 return InvalidOperands(Loc, LHS, RHS); 8387 } 8388 } 8389 assert(PExp->getType()->isAnyPointerType()); 8390 8391 if (!IExp->getType()->isIntegerType()) 8392 return InvalidOperands(Loc, LHS, RHS); 8393 8394 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8395 return QualType(); 8396 8397 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8398 return QualType(); 8399 8400 // Check array bounds for pointer arithemtic 8401 CheckArrayAccess(PExp, IExp); 8402 8403 if (CompLHSTy) { 8404 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8405 if (LHSTy.isNull()) { 8406 LHSTy = LHS.get()->getType(); 8407 if (LHSTy->isPromotableIntegerType()) 8408 LHSTy = Context.getPromotedIntegerType(LHSTy); 8409 } 8410 *CompLHSTy = LHSTy; 8411 } 8412 8413 return PExp->getType(); 8414 } 8415 8416 // C99 6.5.6 8417 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8418 SourceLocation Loc, 8419 QualType* CompLHSTy) { 8420 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8421 8422 if (LHS.get()->getType()->isVectorType() || 8423 RHS.get()->getType()->isVectorType()) { 8424 QualType compType = CheckVectorOperands( 8425 LHS, RHS, Loc, CompLHSTy, 8426 /*AllowBothBool*/getLangOpts().AltiVec, 8427 /*AllowBoolConversions*/getLangOpts().ZVector); 8428 if (CompLHSTy) *CompLHSTy = compType; 8429 return compType; 8430 } 8431 8432 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8433 if (LHS.isInvalid() || RHS.isInvalid()) 8434 return QualType(); 8435 8436 // Enforce type constraints: C99 6.5.6p3. 8437 8438 // Handle the common case first (both operands are arithmetic). 8439 if (!compType.isNull() && compType->isArithmeticType()) { 8440 if (CompLHSTy) *CompLHSTy = compType; 8441 return compType; 8442 } 8443 8444 // Either ptr - int or ptr - ptr. 8445 if (LHS.get()->getType()->isAnyPointerType()) { 8446 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8447 8448 // Diagnose bad cases where we step over interface counts. 8449 if (LHS.get()->getType()->isObjCObjectPointerType() && 8450 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8451 return QualType(); 8452 8453 // The result type of a pointer-int computation is the pointer type. 8454 if (RHS.get()->getType()->isIntegerType()) { 8455 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8456 return QualType(); 8457 8458 // Check array bounds for pointer arithemtic 8459 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8460 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8461 8462 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8463 return LHS.get()->getType(); 8464 } 8465 8466 // Handle pointer-pointer subtractions. 8467 if (const PointerType *RHSPTy 8468 = RHS.get()->getType()->getAs<PointerType>()) { 8469 QualType rpointee = RHSPTy->getPointeeType(); 8470 8471 if (getLangOpts().CPlusPlus) { 8472 // Pointee types must be the same: C++ [expr.add] 8473 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8474 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8475 } 8476 } else { 8477 // Pointee types must be compatible C99 6.5.6p3 8478 if (!Context.typesAreCompatible( 8479 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8480 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8481 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8482 return QualType(); 8483 } 8484 } 8485 8486 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8487 LHS.get(), RHS.get())) 8488 return QualType(); 8489 8490 // The pointee type may have zero size. As an extension, a structure or 8491 // union may have zero size or an array may have zero length. In this 8492 // case subtraction does not make sense. 8493 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8494 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8495 if (ElementSize.isZero()) { 8496 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8497 << rpointee.getUnqualifiedType() 8498 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8499 } 8500 } 8501 8502 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8503 return Context.getPointerDiffType(); 8504 } 8505 } 8506 8507 return InvalidOperands(Loc, LHS, RHS); 8508 } 8509 8510 static bool isScopedEnumerationType(QualType T) { 8511 if (const EnumType *ET = T->getAs<EnumType>()) 8512 return ET->getDecl()->isScoped(); 8513 return false; 8514 } 8515 8516 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8517 SourceLocation Loc, BinaryOperatorKind Opc, 8518 QualType LHSType) { 8519 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8520 // so skip remaining warnings as we don't want to modify values within Sema. 8521 if (S.getLangOpts().OpenCL) 8522 return; 8523 8524 llvm::APSInt Right; 8525 // Check right/shifter operand 8526 if (RHS.get()->isValueDependent() || 8527 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8528 return; 8529 8530 if (Right.isNegative()) { 8531 S.DiagRuntimeBehavior(Loc, RHS.get(), 8532 S.PDiag(diag::warn_shift_negative) 8533 << RHS.get()->getSourceRange()); 8534 return; 8535 } 8536 llvm::APInt LeftBits(Right.getBitWidth(), 8537 S.Context.getTypeSize(LHS.get()->getType())); 8538 if (Right.uge(LeftBits)) { 8539 S.DiagRuntimeBehavior(Loc, RHS.get(), 8540 S.PDiag(diag::warn_shift_gt_typewidth) 8541 << RHS.get()->getSourceRange()); 8542 return; 8543 } 8544 if (Opc != BO_Shl) 8545 return; 8546 8547 // When left shifting an ICE which is signed, we can check for overflow which 8548 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8549 // integers have defined behavior modulo one more than the maximum value 8550 // representable in the result type, so never warn for those. 8551 llvm::APSInt Left; 8552 if (LHS.get()->isValueDependent() || 8553 LHSType->hasUnsignedIntegerRepresentation() || 8554 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8555 return; 8556 8557 // If LHS does not have a signed type and non-negative value 8558 // then, the behavior is undefined. Warn about it. 8559 if (Left.isNegative()) { 8560 S.DiagRuntimeBehavior(Loc, LHS.get(), 8561 S.PDiag(diag::warn_shift_lhs_negative) 8562 << LHS.get()->getSourceRange()); 8563 return; 8564 } 8565 8566 llvm::APInt ResultBits = 8567 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8568 if (LeftBits.uge(ResultBits)) 8569 return; 8570 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8571 Result = Result.shl(Right); 8572 8573 // Print the bit representation of the signed integer as an unsigned 8574 // hexadecimal number. 8575 SmallString<40> HexResult; 8576 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8577 8578 // If we are only missing a sign bit, this is less likely to result in actual 8579 // bugs -- if the result is cast back to an unsigned type, it will have the 8580 // expected value. Thus we place this behind a different warning that can be 8581 // turned off separately if needed. 8582 if (LeftBits == ResultBits - 1) { 8583 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8584 << HexResult << LHSType 8585 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8586 return; 8587 } 8588 8589 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8590 << HexResult.str() << Result.getMinSignedBits() << LHSType 8591 << Left.getBitWidth() << LHS.get()->getSourceRange() 8592 << RHS.get()->getSourceRange(); 8593 } 8594 8595 /// \brief Return the resulting type when an OpenCL vector is shifted 8596 /// by a scalar or vector shift amount. 8597 static QualType checkOpenCLVectorShift(Sema &S, 8598 ExprResult &LHS, ExprResult &RHS, 8599 SourceLocation Loc, bool IsCompAssign) { 8600 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8601 if (!LHS.get()->getType()->isVectorType()) { 8602 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8603 << RHS.get()->getType() << LHS.get()->getType() 8604 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8605 return QualType(); 8606 } 8607 8608 if (!IsCompAssign) { 8609 LHS = S.UsualUnaryConversions(LHS.get()); 8610 if (LHS.isInvalid()) return QualType(); 8611 } 8612 8613 RHS = S.UsualUnaryConversions(RHS.get()); 8614 if (RHS.isInvalid()) return QualType(); 8615 8616 QualType LHSType = LHS.get()->getType(); 8617 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8618 QualType LHSEleType = LHSVecTy->getElementType(); 8619 8620 // Note that RHS might not be a vector. 8621 QualType RHSType = RHS.get()->getType(); 8622 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8623 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8624 8625 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8626 if (!LHSEleType->isIntegerType()) { 8627 S.Diag(Loc, diag::err_typecheck_expect_int) 8628 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8629 return QualType(); 8630 } 8631 8632 if (!RHSEleType->isIntegerType()) { 8633 S.Diag(Loc, diag::err_typecheck_expect_int) 8634 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8635 return QualType(); 8636 } 8637 8638 if (RHSVecTy) { 8639 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8640 // are applied component-wise. So if RHS is a vector, then ensure 8641 // that the number of elements is the same as LHS... 8642 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8643 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8644 << LHS.get()->getType() << RHS.get()->getType() 8645 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8646 return QualType(); 8647 } 8648 } else { 8649 // ...else expand RHS to match the number of elements in LHS. 8650 QualType VecTy = 8651 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8652 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8653 } 8654 8655 return LHSType; 8656 } 8657 8658 // C99 6.5.7 8659 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8660 SourceLocation Loc, BinaryOperatorKind Opc, 8661 bool IsCompAssign) { 8662 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8663 8664 // Vector shifts promote their scalar inputs to vector type. 8665 if (LHS.get()->getType()->isVectorType() || 8666 RHS.get()->getType()->isVectorType()) { 8667 if (LangOpts.OpenCL) 8668 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8669 if (LangOpts.ZVector) { 8670 // The shift operators for the z vector extensions work basically 8671 // like OpenCL shifts, except that neither the LHS nor the RHS is 8672 // allowed to be a "vector bool". 8673 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8674 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8675 return InvalidOperands(Loc, LHS, RHS); 8676 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8677 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8678 return InvalidOperands(Loc, LHS, RHS); 8679 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8680 } 8681 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8682 /*AllowBothBool*/true, 8683 /*AllowBoolConversions*/false); 8684 } 8685 8686 // Shifts don't perform usual arithmetic conversions, they just do integer 8687 // promotions on each operand. C99 6.5.7p3 8688 8689 // For the LHS, do usual unary conversions, but then reset them away 8690 // if this is a compound assignment. 8691 ExprResult OldLHS = LHS; 8692 LHS = UsualUnaryConversions(LHS.get()); 8693 if (LHS.isInvalid()) 8694 return QualType(); 8695 QualType LHSType = LHS.get()->getType(); 8696 if (IsCompAssign) LHS = OldLHS; 8697 8698 // The RHS is simpler. 8699 RHS = UsualUnaryConversions(RHS.get()); 8700 if (RHS.isInvalid()) 8701 return QualType(); 8702 QualType RHSType = RHS.get()->getType(); 8703 8704 // C99 6.5.7p2: Each of the operands shall have integer type. 8705 if (!LHSType->hasIntegerRepresentation() || 8706 !RHSType->hasIntegerRepresentation()) 8707 return InvalidOperands(Loc, LHS, RHS); 8708 8709 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8710 // hasIntegerRepresentation() above instead of this. 8711 if (isScopedEnumerationType(LHSType) || 8712 isScopedEnumerationType(RHSType)) { 8713 return InvalidOperands(Loc, LHS, RHS); 8714 } 8715 // Sanity-check shift operands 8716 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8717 8718 // "The type of the result is that of the promoted left operand." 8719 return LHSType; 8720 } 8721 8722 static bool IsWithinTemplateSpecialization(Decl *D) { 8723 if (DeclContext *DC = D->getDeclContext()) { 8724 if (isa<ClassTemplateSpecializationDecl>(DC)) 8725 return true; 8726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8727 return FD->isFunctionTemplateSpecialization(); 8728 } 8729 return false; 8730 } 8731 8732 /// If two different enums are compared, raise a warning. 8733 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8734 Expr *RHS) { 8735 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8736 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8737 8738 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8739 if (!LHSEnumType) 8740 return; 8741 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8742 if (!RHSEnumType) 8743 return; 8744 8745 // Ignore anonymous enums. 8746 if (!LHSEnumType->getDecl()->getIdentifier()) 8747 return; 8748 if (!RHSEnumType->getDecl()->getIdentifier()) 8749 return; 8750 8751 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8752 return; 8753 8754 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8755 << LHSStrippedType << RHSStrippedType 8756 << LHS->getSourceRange() << RHS->getSourceRange(); 8757 } 8758 8759 /// \brief Diagnose bad pointer comparisons. 8760 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8761 ExprResult &LHS, ExprResult &RHS, 8762 bool IsError) { 8763 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8764 : diag::ext_typecheck_comparison_of_distinct_pointers) 8765 << LHS.get()->getType() << RHS.get()->getType() 8766 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8767 } 8768 8769 /// \brief Returns false if the pointers are converted to a composite type, 8770 /// true otherwise. 8771 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8772 ExprResult &LHS, ExprResult &RHS) { 8773 // C++ [expr.rel]p2: 8774 // [...] Pointer conversions (4.10) and qualification 8775 // conversions (4.4) are performed on pointer operands (or on 8776 // a pointer operand and a null pointer constant) to bring 8777 // them to their composite pointer type. [...] 8778 // 8779 // C++ [expr.eq]p1 uses the same notion for (in)equality 8780 // comparisons of pointers. 8781 8782 // C++ [expr.eq]p2: 8783 // In addition, pointers to members can be compared, or a pointer to 8784 // member and a null pointer constant. Pointer to member conversions 8785 // (4.11) and qualification conversions (4.4) are performed to bring 8786 // them to a common type. If one operand is a null pointer constant, 8787 // the common type is the type of the other operand. Otherwise, the 8788 // common type is a pointer to member type similar (4.4) to the type 8789 // of one of the operands, with a cv-qualification signature (4.4) 8790 // that is the union of the cv-qualification signatures of the operand 8791 // types. 8792 8793 QualType LHSType = LHS.get()->getType(); 8794 QualType RHSType = RHS.get()->getType(); 8795 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8796 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8797 8798 bool NonStandardCompositeType = false; 8799 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8800 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8801 if (T.isNull()) { 8802 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8803 return true; 8804 } 8805 8806 if (NonStandardCompositeType) 8807 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8808 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8809 << RHS.get()->getSourceRange(); 8810 8811 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8812 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8813 return false; 8814 } 8815 8816 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8817 ExprResult &LHS, 8818 ExprResult &RHS, 8819 bool IsError) { 8820 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8821 : diag::ext_typecheck_comparison_of_fptr_to_void) 8822 << LHS.get()->getType() << RHS.get()->getType() 8823 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8824 } 8825 8826 static bool isObjCObjectLiteral(ExprResult &E) { 8827 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8828 case Stmt::ObjCArrayLiteralClass: 8829 case Stmt::ObjCDictionaryLiteralClass: 8830 case Stmt::ObjCStringLiteralClass: 8831 case Stmt::ObjCBoxedExprClass: 8832 return true; 8833 default: 8834 // Note that ObjCBoolLiteral is NOT an object literal! 8835 return false; 8836 } 8837 } 8838 8839 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8840 const ObjCObjectPointerType *Type = 8841 LHS->getType()->getAs<ObjCObjectPointerType>(); 8842 8843 // If this is not actually an Objective-C object, bail out. 8844 if (!Type) 8845 return false; 8846 8847 // Get the LHS object's interface type. 8848 QualType InterfaceType = Type->getPointeeType(); 8849 8850 // If the RHS isn't an Objective-C object, bail out. 8851 if (!RHS->getType()->isObjCObjectPointerType()) 8852 return false; 8853 8854 // Try to find the -isEqual: method. 8855 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8856 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8857 InterfaceType, 8858 /*instance=*/true); 8859 if (!Method) { 8860 if (Type->isObjCIdType()) { 8861 // For 'id', just check the global pool. 8862 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8863 /*receiverId=*/true); 8864 } else { 8865 // Check protocols. 8866 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8867 /*instance=*/true); 8868 } 8869 } 8870 8871 if (!Method) 8872 return false; 8873 8874 QualType T = Method->parameters()[0]->getType(); 8875 if (!T->isObjCObjectPointerType()) 8876 return false; 8877 8878 QualType R = Method->getReturnType(); 8879 if (!R->isScalarType()) 8880 return false; 8881 8882 return true; 8883 } 8884 8885 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8886 FromE = FromE->IgnoreParenImpCasts(); 8887 switch (FromE->getStmtClass()) { 8888 default: 8889 break; 8890 case Stmt::ObjCStringLiteralClass: 8891 // "string literal" 8892 return LK_String; 8893 case Stmt::ObjCArrayLiteralClass: 8894 // "array literal" 8895 return LK_Array; 8896 case Stmt::ObjCDictionaryLiteralClass: 8897 // "dictionary literal" 8898 return LK_Dictionary; 8899 case Stmt::BlockExprClass: 8900 return LK_Block; 8901 case Stmt::ObjCBoxedExprClass: { 8902 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8903 switch (Inner->getStmtClass()) { 8904 case Stmt::IntegerLiteralClass: 8905 case Stmt::FloatingLiteralClass: 8906 case Stmt::CharacterLiteralClass: 8907 case Stmt::ObjCBoolLiteralExprClass: 8908 case Stmt::CXXBoolLiteralExprClass: 8909 // "numeric literal" 8910 return LK_Numeric; 8911 case Stmt::ImplicitCastExprClass: { 8912 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8913 // Boolean literals can be represented by implicit casts. 8914 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8915 return LK_Numeric; 8916 break; 8917 } 8918 default: 8919 break; 8920 } 8921 return LK_Boxed; 8922 } 8923 } 8924 return LK_None; 8925 } 8926 8927 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8928 ExprResult &LHS, ExprResult &RHS, 8929 BinaryOperator::Opcode Opc){ 8930 Expr *Literal; 8931 Expr *Other; 8932 if (isObjCObjectLiteral(LHS)) { 8933 Literal = LHS.get(); 8934 Other = RHS.get(); 8935 } else { 8936 Literal = RHS.get(); 8937 Other = LHS.get(); 8938 } 8939 8940 // Don't warn on comparisons against nil. 8941 Other = Other->IgnoreParenCasts(); 8942 if (Other->isNullPointerConstant(S.getASTContext(), 8943 Expr::NPC_ValueDependentIsNotNull)) 8944 return; 8945 8946 // This should be kept in sync with warn_objc_literal_comparison. 8947 // LK_String should always be after the other literals, since it has its own 8948 // warning flag. 8949 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8950 assert(LiteralKind != Sema::LK_Block); 8951 if (LiteralKind == Sema::LK_None) { 8952 llvm_unreachable("Unknown Objective-C object literal kind"); 8953 } 8954 8955 if (LiteralKind == Sema::LK_String) 8956 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8957 << Literal->getSourceRange(); 8958 else 8959 S.Diag(Loc, diag::warn_objc_literal_comparison) 8960 << LiteralKind << Literal->getSourceRange(); 8961 8962 if (BinaryOperator::isEqualityOp(Opc) && 8963 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8964 SourceLocation Start = LHS.get()->getLocStart(); 8965 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8966 CharSourceRange OpRange = 8967 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8968 8969 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8970 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8971 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8972 << FixItHint::CreateInsertion(End, "]"); 8973 } 8974 } 8975 8976 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8977 ExprResult &RHS, 8978 SourceLocation Loc, 8979 BinaryOperatorKind Opc) { 8980 // Check that left hand side is !something. 8981 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8982 if (!UO || UO->getOpcode() != UO_LNot) return; 8983 8984 // Only check if the right hand side is non-bool arithmetic type. 8985 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8986 8987 // Make sure that the something in !something is not bool. 8988 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8989 if (SubExpr->isKnownToHaveBooleanValue()) return; 8990 8991 // Emit warning. 8992 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8993 << Loc; 8994 8995 // First note suggest !(x < y) 8996 SourceLocation FirstOpen = SubExpr->getLocStart(); 8997 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8998 FirstClose = S.getLocForEndOfToken(FirstClose); 8999 if (FirstClose.isInvalid()) 9000 FirstOpen = SourceLocation(); 9001 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9002 << FixItHint::CreateInsertion(FirstOpen, "(") 9003 << FixItHint::CreateInsertion(FirstClose, ")"); 9004 9005 // Second note suggests (!x) < y 9006 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9007 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9008 SecondClose = S.getLocForEndOfToken(SecondClose); 9009 if (SecondClose.isInvalid()) 9010 SecondOpen = SourceLocation(); 9011 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9012 << FixItHint::CreateInsertion(SecondOpen, "(") 9013 << FixItHint::CreateInsertion(SecondClose, ")"); 9014 } 9015 9016 // Get the decl for a simple expression: a reference to a variable, 9017 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9018 static ValueDecl *getCompareDecl(Expr *E) { 9019 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9020 return DR->getDecl(); 9021 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9022 if (Ivar->isFreeIvar()) 9023 return Ivar->getDecl(); 9024 } 9025 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9026 if (Mem->isImplicitAccess()) 9027 return Mem->getMemberDecl(); 9028 } 9029 return nullptr; 9030 } 9031 9032 // C99 6.5.8, C++ [expr.rel] 9033 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9034 SourceLocation Loc, BinaryOperatorKind Opc, 9035 bool IsRelational) { 9036 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9037 9038 // Handle vector comparisons separately. 9039 if (LHS.get()->getType()->isVectorType() || 9040 RHS.get()->getType()->isVectorType()) 9041 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9042 9043 QualType LHSType = LHS.get()->getType(); 9044 QualType RHSType = RHS.get()->getType(); 9045 9046 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9047 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9048 9049 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9050 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9051 9052 if (!LHSType->hasFloatingRepresentation() && 9053 !(LHSType->isBlockPointerType() && IsRelational) && 9054 !LHS.get()->getLocStart().isMacroID() && 9055 !RHS.get()->getLocStart().isMacroID() && 9056 ActiveTemplateInstantiations.empty()) { 9057 // For non-floating point types, check for self-comparisons of the form 9058 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9059 // often indicate logic errors in the program. 9060 // 9061 // NOTE: Don't warn about comparison expressions resulting from macro 9062 // expansion. Also don't warn about comparisons which are only self 9063 // comparisons within a template specialization. The warnings should catch 9064 // obvious cases in the definition of the template anyways. The idea is to 9065 // warn when the typed comparison operator will always evaluate to the same 9066 // result. 9067 ValueDecl *DL = getCompareDecl(LHSStripped); 9068 ValueDecl *DR = getCompareDecl(RHSStripped); 9069 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9070 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9071 << 0 // self- 9072 << (Opc == BO_EQ 9073 || Opc == BO_LE 9074 || Opc == BO_GE)); 9075 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9076 !DL->getType()->isReferenceType() && 9077 !DR->getType()->isReferenceType()) { 9078 // what is it always going to eval to? 9079 char always_evals_to; 9080 switch(Opc) { 9081 case BO_EQ: // e.g. array1 == array2 9082 always_evals_to = 0; // false 9083 break; 9084 case BO_NE: // e.g. array1 != array2 9085 always_evals_to = 1; // true 9086 break; 9087 default: 9088 // best we can say is 'a constant' 9089 always_evals_to = 2; // e.g. array1 <= array2 9090 break; 9091 } 9092 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9093 << 1 // array 9094 << always_evals_to); 9095 } 9096 9097 if (isa<CastExpr>(LHSStripped)) 9098 LHSStripped = LHSStripped->IgnoreParenCasts(); 9099 if (isa<CastExpr>(RHSStripped)) 9100 RHSStripped = RHSStripped->IgnoreParenCasts(); 9101 9102 // Warn about comparisons against a string constant (unless the other 9103 // operand is null), the user probably wants strcmp. 9104 Expr *literalString = nullptr; 9105 Expr *literalStringStripped = nullptr; 9106 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9107 !RHSStripped->isNullPointerConstant(Context, 9108 Expr::NPC_ValueDependentIsNull)) { 9109 literalString = LHS.get(); 9110 literalStringStripped = LHSStripped; 9111 } else if ((isa<StringLiteral>(RHSStripped) || 9112 isa<ObjCEncodeExpr>(RHSStripped)) && 9113 !LHSStripped->isNullPointerConstant(Context, 9114 Expr::NPC_ValueDependentIsNull)) { 9115 literalString = RHS.get(); 9116 literalStringStripped = RHSStripped; 9117 } 9118 9119 if (literalString) { 9120 DiagRuntimeBehavior(Loc, nullptr, 9121 PDiag(diag::warn_stringcompare) 9122 << isa<ObjCEncodeExpr>(literalStringStripped) 9123 << literalString->getSourceRange()); 9124 } 9125 } 9126 9127 // C99 6.5.8p3 / C99 6.5.9p4 9128 UsualArithmeticConversions(LHS, RHS); 9129 if (LHS.isInvalid() || RHS.isInvalid()) 9130 return QualType(); 9131 9132 LHSType = LHS.get()->getType(); 9133 RHSType = RHS.get()->getType(); 9134 9135 // The result of comparisons is 'bool' in C++, 'int' in C. 9136 QualType ResultTy = Context.getLogicalOperationType(); 9137 9138 if (IsRelational) { 9139 if (LHSType->isRealType() && RHSType->isRealType()) 9140 return ResultTy; 9141 } else { 9142 // Check for comparisons of floating point operands using != and ==. 9143 if (LHSType->hasFloatingRepresentation()) 9144 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9145 9146 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9147 return ResultTy; 9148 } 9149 9150 const Expr::NullPointerConstantKind LHSNullKind = 9151 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9152 const Expr::NullPointerConstantKind RHSNullKind = 9153 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9154 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9155 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9156 9157 if (!IsRelational && LHSIsNull != RHSIsNull) { 9158 bool IsEquality = Opc == BO_EQ; 9159 if (RHSIsNull) 9160 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9161 RHS.get()->getSourceRange()); 9162 else 9163 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9164 LHS.get()->getSourceRange()); 9165 } 9166 9167 // All of the following pointer-related warnings are GCC extensions, except 9168 // when handling null pointer constants. 9169 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9170 QualType LCanPointeeTy = 9171 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9172 QualType RCanPointeeTy = 9173 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9174 9175 if (getLangOpts().CPlusPlus) { 9176 if (LCanPointeeTy == RCanPointeeTy) 9177 return ResultTy; 9178 if (!IsRelational && 9179 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9180 // Valid unless comparison between non-null pointer and function pointer 9181 // This is a gcc extension compatibility comparison. 9182 // In a SFINAE context, we treat this as a hard error to maintain 9183 // conformance with the C++ standard. 9184 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9185 && !LHSIsNull && !RHSIsNull) { 9186 diagnoseFunctionPointerToVoidComparison( 9187 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9188 9189 if (isSFINAEContext()) 9190 return QualType(); 9191 9192 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9193 return ResultTy; 9194 } 9195 } 9196 9197 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9198 return QualType(); 9199 else 9200 return ResultTy; 9201 } 9202 // C99 6.5.9p2 and C99 6.5.8p2 9203 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9204 RCanPointeeTy.getUnqualifiedType())) { 9205 // Valid unless a relational comparison of function pointers 9206 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9207 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9208 << LHSType << RHSType << LHS.get()->getSourceRange() 9209 << RHS.get()->getSourceRange(); 9210 } 9211 } else if (!IsRelational && 9212 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9213 // Valid unless comparison between non-null pointer and function pointer 9214 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9215 && !LHSIsNull && !RHSIsNull) 9216 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9217 /*isError*/false); 9218 } else { 9219 // Invalid 9220 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9221 } 9222 if (LCanPointeeTy != RCanPointeeTy) { 9223 // Treat NULL constant as a special case in OpenCL. 9224 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9225 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9226 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9227 Diag(Loc, 9228 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9229 << LHSType << RHSType << 0 /* comparison */ 9230 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9231 } 9232 } 9233 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9234 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9235 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9236 : CK_BitCast; 9237 if (LHSIsNull && !RHSIsNull) 9238 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9239 else 9240 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9241 } 9242 return ResultTy; 9243 } 9244 9245 if (getLangOpts().CPlusPlus) { 9246 // Comparison of nullptr_t with itself. 9247 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9248 return ResultTy; 9249 9250 // Comparison of pointers with null pointer constants and equality 9251 // comparisons of member pointers to null pointer constants. 9252 if (RHSIsNull && 9253 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9254 (!IsRelational && 9255 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9256 RHS = ImpCastExprToType(RHS.get(), LHSType, 9257 LHSType->isMemberPointerType() 9258 ? CK_NullToMemberPointer 9259 : CK_NullToPointer); 9260 return ResultTy; 9261 } 9262 if (LHSIsNull && 9263 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9264 (!IsRelational && 9265 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9266 LHS = ImpCastExprToType(LHS.get(), RHSType, 9267 RHSType->isMemberPointerType() 9268 ? CK_NullToMemberPointer 9269 : CK_NullToPointer); 9270 return ResultTy; 9271 } 9272 9273 // Comparison of member pointers. 9274 if (!IsRelational && 9275 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9276 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9277 return QualType(); 9278 else 9279 return ResultTy; 9280 } 9281 9282 // Handle scoped enumeration types specifically, since they don't promote 9283 // to integers. 9284 if (LHS.get()->getType()->isEnumeralType() && 9285 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9286 RHS.get()->getType())) 9287 return ResultTy; 9288 } 9289 9290 // Handle block pointer types. 9291 if (!IsRelational && LHSType->isBlockPointerType() && 9292 RHSType->isBlockPointerType()) { 9293 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9294 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9295 9296 if (!LHSIsNull && !RHSIsNull && 9297 !Context.typesAreCompatible(lpointee, rpointee)) { 9298 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9299 << LHSType << RHSType << LHS.get()->getSourceRange() 9300 << RHS.get()->getSourceRange(); 9301 } 9302 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9303 return ResultTy; 9304 } 9305 9306 // Allow block pointers to be compared with null pointer constants. 9307 if (!IsRelational 9308 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9309 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9310 if (!LHSIsNull && !RHSIsNull) { 9311 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9312 ->getPointeeType()->isVoidType()) 9313 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9314 ->getPointeeType()->isVoidType()))) 9315 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9316 << LHSType << RHSType << LHS.get()->getSourceRange() 9317 << RHS.get()->getSourceRange(); 9318 } 9319 if (LHSIsNull && !RHSIsNull) 9320 LHS = ImpCastExprToType(LHS.get(), RHSType, 9321 RHSType->isPointerType() ? CK_BitCast 9322 : CK_AnyPointerToBlockPointerCast); 9323 else 9324 RHS = ImpCastExprToType(RHS.get(), LHSType, 9325 LHSType->isPointerType() ? CK_BitCast 9326 : CK_AnyPointerToBlockPointerCast); 9327 return ResultTy; 9328 } 9329 9330 if (LHSType->isObjCObjectPointerType() || 9331 RHSType->isObjCObjectPointerType()) { 9332 const PointerType *LPT = LHSType->getAs<PointerType>(); 9333 const PointerType *RPT = RHSType->getAs<PointerType>(); 9334 if (LPT || RPT) { 9335 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9336 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9337 9338 if (!LPtrToVoid && !RPtrToVoid && 9339 !Context.typesAreCompatible(LHSType, RHSType)) { 9340 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9341 /*isError*/false); 9342 } 9343 if (LHSIsNull && !RHSIsNull) { 9344 Expr *E = LHS.get(); 9345 if (getLangOpts().ObjCAutoRefCount) 9346 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9347 LHS = ImpCastExprToType(E, RHSType, 9348 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9349 } 9350 else { 9351 Expr *E = RHS.get(); 9352 if (getLangOpts().ObjCAutoRefCount) 9353 CheckObjCARCConversion(SourceRange(), LHSType, E, 9354 CCK_ImplicitConversion, /*Diagnose=*/true, 9355 /*DiagnoseCFAudited=*/false, Opc); 9356 RHS = ImpCastExprToType(E, LHSType, 9357 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9358 } 9359 return ResultTy; 9360 } 9361 if (LHSType->isObjCObjectPointerType() && 9362 RHSType->isObjCObjectPointerType()) { 9363 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9364 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9365 /*isError*/false); 9366 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9367 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9368 9369 if (LHSIsNull && !RHSIsNull) 9370 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9371 else 9372 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9373 return ResultTy; 9374 } 9375 } 9376 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9377 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9378 unsigned DiagID = 0; 9379 bool isError = false; 9380 if (LangOpts.DebuggerSupport) { 9381 // Under a debugger, allow the comparison of pointers to integers, 9382 // since users tend to want to compare addresses. 9383 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9384 (RHSIsNull && RHSType->isIntegerType())) { 9385 if (IsRelational && !getLangOpts().CPlusPlus) 9386 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9387 } else if (IsRelational && !getLangOpts().CPlusPlus) 9388 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9389 else if (getLangOpts().CPlusPlus) { 9390 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9391 isError = true; 9392 } else 9393 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9394 9395 if (DiagID) { 9396 Diag(Loc, DiagID) 9397 << LHSType << RHSType << LHS.get()->getSourceRange() 9398 << RHS.get()->getSourceRange(); 9399 if (isError) 9400 return QualType(); 9401 } 9402 9403 if (LHSType->isIntegerType()) 9404 LHS = ImpCastExprToType(LHS.get(), RHSType, 9405 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9406 else 9407 RHS = ImpCastExprToType(RHS.get(), LHSType, 9408 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9409 return ResultTy; 9410 } 9411 9412 // Handle block pointers. 9413 if (!IsRelational && RHSIsNull 9414 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9415 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9416 return ResultTy; 9417 } 9418 if (!IsRelational && LHSIsNull 9419 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9420 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9421 return ResultTy; 9422 } 9423 9424 return InvalidOperands(Loc, LHS, RHS); 9425 } 9426 9427 9428 // Return a signed type that is of identical size and number of elements. 9429 // For floating point vectors, return an integer type of identical size 9430 // and number of elements. 9431 QualType Sema::GetSignedVectorType(QualType V) { 9432 const VectorType *VTy = V->getAs<VectorType>(); 9433 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9434 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9435 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9436 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9437 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9438 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9439 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9440 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9441 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9442 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9443 "Unhandled vector element size in vector compare"); 9444 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9445 } 9446 9447 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9448 /// operates on extended vector types. Instead of producing an IntTy result, 9449 /// like a scalar comparison, a vector comparison produces a vector of integer 9450 /// types. 9451 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9452 SourceLocation Loc, 9453 bool IsRelational) { 9454 // Check to make sure we're operating on vectors of the same type and width, 9455 // Allowing one side to be a scalar of element type. 9456 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9457 /*AllowBothBool*/true, 9458 /*AllowBoolConversions*/getLangOpts().ZVector); 9459 if (vType.isNull()) 9460 return vType; 9461 9462 QualType LHSType = LHS.get()->getType(); 9463 9464 // If AltiVec, the comparison results in a numeric type, i.e. 9465 // bool for C++, int for C 9466 if (getLangOpts().AltiVec && 9467 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9468 return Context.getLogicalOperationType(); 9469 9470 // For non-floating point types, check for self-comparisons of the form 9471 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9472 // often indicate logic errors in the program. 9473 if (!LHSType->hasFloatingRepresentation() && 9474 ActiveTemplateInstantiations.empty()) { 9475 if (DeclRefExpr* DRL 9476 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9477 if (DeclRefExpr* DRR 9478 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9479 if (DRL->getDecl() == DRR->getDecl()) 9480 DiagRuntimeBehavior(Loc, nullptr, 9481 PDiag(diag::warn_comparison_always) 9482 << 0 // self- 9483 << 2 // "a constant" 9484 ); 9485 } 9486 9487 // Check for comparisons of floating point operands using != and ==. 9488 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9489 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9490 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9491 } 9492 9493 // Return a signed type for the vector. 9494 return GetSignedVectorType(vType); 9495 } 9496 9497 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9498 SourceLocation Loc) { 9499 // Ensure that either both operands are of the same vector type, or 9500 // one operand is of a vector type and the other is of its element type. 9501 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9502 /*AllowBothBool*/true, 9503 /*AllowBoolConversions*/false); 9504 if (vType.isNull()) 9505 return InvalidOperands(Loc, LHS, RHS); 9506 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9507 vType->hasFloatingRepresentation()) 9508 return InvalidOperands(Loc, LHS, RHS); 9509 9510 return GetSignedVectorType(LHS.get()->getType()); 9511 } 9512 9513 inline QualType Sema::CheckBitwiseOperands( 9514 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9515 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9516 9517 if (LHS.get()->getType()->isVectorType() || 9518 RHS.get()->getType()->isVectorType()) { 9519 if (LHS.get()->getType()->hasIntegerRepresentation() && 9520 RHS.get()->getType()->hasIntegerRepresentation()) 9521 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9522 /*AllowBothBool*/true, 9523 /*AllowBoolConversions*/getLangOpts().ZVector); 9524 return InvalidOperands(Loc, LHS, RHS); 9525 } 9526 9527 ExprResult LHSResult = LHS, RHSResult = RHS; 9528 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9529 IsCompAssign); 9530 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9531 return QualType(); 9532 LHS = LHSResult.get(); 9533 RHS = RHSResult.get(); 9534 9535 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9536 return compType; 9537 return InvalidOperands(Loc, LHS, RHS); 9538 } 9539 9540 // C99 6.5.[13,14] 9541 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9542 SourceLocation Loc, 9543 BinaryOperatorKind Opc) { 9544 // Check vector operands differently. 9545 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9546 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9547 9548 // Diagnose cases where the user write a logical and/or but probably meant a 9549 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9550 // is a constant. 9551 if (LHS.get()->getType()->isIntegerType() && 9552 !LHS.get()->getType()->isBooleanType() && 9553 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9554 // Don't warn in macros or template instantiations. 9555 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9556 // If the RHS can be constant folded, and if it constant folds to something 9557 // that isn't 0 or 1 (which indicate a potential logical operation that 9558 // happened to fold to true/false) then warn. 9559 // Parens on the RHS are ignored. 9560 llvm::APSInt Result; 9561 if (RHS.get()->EvaluateAsInt(Result, Context)) 9562 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9563 !RHS.get()->getExprLoc().isMacroID()) || 9564 (Result != 0 && Result != 1)) { 9565 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9566 << RHS.get()->getSourceRange() 9567 << (Opc == BO_LAnd ? "&&" : "||"); 9568 // Suggest replacing the logical operator with the bitwise version 9569 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9570 << (Opc == BO_LAnd ? "&" : "|") 9571 << FixItHint::CreateReplacement(SourceRange( 9572 Loc, getLocForEndOfToken(Loc)), 9573 Opc == BO_LAnd ? "&" : "|"); 9574 if (Opc == BO_LAnd) 9575 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9576 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9577 << FixItHint::CreateRemoval( 9578 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9579 RHS.get()->getLocEnd())); 9580 } 9581 } 9582 9583 if (!Context.getLangOpts().CPlusPlus) { 9584 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9585 // not operate on the built-in scalar and vector float types. 9586 if (Context.getLangOpts().OpenCL && 9587 Context.getLangOpts().OpenCLVersion < 120) { 9588 if (LHS.get()->getType()->isFloatingType() || 9589 RHS.get()->getType()->isFloatingType()) 9590 return InvalidOperands(Loc, LHS, RHS); 9591 } 9592 9593 LHS = UsualUnaryConversions(LHS.get()); 9594 if (LHS.isInvalid()) 9595 return QualType(); 9596 9597 RHS = UsualUnaryConversions(RHS.get()); 9598 if (RHS.isInvalid()) 9599 return QualType(); 9600 9601 if (!LHS.get()->getType()->isScalarType() || 9602 !RHS.get()->getType()->isScalarType()) 9603 return InvalidOperands(Loc, LHS, RHS); 9604 9605 return Context.IntTy; 9606 } 9607 9608 // The following is safe because we only use this method for 9609 // non-overloadable operands. 9610 9611 // C++ [expr.log.and]p1 9612 // C++ [expr.log.or]p1 9613 // The operands are both contextually converted to type bool. 9614 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9615 if (LHSRes.isInvalid()) 9616 return InvalidOperands(Loc, LHS, RHS); 9617 LHS = LHSRes; 9618 9619 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9620 if (RHSRes.isInvalid()) 9621 return InvalidOperands(Loc, LHS, RHS); 9622 RHS = RHSRes; 9623 9624 // C++ [expr.log.and]p2 9625 // C++ [expr.log.or]p2 9626 // The result is a bool. 9627 return Context.BoolTy; 9628 } 9629 9630 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9631 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9632 if (!ME) return false; 9633 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9634 ObjCMessageExpr *Base = 9635 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9636 if (!Base) return false; 9637 return Base->getMethodDecl() != nullptr; 9638 } 9639 9640 /// Is the given expression (which must be 'const') a reference to a 9641 /// variable which was originally non-const, but which has become 9642 /// 'const' due to being captured within a block? 9643 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9644 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9645 assert(E->isLValue() && E->getType().isConstQualified()); 9646 E = E->IgnoreParens(); 9647 9648 // Must be a reference to a declaration from an enclosing scope. 9649 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9650 if (!DRE) return NCCK_None; 9651 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9652 9653 // The declaration must be a variable which is not declared 'const'. 9654 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9655 if (!var) return NCCK_None; 9656 if (var->getType().isConstQualified()) return NCCK_None; 9657 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9658 9659 // Decide whether the first capture was for a block or a lambda. 9660 DeclContext *DC = S.CurContext, *Prev = nullptr; 9661 while (DC != var->getDeclContext()) { 9662 Prev = DC; 9663 DC = DC->getParent(); 9664 } 9665 // Unless we have an init-capture, we've gone one step too far. 9666 if (!var->isInitCapture()) 9667 DC = Prev; 9668 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9669 } 9670 9671 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9672 Ty = Ty.getNonReferenceType(); 9673 if (IsDereference && Ty->isPointerType()) 9674 Ty = Ty->getPointeeType(); 9675 return !Ty.isConstQualified(); 9676 } 9677 9678 /// Emit the "read-only variable not assignable" error and print notes to give 9679 /// more information about why the variable is not assignable, such as pointing 9680 /// to the declaration of a const variable, showing that a method is const, or 9681 /// that the function is returning a const reference. 9682 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9683 SourceLocation Loc) { 9684 // Update err_typecheck_assign_const and note_typecheck_assign_const 9685 // when this enum is changed. 9686 enum { 9687 ConstFunction, 9688 ConstVariable, 9689 ConstMember, 9690 ConstMethod, 9691 ConstUnknown, // Keep as last element 9692 }; 9693 9694 SourceRange ExprRange = E->getSourceRange(); 9695 9696 // Only emit one error on the first const found. All other consts will emit 9697 // a note to the error. 9698 bool DiagnosticEmitted = false; 9699 9700 // Track if the current expression is the result of a derefence, and if the 9701 // next checked expression is the result of a derefence. 9702 bool IsDereference = false; 9703 bool NextIsDereference = false; 9704 9705 // Loop to process MemberExpr chains. 9706 while (true) { 9707 IsDereference = NextIsDereference; 9708 NextIsDereference = false; 9709 9710 E = E->IgnoreParenImpCasts(); 9711 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9712 NextIsDereference = ME->isArrow(); 9713 const ValueDecl *VD = ME->getMemberDecl(); 9714 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9715 // Mutable fields can be modified even if the class is const. 9716 if (Field->isMutable()) { 9717 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9718 break; 9719 } 9720 9721 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9722 if (!DiagnosticEmitted) { 9723 S.Diag(Loc, diag::err_typecheck_assign_const) 9724 << ExprRange << ConstMember << false /*static*/ << Field 9725 << Field->getType(); 9726 DiagnosticEmitted = true; 9727 } 9728 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9729 << ConstMember << false /*static*/ << Field << Field->getType() 9730 << Field->getSourceRange(); 9731 } 9732 E = ME->getBase(); 9733 continue; 9734 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9735 if (VDecl->getType().isConstQualified()) { 9736 if (!DiagnosticEmitted) { 9737 S.Diag(Loc, diag::err_typecheck_assign_const) 9738 << ExprRange << ConstMember << true /*static*/ << VDecl 9739 << VDecl->getType(); 9740 DiagnosticEmitted = true; 9741 } 9742 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9743 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9744 << VDecl->getSourceRange(); 9745 } 9746 // Static fields do not inherit constness from parents. 9747 break; 9748 } 9749 break; 9750 } // End MemberExpr 9751 break; 9752 } 9753 9754 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9755 // Function calls 9756 const FunctionDecl *FD = CE->getDirectCallee(); 9757 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9758 if (!DiagnosticEmitted) { 9759 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9760 << ConstFunction << FD; 9761 DiagnosticEmitted = true; 9762 } 9763 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9764 diag::note_typecheck_assign_const) 9765 << ConstFunction << FD << FD->getReturnType() 9766 << FD->getReturnTypeSourceRange(); 9767 } 9768 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9769 // Point to variable declaration. 9770 if (const ValueDecl *VD = DRE->getDecl()) { 9771 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9772 if (!DiagnosticEmitted) { 9773 S.Diag(Loc, diag::err_typecheck_assign_const) 9774 << ExprRange << ConstVariable << VD << VD->getType(); 9775 DiagnosticEmitted = true; 9776 } 9777 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9778 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9779 } 9780 } 9781 } else if (isa<CXXThisExpr>(E)) { 9782 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9783 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9784 if (MD->isConst()) { 9785 if (!DiagnosticEmitted) { 9786 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9787 << ConstMethod << MD; 9788 DiagnosticEmitted = true; 9789 } 9790 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9791 << ConstMethod << MD << MD->getSourceRange(); 9792 } 9793 } 9794 } 9795 } 9796 9797 if (DiagnosticEmitted) 9798 return; 9799 9800 // Can't determine a more specific message, so display the generic error. 9801 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9802 } 9803 9804 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9805 /// emit an error and return true. If so, return false. 9806 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9807 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9808 9809 S.CheckShadowingDeclModification(E, Loc); 9810 9811 SourceLocation OrigLoc = Loc; 9812 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9813 &Loc); 9814 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9815 IsLV = Expr::MLV_InvalidMessageExpression; 9816 if (IsLV == Expr::MLV_Valid) 9817 return false; 9818 9819 unsigned DiagID = 0; 9820 bool NeedType = false; 9821 switch (IsLV) { // C99 6.5.16p2 9822 case Expr::MLV_ConstQualified: 9823 // Use a specialized diagnostic when we're assigning to an object 9824 // from an enclosing function or block. 9825 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9826 if (NCCK == NCCK_Block) 9827 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9828 else 9829 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9830 break; 9831 } 9832 9833 // In ARC, use some specialized diagnostics for occasions where we 9834 // infer 'const'. These are always pseudo-strong variables. 9835 if (S.getLangOpts().ObjCAutoRefCount) { 9836 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9837 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9838 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9839 9840 // Use the normal diagnostic if it's pseudo-__strong but the 9841 // user actually wrote 'const'. 9842 if (var->isARCPseudoStrong() && 9843 (!var->getTypeSourceInfo() || 9844 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9845 // There are two pseudo-strong cases: 9846 // - self 9847 ObjCMethodDecl *method = S.getCurMethodDecl(); 9848 if (method && var == method->getSelfDecl()) 9849 DiagID = method->isClassMethod() 9850 ? diag::err_typecheck_arc_assign_self_class_method 9851 : diag::err_typecheck_arc_assign_self; 9852 9853 // - fast enumeration variables 9854 else 9855 DiagID = diag::err_typecheck_arr_assign_enumeration; 9856 9857 SourceRange Assign; 9858 if (Loc != OrigLoc) 9859 Assign = SourceRange(OrigLoc, OrigLoc); 9860 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9861 // We need to preserve the AST regardless, so migration tool 9862 // can do its job. 9863 return false; 9864 } 9865 } 9866 } 9867 9868 // If none of the special cases above are triggered, then this is a 9869 // simple const assignment. 9870 if (DiagID == 0) { 9871 DiagnoseConstAssignment(S, E, Loc); 9872 return true; 9873 } 9874 9875 break; 9876 case Expr::MLV_ConstAddrSpace: 9877 DiagnoseConstAssignment(S, E, Loc); 9878 return true; 9879 case Expr::MLV_ArrayType: 9880 case Expr::MLV_ArrayTemporary: 9881 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9882 NeedType = true; 9883 break; 9884 case Expr::MLV_NotObjectType: 9885 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9886 NeedType = true; 9887 break; 9888 case Expr::MLV_LValueCast: 9889 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9890 break; 9891 case Expr::MLV_Valid: 9892 llvm_unreachable("did not take early return for MLV_Valid"); 9893 case Expr::MLV_InvalidExpression: 9894 case Expr::MLV_MemberFunction: 9895 case Expr::MLV_ClassTemporary: 9896 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9897 break; 9898 case Expr::MLV_IncompleteType: 9899 case Expr::MLV_IncompleteVoidType: 9900 return S.RequireCompleteType(Loc, E->getType(), 9901 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9902 case Expr::MLV_DuplicateVectorComponents: 9903 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9904 break; 9905 case Expr::MLV_NoSetterProperty: 9906 llvm_unreachable("readonly properties should be processed differently"); 9907 case Expr::MLV_InvalidMessageExpression: 9908 DiagID = diag::error_readonly_message_assignment; 9909 break; 9910 case Expr::MLV_SubObjCPropertySetting: 9911 DiagID = diag::error_no_subobject_property_setting; 9912 break; 9913 } 9914 9915 SourceRange Assign; 9916 if (Loc != OrigLoc) 9917 Assign = SourceRange(OrigLoc, OrigLoc); 9918 if (NeedType) 9919 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9920 else 9921 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9922 return true; 9923 } 9924 9925 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9926 SourceLocation Loc, 9927 Sema &Sema) { 9928 // C / C++ fields 9929 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9930 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9931 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9932 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9933 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9934 } 9935 9936 // Objective-C instance variables 9937 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9938 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9939 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9940 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9941 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9942 if (RL && RR && RL->getDecl() == RR->getDecl()) 9943 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9944 } 9945 } 9946 9947 // C99 6.5.16.1 9948 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9949 SourceLocation Loc, 9950 QualType CompoundType) { 9951 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9952 9953 // Verify that LHS is a modifiable lvalue, and emit error if not. 9954 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9955 return QualType(); 9956 9957 QualType LHSType = LHSExpr->getType(); 9958 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9959 CompoundType; 9960 AssignConvertType ConvTy; 9961 if (CompoundType.isNull()) { 9962 Expr *RHSCheck = RHS.get(); 9963 9964 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9965 9966 QualType LHSTy(LHSType); 9967 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9968 if (RHS.isInvalid()) 9969 return QualType(); 9970 // Special case of NSObject attributes on c-style pointer types. 9971 if (ConvTy == IncompatiblePointer && 9972 ((Context.isObjCNSObjectType(LHSType) && 9973 RHSType->isObjCObjectPointerType()) || 9974 (Context.isObjCNSObjectType(RHSType) && 9975 LHSType->isObjCObjectPointerType()))) 9976 ConvTy = Compatible; 9977 9978 if (ConvTy == Compatible && 9979 LHSType->isObjCObjectType()) 9980 Diag(Loc, diag::err_objc_object_assignment) 9981 << LHSType; 9982 9983 // If the RHS is a unary plus or minus, check to see if they = and + are 9984 // right next to each other. If so, the user may have typo'd "x =+ 4" 9985 // instead of "x += 4". 9986 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9987 RHSCheck = ICE->getSubExpr(); 9988 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9989 if ((UO->getOpcode() == UO_Plus || 9990 UO->getOpcode() == UO_Minus) && 9991 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9992 // Only if the two operators are exactly adjacent. 9993 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9994 // And there is a space or other character before the subexpr of the 9995 // unary +/-. We don't want to warn on "x=-1". 9996 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9997 UO->getSubExpr()->getLocStart().isFileID()) { 9998 Diag(Loc, diag::warn_not_compound_assign) 9999 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10000 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10001 } 10002 } 10003 10004 if (ConvTy == Compatible) { 10005 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10006 // Warn about retain cycles where a block captures the LHS, but 10007 // not if the LHS is a simple variable into which the block is 10008 // being stored...unless that variable can be captured by reference! 10009 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10010 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10011 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10012 checkRetainCycles(LHSExpr, RHS.get()); 10013 10014 // It is safe to assign a weak reference into a strong variable. 10015 // Although this code can still have problems: 10016 // id x = self.weakProp; 10017 // id y = self.weakProp; 10018 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10019 // paths through the function. This should be revisited if 10020 // -Wrepeated-use-of-weak is made flow-sensitive. 10021 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10022 RHS.get()->getLocStart())) 10023 getCurFunction()->markSafeWeakUse(RHS.get()); 10024 10025 } else if (getLangOpts().ObjCAutoRefCount) { 10026 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10027 } 10028 } 10029 } else { 10030 // Compound assignment "x += y" 10031 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10032 } 10033 10034 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10035 RHS.get(), AA_Assigning)) 10036 return QualType(); 10037 10038 CheckForNullPointerDereference(*this, LHSExpr); 10039 10040 // C99 6.5.16p3: The type of an assignment expression is the type of the 10041 // left operand unless the left operand has qualified type, in which case 10042 // it is the unqualified version of the type of the left operand. 10043 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10044 // is converted to the type of the assignment expression (above). 10045 // C++ 5.17p1: the type of the assignment expression is that of its left 10046 // operand. 10047 return (getLangOpts().CPlusPlus 10048 ? LHSType : LHSType.getUnqualifiedType()); 10049 } 10050 10051 // Only ignore explicit casts to void. 10052 static bool IgnoreCommaOperand(const Expr *E) { 10053 E = E->IgnoreParens(); 10054 10055 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10056 if (CE->getCastKind() == CK_ToVoid) { 10057 return true; 10058 } 10059 } 10060 10061 return false; 10062 } 10063 10064 // Look for instances where it is likely the comma operator is confused with 10065 // another operator. There is a whitelist of acceptable expressions for the 10066 // left hand side of the comma operator, otherwise emit a warning. 10067 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10068 // No warnings in macros 10069 if (Loc.isMacroID()) 10070 return; 10071 10072 // Don't warn in template instantiations. 10073 if (!ActiveTemplateInstantiations.empty()) 10074 return; 10075 10076 // Scope isn't fine-grained enough to whitelist the specific cases, so 10077 // instead, skip more than needed, then call back into here with the 10078 // CommaVisitor in SemaStmt.cpp. 10079 // The whitelisted locations are the initialization and increment portions 10080 // of a for loop. The additional checks are on the condition of 10081 // if statements, do/while loops, and for loops. 10082 const unsigned ForIncrementFlags = 10083 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10084 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10085 const unsigned ScopeFlags = getCurScope()->getFlags(); 10086 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10087 (ScopeFlags & ForInitFlags) == ForInitFlags) 10088 return; 10089 10090 // If there are multiple comma operators used together, get the RHS of the 10091 // of the comma operator as the LHS. 10092 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10093 if (BO->getOpcode() != BO_Comma) 10094 break; 10095 LHS = BO->getRHS(); 10096 } 10097 10098 // Only allow some expressions on LHS to not warn. 10099 if (IgnoreCommaOperand(LHS)) 10100 return; 10101 10102 Diag(Loc, diag::warn_comma_operator); 10103 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10104 << LHS->getSourceRange() 10105 << FixItHint::CreateInsertion(LHS->getLocStart(), 10106 LangOpts.CPlusPlus ? "static_cast<void>(" 10107 : "(void)(") 10108 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10109 ")"); 10110 } 10111 10112 // C99 6.5.17 10113 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10114 SourceLocation Loc) { 10115 LHS = S.CheckPlaceholderExpr(LHS.get()); 10116 RHS = S.CheckPlaceholderExpr(RHS.get()); 10117 if (LHS.isInvalid() || RHS.isInvalid()) 10118 return QualType(); 10119 10120 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10121 // operands, but not unary promotions. 10122 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10123 10124 // So we treat the LHS as a ignored value, and in C++ we allow the 10125 // containing site to determine what should be done with the RHS. 10126 LHS = S.IgnoredValueConversions(LHS.get()); 10127 if (LHS.isInvalid()) 10128 return QualType(); 10129 10130 S.DiagnoseUnusedExprResult(LHS.get()); 10131 10132 if (!S.getLangOpts().CPlusPlus) { 10133 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10134 if (RHS.isInvalid()) 10135 return QualType(); 10136 if (!RHS.get()->getType()->isVoidType()) 10137 S.RequireCompleteType(Loc, RHS.get()->getType(), 10138 diag::err_incomplete_type); 10139 } 10140 10141 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10142 S.DiagnoseCommaOperator(LHS.get(), Loc); 10143 10144 return RHS.get()->getType(); 10145 } 10146 10147 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10148 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10149 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10150 ExprValueKind &VK, 10151 ExprObjectKind &OK, 10152 SourceLocation OpLoc, 10153 bool IsInc, bool IsPrefix) { 10154 if (Op->isTypeDependent()) 10155 return S.Context.DependentTy; 10156 10157 QualType ResType = Op->getType(); 10158 // Atomic types can be used for increment / decrement where the non-atomic 10159 // versions can, so ignore the _Atomic() specifier for the purpose of 10160 // checking. 10161 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10162 ResType = ResAtomicType->getValueType(); 10163 10164 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10165 10166 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10167 // Decrement of bool is not allowed. 10168 if (!IsInc) { 10169 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10170 return QualType(); 10171 } 10172 // Increment of bool sets it to true, but is deprecated. 10173 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10174 : diag::warn_increment_bool) 10175 << Op->getSourceRange(); 10176 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10177 // Error on enum increments and decrements in C++ mode 10178 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10179 return QualType(); 10180 } else if (ResType->isRealType()) { 10181 // OK! 10182 } else if (ResType->isPointerType()) { 10183 // C99 6.5.2.4p2, 6.5.6p2 10184 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10185 return QualType(); 10186 } else if (ResType->isObjCObjectPointerType()) { 10187 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10188 // Otherwise, we just need a complete type. 10189 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10190 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10191 return QualType(); 10192 } else if (ResType->isAnyComplexType()) { 10193 // C99 does not support ++/-- on complex types, we allow as an extension. 10194 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10195 << ResType << Op->getSourceRange(); 10196 } else if (ResType->isPlaceholderType()) { 10197 ExprResult PR = S.CheckPlaceholderExpr(Op); 10198 if (PR.isInvalid()) return QualType(); 10199 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10200 IsInc, IsPrefix); 10201 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10202 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10203 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10204 (ResType->getAs<VectorType>()->getVectorKind() != 10205 VectorType::AltiVecBool)) { 10206 // The z vector extensions allow ++ and -- for non-bool vectors. 10207 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10208 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10209 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10210 } else { 10211 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10212 << ResType << int(IsInc) << Op->getSourceRange(); 10213 return QualType(); 10214 } 10215 // At this point, we know we have a real, complex or pointer type. 10216 // Now make sure the operand is a modifiable lvalue. 10217 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10218 return QualType(); 10219 // In C++, a prefix increment is the same type as the operand. Otherwise 10220 // (in C or with postfix), the increment is the unqualified type of the 10221 // operand. 10222 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10223 VK = VK_LValue; 10224 OK = Op->getObjectKind(); 10225 return ResType; 10226 } else { 10227 VK = VK_RValue; 10228 return ResType.getUnqualifiedType(); 10229 } 10230 } 10231 10232 10233 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10234 /// This routine allows us to typecheck complex/recursive expressions 10235 /// where the declaration is needed for type checking. We only need to 10236 /// handle cases when the expression references a function designator 10237 /// or is an lvalue. Here are some examples: 10238 /// - &(x) => x 10239 /// - &*****f => f for f a function designator. 10240 /// - &s.xx => s 10241 /// - &s.zz[1].yy -> s, if zz is an array 10242 /// - *(x + 1) -> x, if x is an array 10243 /// - &"123"[2] -> 0 10244 /// - & __real__ x -> x 10245 static ValueDecl *getPrimaryDecl(Expr *E) { 10246 switch (E->getStmtClass()) { 10247 case Stmt::DeclRefExprClass: 10248 return cast<DeclRefExpr>(E)->getDecl(); 10249 case Stmt::MemberExprClass: 10250 // If this is an arrow operator, the address is an offset from 10251 // the base's value, so the object the base refers to is 10252 // irrelevant. 10253 if (cast<MemberExpr>(E)->isArrow()) 10254 return nullptr; 10255 // Otherwise, the expression refers to a part of the base 10256 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10257 case Stmt::ArraySubscriptExprClass: { 10258 // FIXME: This code shouldn't be necessary! We should catch the implicit 10259 // promotion of register arrays earlier. 10260 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10261 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10262 if (ICE->getSubExpr()->getType()->isArrayType()) 10263 return getPrimaryDecl(ICE->getSubExpr()); 10264 } 10265 return nullptr; 10266 } 10267 case Stmt::UnaryOperatorClass: { 10268 UnaryOperator *UO = cast<UnaryOperator>(E); 10269 10270 switch(UO->getOpcode()) { 10271 case UO_Real: 10272 case UO_Imag: 10273 case UO_Extension: 10274 return getPrimaryDecl(UO->getSubExpr()); 10275 default: 10276 return nullptr; 10277 } 10278 } 10279 case Stmt::ParenExprClass: 10280 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10281 case Stmt::ImplicitCastExprClass: 10282 // If the result of an implicit cast is an l-value, we care about 10283 // the sub-expression; otherwise, the result here doesn't matter. 10284 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10285 default: 10286 return nullptr; 10287 } 10288 } 10289 10290 namespace { 10291 enum { 10292 AO_Bit_Field = 0, 10293 AO_Vector_Element = 1, 10294 AO_Property_Expansion = 2, 10295 AO_Register_Variable = 3, 10296 AO_No_Error = 4 10297 }; 10298 } 10299 /// \brief Diagnose invalid operand for address of operations. 10300 /// 10301 /// \param Type The type of operand which cannot have its address taken. 10302 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10303 Expr *E, unsigned Type) { 10304 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10305 } 10306 10307 /// CheckAddressOfOperand - The operand of & must be either a function 10308 /// designator or an lvalue designating an object. If it is an lvalue, the 10309 /// object cannot be declared with storage class register or be a bit field. 10310 /// Note: The usual conversions are *not* applied to the operand of the & 10311 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10312 /// In C++, the operand might be an overloaded function name, in which case 10313 /// we allow the '&' but retain the overloaded-function type. 10314 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10315 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10316 if (PTy->getKind() == BuiltinType::Overload) { 10317 Expr *E = OrigOp.get()->IgnoreParens(); 10318 if (!isa<OverloadExpr>(E)) { 10319 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10320 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10321 << OrigOp.get()->getSourceRange(); 10322 return QualType(); 10323 } 10324 10325 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10326 if (isa<UnresolvedMemberExpr>(Ovl)) 10327 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10328 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10329 << OrigOp.get()->getSourceRange(); 10330 return QualType(); 10331 } 10332 10333 return Context.OverloadTy; 10334 } 10335 10336 if (PTy->getKind() == BuiltinType::UnknownAny) 10337 return Context.UnknownAnyTy; 10338 10339 if (PTy->getKind() == BuiltinType::BoundMember) { 10340 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10341 << OrigOp.get()->getSourceRange(); 10342 return QualType(); 10343 } 10344 10345 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10346 if (OrigOp.isInvalid()) return QualType(); 10347 } 10348 10349 if (OrigOp.get()->isTypeDependent()) 10350 return Context.DependentTy; 10351 10352 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10353 10354 // Make sure to ignore parentheses in subsequent checks 10355 Expr *op = OrigOp.get()->IgnoreParens(); 10356 10357 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10358 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10359 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10360 return QualType(); 10361 } 10362 10363 if (getLangOpts().C99) { 10364 // Implement C99-only parts of addressof rules. 10365 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10366 if (uOp->getOpcode() == UO_Deref) 10367 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10368 // (assuming the deref expression is valid). 10369 return uOp->getSubExpr()->getType(); 10370 } 10371 // Technically, there should be a check for array subscript 10372 // expressions here, but the result of one is always an lvalue anyway. 10373 } 10374 ValueDecl *dcl = getPrimaryDecl(op); 10375 10376 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10377 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10378 op->getLocStart())) 10379 return QualType(); 10380 10381 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10382 unsigned AddressOfError = AO_No_Error; 10383 10384 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10385 bool sfinae = (bool)isSFINAEContext(); 10386 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10387 : diag::ext_typecheck_addrof_temporary) 10388 << op->getType() << op->getSourceRange(); 10389 if (sfinae) 10390 return QualType(); 10391 // Materialize the temporary as an lvalue so that we can take its address. 10392 OrigOp = op = new (Context) 10393 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10394 } else if (isa<ObjCSelectorExpr>(op)) { 10395 return Context.getPointerType(op->getType()); 10396 } else if (lval == Expr::LV_MemberFunction) { 10397 // If it's an instance method, make a member pointer. 10398 // The expression must have exactly the form &A::foo. 10399 10400 // If the underlying expression isn't a decl ref, give up. 10401 if (!isa<DeclRefExpr>(op)) { 10402 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10403 << OrigOp.get()->getSourceRange(); 10404 return QualType(); 10405 } 10406 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10407 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10408 10409 // The id-expression was parenthesized. 10410 if (OrigOp.get() != DRE) { 10411 Diag(OpLoc, diag::err_parens_pointer_member_function) 10412 << OrigOp.get()->getSourceRange(); 10413 10414 // The method was named without a qualifier. 10415 } else if (!DRE->getQualifier()) { 10416 if (MD->getParent()->getName().empty()) 10417 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10418 << op->getSourceRange(); 10419 else { 10420 SmallString<32> Str; 10421 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10422 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10423 << op->getSourceRange() 10424 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10425 } 10426 } 10427 10428 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10429 if (isa<CXXDestructorDecl>(MD)) 10430 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10431 10432 QualType MPTy = Context.getMemberPointerType( 10433 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10434 // Under the MS ABI, lock down the inheritance model now. 10435 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10436 (void)isCompleteType(OpLoc, MPTy); 10437 return MPTy; 10438 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10439 // C99 6.5.3.2p1 10440 // The operand must be either an l-value or a function designator 10441 if (!op->getType()->isFunctionType()) { 10442 // Use a special diagnostic for loads from property references. 10443 if (isa<PseudoObjectExpr>(op)) { 10444 AddressOfError = AO_Property_Expansion; 10445 } else { 10446 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10447 << op->getType() << op->getSourceRange(); 10448 return QualType(); 10449 } 10450 } 10451 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10452 // The operand cannot be a bit-field 10453 AddressOfError = AO_Bit_Field; 10454 } else if (op->getObjectKind() == OK_VectorComponent) { 10455 // The operand cannot be an element of a vector 10456 AddressOfError = AO_Vector_Element; 10457 } else if (dcl) { // C99 6.5.3.2p1 10458 // We have an lvalue with a decl. Make sure the decl is not declared 10459 // with the register storage-class specifier. 10460 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10461 // in C++ it is not error to take address of a register 10462 // variable (c++03 7.1.1P3) 10463 if (vd->getStorageClass() == SC_Register && 10464 !getLangOpts().CPlusPlus) { 10465 AddressOfError = AO_Register_Variable; 10466 } 10467 } else if (isa<MSPropertyDecl>(dcl)) { 10468 AddressOfError = AO_Property_Expansion; 10469 } else if (isa<FunctionTemplateDecl>(dcl)) { 10470 return Context.OverloadTy; 10471 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10472 // Okay: we can take the address of a field. 10473 // Could be a pointer to member, though, if there is an explicit 10474 // scope qualifier for the class. 10475 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10476 DeclContext *Ctx = dcl->getDeclContext(); 10477 if (Ctx && Ctx->isRecord()) { 10478 if (dcl->getType()->isReferenceType()) { 10479 Diag(OpLoc, 10480 diag::err_cannot_form_pointer_to_member_of_reference_type) 10481 << dcl->getDeclName() << dcl->getType(); 10482 return QualType(); 10483 } 10484 10485 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10486 Ctx = Ctx->getParent(); 10487 10488 QualType MPTy = Context.getMemberPointerType( 10489 op->getType(), 10490 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10491 // Under the MS ABI, lock down the inheritance model now. 10492 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10493 (void)isCompleteType(OpLoc, MPTy); 10494 return MPTy; 10495 } 10496 } 10497 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10498 llvm_unreachable("Unknown/unexpected decl type"); 10499 } 10500 10501 if (AddressOfError != AO_No_Error) { 10502 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10503 return QualType(); 10504 } 10505 10506 if (lval == Expr::LV_IncompleteVoidType) { 10507 // Taking the address of a void variable is technically illegal, but we 10508 // allow it in cases which are otherwise valid. 10509 // Example: "extern void x; void* y = &x;". 10510 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10511 } 10512 10513 // If the operand has type "type", the result has type "pointer to type". 10514 if (op->getType()->isObjCObjectType()) 10515 return Context.getObjCObjectPointerType(op->getType()); 10516 10517 // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block. 10518 if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) { 10519 Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType() 10520 << op->getSourceRange(); 10521 return QualType(); 10522 } 10523 10524 return Context.getPointerType(op->getType()); 10525 } 10526 10527 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10528 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10529 if (!DRE) 10530 return; 10531 const Decl *D = DRE->getDecl(); 10532 if (!D) 10533 return; 10534 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10535 if (!Param) 10536 return; 10537 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10538 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10539 return; 10540 if (FunctionScopeInfo *FD = S.getCurFunction()) 10541 if (!FD->ModifiedNonNullParams.count(Param)) 10542 FD->ModifiedNonNullParams.insert(Param); 10543 } 10544 10545 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10546 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10547 SourceLocation OpLoc) { 10548 if (Op->isTypeDependent()) 10549 return S.Context.DependentTy; 10550 10551 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10552 if (ConvResult.isInvalid()) 10553 return QualType(); 10554 Op = ConvResult.get(); 10555 QualType OpTy = Op->getType(); 10556 QualType Result; 10557 10558 if (isa<CXXReinterpretCastExpr>(Op)) { 10559 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10560 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10561 Op->getSourceRange()); 10562 } 10563 10564 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10565 { 10566 Result = PT->getPointeeType(); 10567 // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block. 10568 if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) { 10569 S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy 10570 << Op->getSourceRange(); 10571 return QualType(); 10572 } 10573 } 10574 else if (const ObjCObjectPointerType *OPT = 10575 OpTy->getAs<ObjCObjectPointerType>()) 10576 Result = OPT->getPointeeType(); 10577 else { 10578 ExprResult PR = S.CheckPlaceholderExpr(Op); 10579 if (PR.isInvalid()) return QualType(); 10580 if (PR.get() != Op) 10581 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10582 } 10583 10584 if (Result.isNull()) { 10585 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10586 << OpTy << Op->getSourceRange(); 10587 return QualType(); 10588 } 10589 10590 // Note that per both C89 and C99, indirection is always legal, even if Result 10591 // is an incomplete type or void. It would be possible to warn about 10592 // dereferencing a void pointer, but it's completely well-defined, and such a 10593 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10594 // for pointers to 'void' but is fine for any other pointer type: 10595 // 10596 // C++ [expr.unary.op]p1: 10597 // [...] the expression to which [the unary * operator] is applied shall 10598 // be a pointer to an object type, or a pointer to a function type 10599 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10600 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10601 << OpTy << Op->getSourceRange(); 10602 10603 // Dereferences are usually l-values... 10604 VK = VK_LValue; 10605 10606 // ...except that certain expressions are never l-values in C. 10607 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10608 VK = VK_RValue; 10609 10610 return Result; 10611 } 10612 10613 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10614 BinaryOperatorKind Opc; 10615 switch (Kind) { 10616 default: llvm_unreachable("Unknown binop!"); 10617 case tok::periodstar: Opc = BO_PtrMemD; break; 10618 case tok::arrowstar: Opc = BO_PtrMemI; break; 10619 case tok::star: Opc = BO_Mul; break; 10620 case tok::slash: Opc = BO_Div; break; 10621 case tok::percent: Opc = BO_Rem; break; 10622 case tok::plus: Opc = BO_Add; break; 10623 case tok::minus: Opc = BO_Sub; break; 10624 case tok::lessless: Opc = BO_Shl; break; 10625 case tok::greatergreater: Opc = BO_Shr; break; 10626 case tok::lessequal: Opc = BO_LE; break; 10627 case tok::less: Opc = BO_LT; break; 10628 case tok::greaterequal: Opc = BO_GE; break; 10629 case tok::greater: Opc = BO_GT; break; 10630 case tok::exclaimequal: Opc = BO_NE; break; 10631 case tok::equalequal: Opc = BO_EQ; break; 10632 case tok::amp: Opc = BO_And; break; 10633 case tok::caret: Opc = BO_Xor; break; 10634 case tok::pipe: Opc = BO_Or; break; 10635 case tok::ampamp: Opc = BO_LAnd; break; 10636 case tok::pipepipe: Opc = BO_LOr; break; 10637 case tok::equal: Opc = BO_Assign; break; 10638 case tok::starequal: Opc = BO_MulAssign; break; 10639 case tok::slashequal: Opc = BO_DivAssign; break; 10640 case tok::percentequal: Opc = BO_RemAssign; break; 10641 case tok::plusequal: Opc = BO_AddAssign; break; 10642 case tok::minusequal: Opc = BO_SubAssign; break; 10643 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10644 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10645 case tok::ampequal: Opc = BO_AndAssign; break; 10646 case tok::caretequal: Opc = BO_XorAssign; break; 10647 case tok::pipeequal: Opc = BO_OrAssign; break; 10648 case tok::comma: Opc = BO_Comma; break; 10649 } 10650 return Opc; 10651 } 10652 10653 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10654 tok::TokenKind Kind) { 10655 UnaryOperatorKind Opc; 10656 switch (Kind) { 10657 default: llvm_unreachable("Unknown unary op!"); 10658 case tok::plusplus: Opc = UO_PreInc; break; 10659 case tok::minusminus: Opc = UO_PreDec; break; 10660 case tok::amp: Opc = UO_AddrOf; break; 10661 case tok::star: Opc = UO_Deref; break; 10662 case tok::plus: Opc = UO_Plus; break; 10663 case tok::minus: Opc = UO_Minus; break; 10664 case tok::tilde: Opc = UO_Not; break; 10665 case tok::exclaim: Opc = UO_LNot; break; 10666 case tok::kw___real: Opc = UO_Real; break; 10667 case tok::kw___imag: Opc = UO_Imag; break; 10668 case tok::kw___extension__: Opc = UO_Extension; break; 10669 } 10670 return Opc; 10671 } 10672 10673 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10674 /// This warning is only emitted for builtin assignment operations. It is also 10675 /// suppressed in the event of macro expansions. 10676 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10677 SourceLocation OpLoc) { 10678 if (!S.ActiveTemplateInstantiations.empty()) 10679 return; 10680 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10681 return; 10682 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10683 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10684 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10685 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10686 if (!LHSDeclRef || !RHSDeclRef || 10687 LHSDeclRef->getLocation().isMacroID() || 10688 RHSDeclRef->getLocation().isMacroID()) 10689 return; 10690 const ValueDecl *LHSDecl = 10691 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10692 const ValueDecl *RHSDecl = 10693 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10694 if (LHSDecl != RHSDecl) 10695 return; 10696 if (LHSDecl->getType().isVolatileQualified()) 10697 return; 10698 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10699 if (RefTy->getPointeeType().isVolatileQualified()) 10700 return; 10701 10702 S.Diag(OpLoc, diag::warn_self_assignment) 10703 << LHSDeclRef->getType() 10704 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10705 } 10706 10707 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10708 /// is usually indicative of introspection within the Objective-C pointer. 10709 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10710 SourceLocation OpLoc) { 10711 if (!S.getLangOpts().ObjC1) 10712 return; 10713 10714 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10715 const Expr *LHS = L.get(); 10716 const Expr *RHS = R.get(); 10717 10718 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10719 ObjCPointerExpr = LHS; 10720 OtherExpr = RHS; 10721 } 10722 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10723 ObjCPointerExpr = RHS; 10724 OtherExpr = LHS; 10725 } 10726 10727 // This warning is deliberately made very specific to reduce false 10728 // positives with logic that uses '&' for hashing. This logic mainly 10729 // looks for code trying to introspect into tagged pointers, which 10730 // code should generally never do. 10731 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10732 unsigned Diag = diag::warn_objc_pointer_masking; 10733 // Determine if we are introspecting the result of performSelectorXXX. 10734 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10735 // Special case messages to -performSelector and friends, which 10736 // can return non-pointer values boxed in a pointer value. 10737 // Some clients may wish to silence warnings in this subcase. 10738 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10739 Selector S = ME->getSelector(); 10740 StringRef SelArg0 = S.getNameForSlot(0); 10741 if (SelArg0.startswith("performSelector")) 10742 Diag = diag::warn_objc_pointer_masking_performSelector; 10743 } 10744 10745 S.Diag(OpLoc, Diag) 10746 << ObjCPointerExpr->getSourceRange(); 10747 } 10748 } 10749 10750 static NamedDecl *getDeclFromExpr(Expr *E) { 10751 if (!E) 10752 return nullptr; 10753 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10754 return DRE->getDecl(); 10755 if (auto *ME = dyn_cast<MemberExpr>(E)) 10756 return ME->getMemberDecl(); 10757 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10758 return IRE->getDecl(); 10759 return nullptr; 10760 } 10761 10762 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10763 /// operator @p Opc at location @c TokLoc. This routine only supports 10764 /// built-in operations; ActOnBinOp handles overloaded operators. 10765 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10766 BinaryOperatorKind Opc, 10767 Expr *LHSExpr, Expr *RHSExpr) { 10768 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10769 // The syntax only allows initializer lists on the RHS of assignment, 10770 // so we don't need to worry about accepting invalid code for 10771 // non-assignment operators. 10772 // C++11 5.17p9: 10773 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10774 // of x = {} is x = T(). 10775 InitializationKind Kind = 10776 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10777 InitializedEntity Entity = 10778 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10779 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10780 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10781 if (Init.isInvalid()) 10782 return Init; 10783 RHSExpr = Init.get(); 10784 } 10785 10786 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10787 QualType ResultTy; // Result type of the binary operator. 10788 // The following two variables are used for compound assignment operators 10789 QualType CompLHSTy; // Type of LHS after promotions for computation 10790 QualType CompResultTy; // Type of computation result 10791 ExprValueKind VK = VK_RValue; 10792 ExprObjectKind OK = OK_Ordinary; 10793 10794 if (!getLangOpts().CPlusPlus) { 10795 // C cannot handle TypoExpr nodes on either side of a binop because it 10796 // doesn't handle dependent types properly, so make sure any TypoExprs have 10797 // been dealt with before checking the operands. 10798 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10799 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10800 if (Opc != BO_Assign) 10801 return ExprResult(E); 10802 // Avoid correcting the RHS to the same Expr as the LHS. 10803 Decl *D = getDeclFromExpr(E); 10804 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10805 }); 10806 if (!LHS.isUsable() || !RHS.isUsable()) 10807 return ExprError(); 10808 } 10809 10810 if (getLangOpts().OpenCL) { 10811 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10812 // the ATOMIC_VAR_INIT macro. 10813 if (LHSExpr->getType()->isAtomicType() || 10814 RHSExpr->getType()->isAtomicType()) { 10815 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10816 if (BO_Assign == Opc) 10817 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10818 else 10819 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10820 return ExprError(); 10821 } 10822 } 10823 10824 switch (Opc) { 10825 case BO_Assign: 10826 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10827 if (getLangOpts().CPlusPlus && 10828 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10829 VK = LHS.get()->getValueKind(); 10830 OK = LHS.get()->getObjectKind(); 10831 } 10832 if (!ResultTy.isNull()) { 10833 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10834 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10835 } 10836 RecordModifiableNonNullParam(*this, LHS.get()); 10837 break; 10838 case BO_PtrMemD: 10839 case BO_PtrMemI: 10840 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10841 Opc == BO_PtrMemI); 10842 break; 10843 case BO_Mul: 10844 case BO_Div: 10845 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10846 Opc == BO_Div); 10847 break; 10848 case BO_Rem: 10849 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10850 break; 10851 case BO_Add: 10852 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10853 break; 10854 case BO_Sub: 10855 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10856 break; 10857 case BO_Shl: 10858 case BO_Shr: 10859 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10860 break; 10861 case BO_LE: 10862 case BO_LT: 10863 case BO_GE: 10864 case BO_GT: 10865 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10866 break; 10867 case BO_EQ: 10868 case BO_NE: 10869 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10870 break; 10871 case BO_And: 10872 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10873 case BO_Xor: 10874 case BO_Or: 10875 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10876 break; 10877 case BO_LAnd: 10878 case BO_LOr: 10879 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10880 break; 10881 case BO_MulAssign: 10882 case BO_DivAssign: 10883 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10884 Opc == BO_DivAssign); 10885 CompLHSTy = CompResultTy; 10886 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10887 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10888 break; 10889 case BO_RemAssign: 10890 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10891 CompLHSTy = CompResultTy; 10892 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10893 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10894 break; 10895 case BO_AddAssign: 10896 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10897 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10898 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10899 break; 10900 case BO_SubAssign: 10901 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10902 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10904 break; 10905 case BO_ShlAssign: 10906 case BO_ShrAssign: 10907 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10908 CompLHSTy = CompResultTy; 10909 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10910 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10911 break; 10912 case BO_AndAssign: 10913 case BO_OrAssign: // fallthrough 10914 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10915 case BO_XorAssign: 10916 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10917 CompLHSTy = CompResultTy; 10918 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10919 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10920 break; 10921 case BO_Comma: 10922 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10923 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10924 VK = RHS.get()->getValueKind(); 10925 OK = RHS.get()->getObjectKind(); 10926 } 10927 break; 10928 } 10929 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10930 return ExprError(); 10931 10932 // Check for array bounds violations for both sides of the BinaryOperator 10933 CheckArrayAccess(LHS.get()); 10934 CheckArrayAccess(RHS.get()); 10935 10936 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10937 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10938 &Context.Idents.get("object_setClass"), 10939 SourceLocation(), LookupOrdinaryName); 10940 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10941 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10942 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10943 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10944 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10945 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10946 } 10947 else 10948 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10949 } 10950 else if (const ObjCIvarRefExpr *OIRE = 10951 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10952 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10953 10954 if (CompResultTy.isNull()) 10955 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10956 OK, OpLoc, FPFeatures.fp_contract); 10957 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10958 OK_ObjCProperty) { 10959 VK = VK_LValue; 10960 OK = LHS.get()->getObjectKind(); 10961 } 10962 return new (Context) CompoundAssignOperator( 10963 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10964 OpLoc, FPFeatures.fp_contract); 10965 } 10966 10967 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10968 /// operators are mixed in a way that suggests that the programmer forgot that 10969 /// comparison operators have higher precedence. The most typical example of 10970 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10971 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10972 SourceLocation OpLoc, Expr *LHSExpr, 10973 Expr *RHSExpr) { 10974 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10975 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10976 10977 // Check that one of the sides is a comparison operator and the other isn't. 10978 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10979 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10980 if (isLeftComp == isRightComp) 10981 return; 10982 10983 // Bitwise operations are sometimes used as eager logical ops. 10984 // Don't diagnose this. 10985 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10986 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10987 if (isLeftBitwise || isRightBitwise) 10988 return; 10989 10990 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10991 OpLoc) 10992 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10993 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10994 SourceRange ParensRange = isLeftComp ? 10995 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10996 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10997 10998 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10999 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11000 SuggestParentheses(Self, OpLoc, 11001 Self.PDiag(diag::note_precedence_silence) << OpStr, 11002 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11003 SuggestParentheses(Self, OpLoc, 11004 Self.PDiag(diag::note_precedence_bitwise_first) 11005 << BinaryOperator::getOpcodeStr(Opc), 11006 ParensRange); 11007 } 11008 11009 /// \brief It accepts a '&&' expr that is inside a '||' one. 11010 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11011 /// in parentheses. 11012 static void 11013 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11014 BinaryOperator *Bop) { 11015 assert(Bop->getOpcode() == BO_LAnd); 11016 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11017 << Bop->getSourceRange() << OpLoc; 11018 SuggestParentheses(Self, Bop->getOperatorLoc(), 11019 Self.PDiag(diag::note_precedence_silence) 11020 << Bop->getOpcodeStr(), 11021 Bop->getSourceRange()); 11022 } 11023 11024 /// \brief Returns true if the given expression can be evaluated as a constant 11025 /// 'true'. 11026 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11027 bool Res; 11028 return !E->isValueDependent() && 11029 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11030 } 11031 11032 /// \brief Returns true if the given expression can be evaluated as a constant 11033 /// 'false'. 11034 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11035 bool Res; 11036 return !E->isValueDependent() && 11037 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11038 } 11039 11040 /// \brief Look for '&&' in the left hand of a '||' expr. 11041 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11042 Expr *LHSExpr, Expr *RHSExpr) { 11043 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11044 if (Bop->getOpcode() == BO_LAnd) { 11045 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11046 if (EvaluatesAsFalse(S, RHSExpr)) 11047 return; 11048 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11049 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11050 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11051 } else if (Bop->getOpcode() == BO_LOr) { 11052 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11053 // If it's "a || b && 1 || c" we didn't warn earlier for 11054 // "a || b && 1", but warn now. 11055 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11056 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11057 } 11058 } 11059 } 11060 } 11061 11062 /// \brief Look for '&&' in the right hand of a '||' expr. 11063 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11064 Expr *LHSExpr, Expr *RHSExpr) { 11065 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11066 if (Bop->getOpcode() == BO_LAnd) { 11067 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11068 if (EvaluatesAsFalse(S, LHSExpr)) 11069 return; 11070 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11071 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11072 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11073 } 11074 } 11075 } 11076 11077 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11078 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11079 /// the '&' expression in parentheses. 11080 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11081 SourceLocation OpLoc, Expr *SubExpr) { 11082 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11083 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11084 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11085 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11086 << Bop->getSourceRange() << OpLoc; 11087 SuggestParentheses(S, Bop->getOperatorLoc(), 11088 S.PDiag(diag::note_precedence_silence) 11089 << Bop->getOpcodeStr(), 11090 Bop->getSourceRange()); 11091 } 11092 } 11093 } 11094 11095 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11096 Expr *SubExpr, StringRef Shift) { 11097 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11098 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11099 StringRef Op = Bop->getOpcodeStr(); 11100 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11101 << Bop->getSourceRange() << OpLoc << Shift << Op; 11102 SuggestParentheses(S, Bop->getOperatorLoc(), 11103 S.PDiag(diag::note_precedence_silence) << Op, 11104 Bop->getSourceRange()); 11105 } 11106 } 11107 } 11108 11109 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11110 Expr *LHSExpr, Expr *RHSExpr) { 11111 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11112 if (!OCE) 11113 return; 11114 11115 FunctionDecl *FD = OCE->getDirectCallee(); 11116 if (!FD || !FD->isOverloadedOperator()) 11117 return; 11118 11119 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11120 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11121 return; 11122 11123 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11124 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11125 << (Kind == OO_LessLess); 11126 SuggestParentheses(S, OCE->getOperatorLoc(), 11127 S.PDiag(diag::note_precedence_silence) 11128 << (Kind == OO_LessLess ? "<<" : ">>"), 11129 OCE->getSourceRange()); 11130 SuggestParentheses(S, OpLoc, 11131 S.PDiag(diag::note_evaluate_comparison_first), 11132 SourceRange(OCE->getArg(1)->getLocStart(), 11133 RHSExpr->getLocEnd())); 11134 } 11135 11136 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11137 /// precedence. 11138 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11139 SourceLocation OpLoc, Expr *LHSExpr, 11140 Expr *RHSExpr){ 11141 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11142 if (BinaryOperator::isBitwiseOp(Opc)) 11143 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11144 11145 // Diagnose "arg1 & arg2 | arg3" 11146 if ((Opc == BO_Or || Opc == BO_Xor) && 11147 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11148 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11149 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11150 } 11151 11152 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11153 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11154 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11155 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11156 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11157 } 11158 11159 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11160 || Opc == BO_Shr) { 11161 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11162 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11163 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11164 } 11165 11166 // Warn on overloaded shift operators and comparisons, such as: 11167 // cout << 5 == 4; 11168 if (BinaryOperator::isComparisonOp(Opc)) 11169 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11170 } 11171 11172 // Binary Operators. 'Tok' is the token for the operator. 11173 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11174 tok::TokenKind Kind, 11175 Expr *LHSExpr, Expr *RHSExpr) { 11176 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11177 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11178 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11179 11180 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11181 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11182 11183 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11184 } 11185 11186 /// Build an overloaded binary operator expression in the given scope. 11187 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11188 BinaryOperatorKind Opc, 11189 Expr *LHS, Expr *RHS) { 11190 // Find all of the overloaded operators visible from this 11191 // point. We perform both an operator-name lookup from the local 11192 // scope and an argument-dependent lookup based on the types of 11193 // the arguments. 11194 UnresolvedSet<16> Functions; 11195 OverloadedOperatorKind OverOp 11196 = BinaryOperator::getOverloadedOperator(Opc); 11197 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11198 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11199 RHS->getType(), Functions); 11200 11201 // Build the (potentially-overloaded, potentially-dependent) 11202 // binary operation. 11203 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11204 } 11205 11206 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11207 BinaryOperatorKind Opc, 11208 Expr *LHSExpr, Expr *RHSExpr) { 11209 // We want to end up calling one of checkPseudoObjectAssignment 11210 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11211 // both expressions are overloadable or either is type-dependent), 11212 // or CreateBuiltinBinOp (in any other case). We also want to get 11213 // any placeholder types out of the way. 11214 11215 // Handle pseudo-objects in the LHS. 11216 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11217 // Assignments with a pseudo-object l-value need special analysis. 11218 if (pty->getKind() == BuiltinType::PseudoObject && 11219 BinaryOperator::isAssignmentOp(Opc)) 11220 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11221 11222 // Don't resolve overloads if the other type is overloadable. 11223 if (pty->getKind() == BuiltinType::Overload) { 11224 // We can't actually test that if we still have a placeholder, 11225 // though. Fortunately, none of the exceptions we see in that 11226 // code below are valid when the LHS is an overload set. Note 11227 // that an overload set can be dependently-typed, but it never 11228 // instantiates to having an overloadable type. 11229 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11230 if (resolvedRHS.isInvalid()) return ExprError(); 11231 RHSExpr = resolvedRHS.get(); 11232 11233 if (RHSExpr->isTypeDependent() || 11234 RHSExpr->getType()->isOverloadableType()) 11235 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11236 } 11237 11238 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11239 if (LHS.isInvalid()) return ExprError(); 11240 LHSExpr = LHS.get(); 11241 } 11242 11243 // Handle pseudo-objects in the RHS. 11244 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11245 // An overload in the RHS can potentially be resolved by the type 11246 // being assigned to. 11247 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11248 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11249 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11250 11251 if (LHSExpr->getType()->isOverloadableType()) 11252 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11253 11254 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11255 } 11256 11257 // Don't resolve overloads if the other type is overloadable. 11258 if (pty->getKind() == BuiltinType::Overload && 11259 LHSExpr->getType()->isOverloadableType()) 11260 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11261 11262 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11263 if (!resolvedRHS.isUsable()) return ExprError(); 11264 RHSExpr = resolvedRHS.get(); 11265 } 11266 11267 if (getLangOpts().CPlusPlus) { 11268 // If either expression is type-dependent, always build an 11269 // overloaded op. 11270 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11271 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11272 11273 // Otherwise, build an overloaded op if either expression has an 11274 // overloadable type. 11275 if (LHSExpr->getType()->isOverloadableType() || 11276 RHSExpr->getType()->isOverloadableType()) 11277 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11278 } 11279 11280 // Build a built-in binary operation. 11281 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11282 } 11283 11284 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11285 UnaryOperatorKind Opc, 11286 Expr *InputExpr) { 11287 ExprResult Input = InputExpr; 11288 ExprValueKind VK = VK_RValue; 11289 ExprObjectKind OK = OK_Ordinary; 11290 QualType resultType; 11291 if (getLangOpts().OpenCL) { 11292 // The only legal unary operation for atomics is '&'. 11293 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 11294 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11295 << InputExpr->getType() 11296 << Input.get()->getSourceRange()); 11297 } 11298 } 11299 switch (Opc) { 11300 case UO_PreInc: 11301 case UO_PreDec: 11302 case UO_PostInc: 11303 case UO_PostDec: 11304 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11305 OpLoc, 11306 Opc == UO_PreInc || 11307 Opc == UO_PostInc, 11308 Opc == UO_PreInc || 11309 Opc == UO_PreDec); 11310 break; 11311 case UO_AddrOf: 11312 resultType = CheckAddressOfOperand(Input, OpLoc); 11313 RecordModifiableNonNullParam(*this, InputExpr); 11314 break; 11315 case UO_Deref: { 11316 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11317 if (Input.isInvalid()) return ExprError(); 11318 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11319 break; 11320 } 11321 case UO_Plus: 11322 case UO_Minus: 11323 Input = UsualUnaryConversions(Input.get()); 11324 if (Input.isInvalid()) return ExprError(); 11325 resultType = Input.get()->getType(); 11326 if (resultType->isDependentType()) 11327 break; 11328 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11329 break; 11330 else if (resultType->isVectorType() && 11331 // The z vector extensions don't allow + or - with bool vectors. 11332 (!Context.getLangOpts().ZVector || 11333 resultType->getAs<VectorType>()->getVectorKind() != 11334 VectorType::AltiVecBool)) 11335 break; 11336 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11337 Opc == UO_Plus && 11338 resultType->isPointerType()) 11339 break; 11340 11341 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11342 << resultType << Input.get()->getSourceRange()); 11343 11344 case UO_Not: // bitwise complement 11345 Input = UsualUnaryConversions(Input.get()); 11346 if (Input.isInvalid()) 11347 return ExprError(); 11348 resultType = Input.get()->getType(); 11349 if (resultType->isDependentType()) 11350 break; 11351 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11352 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11353 // C99 does not support '~' for complex conjugation. 11354 Diag(OpLoc, diag::ext_integer_complement_complex) 11355 << resultType << Input.get()->getSourceRange(); 11356 else if (resultType->hasIntegerRepresentation()) 11357 break; 11358 else if (resultType->isExtVectorType()) { 11359 if (Context.getLangOpts().OpenCL) { 11360 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11361 // on vector float types. 11362 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11363 if (!T->isIntegerType()) 11364 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11365 << resultType << Input.get()->getSourceRange()); 11366 } 11367 break; 11368 } else { 11369 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11370 << resultType << Input.get()->getSourceRange()); 11371 } 11372 break; 11373 11374 case UO_LNot: // logical negation 11375 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11376 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11377 if (Input.isInvalid()) return ExprError(); 11378 resultType = Input.get()->getType(); 11379 11380 // Though we still have to promote half FP to float... 11381 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11382 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11383 resultType = Context.FloatTy; 11384 } 11385 11386 if (resultType->isDependentType()) 11387 break; 11388 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11389 // C99 6.5.3.3p1: ok, fallthrough; 11390 if (Context.getLangOpts().CPlusPlus) { 11391 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11392 // operand contextually converted to bool. 11393 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11394 ScalarTypeToBooleanCastKind(resultType)); 11395 } else if (Context.getLangOpts().OpenCL && 11396 Context.getLangOpts().OpenCLVersion < 120) { 11397 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11398 // operate on scalar float types. 11399 if (!resultType->isIntegerType()) 11400 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11401 << resultType << Input.get()->getSourceRange()); 11402 } 11403 } else if (resultType->isExtVectorType()) { 11404 if (Context.getLangOpts().OpenCL && 11405 Context.getLangOpts().OpenCLVersion < 120) { 11406 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11407 // operate on vector float types. 11408 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11409 if (!T->isIntegerType()) 11410 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11411 << resultType << Input.get()->getSourceRange()); 11412 } 11413 // Vector logical not returns the signed variant of the operand type. 11414 resultType = GetSignedVectorType(resultType); 11415 break; 11416 } else { 11417 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11418 << resultType << Input.get()->getSourceRange()); 11419 } 11420 11421 // LNot always has type int. C99 6.5.3.3p5. 11422 // In C++, it's bool. C++ 5.3.1p8 11423 resultType = Context.getLogicalOperationType(); 11424 break; 11425 case UO_Real: 11426 case UO_Imag: 11427 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11428 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11429 // complex l-values to ordinary l-values and all other values to r-values. 11430 if (Input.isInvalid()) return ExprError(); 11431 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11432 if (Input.get()->getValueKind() != VK_RValue && 11433 Input.get()->getObjectKind() == OK_Ordinary) 11434 VK = Input.get()->getValueKind(); 11435 } else if (!getLangOpts().CPlusPlus) { 11436 // In C, a volatile scalar is read by __imag. In C++, it is not. 11437 Input = DefaultLvalueConversion(Input.get()); 11438 } 11439 break; 11440 case UO_Extension: 11441 case UO_Coawait: 11442 resultType = Input.get()->getType(); 11443 VK = Input.get()->getValueKind(); 11444 OK = Input.get()->getObjectKind(); 11445 break; 11446 } 11447 if (resultType.isNull() || Input.isInvalid()) 11448 return ExprError(); 11449 11450 // Check for array bounds violations in the operand of the UnaryOperator, 11451 // except for the '*' and '&' operators that have to be handled specially 11452 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11453 // that are explicitly defined as valid by the standard). 11454 if (Opc != UO_AddrOf && Opc != UO_Deref) 11455 CheckArrayAccess(Input.get()); 11456 11457 return new (Context) 11458 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11459 } 11460 11461 /// \brief Determine whether the given expression is a qualified member 11462 /// access expression, of a form that could be turned into a pointer to member 11463 /// with the address-of operator. 11464 static bool isQualifiedMemberAccess(Expr *E) { 11465 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11466 if (!DRE->getQualifier()) 11467 return false; 11468 11469 ValueDecl *VD = DRE->getDecl(); 11470 if (!VD->isCXXClassMember()) 11471 return false; 11472 11473 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11474 return true; 11475 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11476 return Method->isInstance(); 11477 11478 return false; 11479 } 11480 11481 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11482 if (!ULE->getQualifier()) 11483 return false; 11484 11485 for (NamedDecl *D : ULE->decls()) { 11486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11487 if (Method->isInstance()) 11488 return true; 11489 } else { 11490 // Overload set does not contain methods. 11491 break; 11492 } 11493 } 11494 11495 return false; 11496 } 11497 11498 return false; 11499 } 11500 11501 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11502 UnaryOperatorKind Opc, Expr *Input) { 11503 // First things first: handle placeholders so that the 11504 // overloaded-operator check considers the right type. 11505 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11506 // Increment and decrement of pseudo-object references. 11507 if (pty->getKind() == BuiltinType::PseudoObject && 11508 UnaryOperator::isIncrementDecrementOp(Opc)) 11509 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11510 11511 // extension is always a builtin operator. 11512 if (Opc == UO_Extension) 11513 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11514 11515 // & gets special logic for several kinds of placeholder. 11516 // The builtin code knows what to do. 11517 if (Opc == UO_AddrOf && 11518 (pty->getKind() == BuiltinType::Overload || 11519 pty->getKind() == BuiltinType::UnknownAny || 11520 pty->getKind() == BuiltinType::BoundMember)) 11521 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11522 11523 // Anything else needs to be handled now. 11524 ExprResult Result = CheckPlaceholderExpr(Input); 11525 if (Result.isInvalid()) return ExprError(); 11526 Input = Result.get(); 11527 } 11528 11529 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11530 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11531 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11532 // Find all of the overloaded operators visible from this 11533 // point. We perform both an operator-name lookup from the local 11534 // scope and an argument-dependent lookup based on the types of 11535 // the arguments. 11536 UnresolvedSet<16> Functions; 11537 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11538 if (S && OverOp != OO_None) 11539 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11540 Functions); 11541 11542 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11543 } 11544 11545 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11546 } 11547 11548 // Unary Operators. 'Tok' is the token for the operator. 11549 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11550 tok::TokenKind Op, Expr *Input) { 11551 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11552 } 11553 11554 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11555 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11556 LabelDecl *TheDecl) { 11557 TheDecl->markUsed(Context); 11558 // Create the AST node. The address of a label always has type 'void*'. 11559 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11560 Context.getPointerType(Context.VoidTy)); 11561 } 11562 11563 /// Given the last statement in a statement-expression, check whether 11564 /// the result is a producing expression (like a call to an 11565 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11566 /// release out of the full-expression. Otherwise, return null. 11567 /// Cannot fail. 11568 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11569 // Should always be wrapped with one of these. 11570 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11571 if (!cleanups) return nullptr; 11572 11573 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11574 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11575 return nullptr; 11576 11577 // Splice out the cast. This shouldn't modify any interesting 11578 // features of the statement. 11579 Expr *producer = cast->getSubExpr(); 11580 assert(producer->getType() == cast->getType()); 11581 assert(producer->getValueKind() == cast->getValueKind()); 11582 cleanups->setSubExpr(producer); 11583 return cleanups; 11584 } 11585 11586 void Sema::ActOnStartStmtExpr() { 11587 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11588 } 11589 11590 void Sema::ActOnStmtExprError() { 11591 // Note that function is also called by TreeTransform when leaving a 11592 // StmtExpr scope without rebuilding anything. 11593 11594 DiscardCleanupsInEvaluationContext(); 11595 PopExpressionEvaluationContext(); 11596 } 11597 11598 ExprResult 11599 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11600 SourceLocation RPLoc) { // "({..})" 11601 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11602 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11603 11604 if (hasAnyUnrecoverableErrorsInThisFunction()) 11605 DiscardCleanupsInEvaluationContext(); 11606 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11607 PopExpressionEvaluationContext(); 11608 11609 // FIXME: there are a variety of strange constraints to enforce here, for 11610 // example, it is not possible to goto into a stmt expression apparently. 11611 // More semantic analysis is needed. 11612 11613 // If there are sub-stmts in the compound stmt, take the type of the last one 11614 // as the type of the stmtexpr. 11615 QualType Ty = Context.VoidTy; 11616 bool StmtExprMayBindToTemp = false; 11617 if (!Compound->body_empty()) { 11618 Stmt *LastStmt = Compound->body_back(); 11619 LabelStmt *LastLabelStmt = nullptr; 11620 // If LastStmt is a label, skip down through into the body. 11621 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11622 LastLabelStmt = Label; 11623 LastStmt = Label->getSubStmt(); 11624 } 11625 11626 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11627 // Do function/array conversion on the last expression, but not 11628 // lvalue-to-rvalue. However, initialize an unqualified type. 11629 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11630 if (LastExpr.isInvalid()) 11631 return ExprError(); 11632 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11633 11634 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11635 // In ARC, if the final expression ends in a consume, splice 11636 // the consume out and bind it later. In the alternate case 11637 // (when dealing with a retainable type), the result 11638 // initialization will create a produce. In both cases the 11639 // result will be +1, and we'll need to balance that out with 11640 // a bind. 11641 if (Expr *rebuiltLastStmt 11642 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11643 LastExpr = rebuiltLastStmt; 11644 } else { 11645 LastExpr = PerformCopyInitialization( 11646 InitializedEntity::InitializeResult(LPLoc, 11647 Ty, 11648 false), 11649 SourceLocation(), 11650 LastExpr); 11651 } 11652 11653 if (LastExpr.isInvalid()) 11654 return ExprError(); 11655 if (LastExpr.get() != nullptr) { 11656 if (!LastLabelStmt) 11657 Compound->setLastStmt(LastExpr.get()); 11658 else 11659 LastLabelStmt->setSubStmt(LastExpr.get()); 11660 StmtExprMayBindToTemp = true; 11661 } 11662 } 11663 } 11664 } 11665 11666 // FIXME: Check that expression type is complete/non-abstract; statement 11667 // expressions are not lvalues. 11668 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11669 if (StmtExprMayBindToTemp) 11670 return MaybeBindToTemporary(ResStmtExpr); 11671 return ResStmtExpr; 11672 } 11673 11674 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11675 TypeSourceInfo *TInfo, 11676 ArrayRef<OffsetOfComponent> Components, 11677 SourceLocation RParenLoc) { 11678 QualType ArgTy = TInfo->getType(); 11679 bool Dependent = ArgTy->isDependentType(); 11680 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11681 11682 // We must have at least one component that refers to the type, and the first 11683 // one is known to be a field designator. Verify that the ArgTy represents 11684 // a struct/union/class. 11685 if (!Dependent && !ArgTy->isRecordType()) 11686 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11687 << ArgTy << TypeRange); 11688 11689 // Type must be complete per C99 7.17p3 because a declaring a variable 11690 // with an incomplete type would be ill-formed. 11691 if (!Dependent 11692 && RequireCompleteType(BuiltinLoc, ArgTy, 11693 diag::err_offsetof_incomplete_type, TypeRange)) 11694 return ExprError(); 11695 11696 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11697 // GCC extension, diagnose them. 11698 // FIXME: This diagnostic isn't actually visible because the location is in 11699 // a system header! 11700 if (Components.size() != 1) 11701 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11702 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11703 11704 bool DidWarnAboutNonPOD = false; 11705 QualType CurrentType = ArgTy; 11706 SmallVector<OffsetOfNode, 4> Comps; 11707 SmallVector<Expr*, 4> Exprs; 11708 for (const OffsetOfComponent &OC : Components) { 11709 if (OC.isBrackets) { 11710 // Offset of an array sub-field. TODO: Should we allow vector elements? 11711 if (!CurrentType->isDependentType()) { 11712 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11713 if(!AT) 11714 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11715 << CurrentType); 11716 CurrentType = AT->getElementType(); 11717 } else 11718 CurrentType = Context.DependentTy; 11719 11720 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11721 if (IdxRval.isInvalid()) 11722 return ExprError(); 11723 Expr *Idx = IdxRval.get(); 11724 11725 // The expression must be an integral expression. 11726 // FIXME: An integral constant expression? 11727 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11728 !Idx->getType()->isIntegerType()) 11729 return ExprError(Diag(Idx->getLocStart(), 11730 diag::err_typecheck_subscript_not_integer) 11731 << Idx->getSourceRange()); 11732 11733 // Record this array index. 11734 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11735 Exprs.push_back(Idx); 11736 continue; 11737 } 11738 11739 // Offset of a field. 11740 if (CurrentType->isDependentType()) { 11741 // We have the offset of a field, but we can't look into the dependent 11742 // type. Just record the identifier of the field. 11743 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11744 CurrentType = Context.DependentTy; 11745 continue; 11746 } 11747 11748 // We need to have a complete type to look into. 11749 if (RequireCompleteType(OC.LocStart, CurrentType, 11750 diag::err_offsetof_incomplete_type)) 11751 return ExprError(); 11752 11753 // Look for the designated field. 11754 const RecordType *RC = CurrentType->getAs<RecordType>(); 11755 if (!RC) 11756 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11757 << CurrentType); 11758 RecordDecl *RD = RC->getDecl(); 11759 11760 // C++ [lib.support.types]p5: 11761 // The macro offsetof accepts a restricted set of type arguments in this 11762 // International Standard. type shall be a POD structure or a POD union 11763 // (clause 9). 11764 // C++11 [support.types]p4: 11765 // If type is not a standard-layout class (Clause 9), the results are 11766 // undefined. 11767 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11768 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11769 unsigned DiagID = 11770 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11771 : diag::ext_offsetof_non_pod_type; 11772 11773 if (!IsSafe && !DidWarnAboutNonPOD && 11774 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11775 PDiag(DiagID) 11776 << SourceRange(Components[0].LocStart, OC.LocEnd) 11777 << CurrentType)) 11778 DidWarnAboutNonPOD = true; 11779 } 11780 11781 // Look for the field. 11782 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11783 LookupQualifiedName(R, RD); 11784 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11785 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11786 if (!MemberDecl) { 11787 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11788 MemberDecl = IndirectMemberDecl->getAnonField(); 11789 } 11790 11791 if (!MemberDecl) 11792 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11793 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11794 OC.LocEnd)); 11795 11796 // C99 7.17p3: 11797 // (If the specified member is a bit-field, the behavior is undefined.) 11798 // 11799 // We diagnose this as an error. 11800 if (MemberDecl->isBitField()) { 11801 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11802 << MemberDecl->getDeclName() 11803 << SourceRange(BuiltinLoc, RParenLoc); 11804 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11805 return ExprError(); 11806 } 11807 11808 RecordDecl *Parent = MemberDecl->getParent(); 11809 if (IndirectMemberDecl) 11810 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11811 11812 // If the member was found in a base class, introduce OffsetOfNodes for 11813 // the base class indirections. 11814 CXXBasePaths Paths; 11815 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11816 Paths)) { 11817 if (Paths.getDetectedVirtual()) { 11818 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11819 << MemberDecl->getDeclName() 11820 << SourceRange(BuiltinLoc, RParenLoc); 11821 return ExprError(); 11822 } 11823 11824 CXXBasePath &Path = Paths.front(); 11825 for (const CXXBasePathElement &B : Path) 11826 Comps.push_back(OffsetOfNode(B.Base)); 11827 } 11828 11829 if (IndirectMemberDecl) { 11830 for (auto *FI : IndirectMemberDecl->chain()) { 11831 assert(isa<FieldDecl>(FI)); 11832 Comps.push_back(OffsetOfNode(OC.LocStart, 11833 cast<FieldDecl>(FI), OC.LocEnd)); 11834 } 11835 } else 11836 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11837 11838 CurrentType = MemberDecl->getType().getNonReferenceType(); 11839 } 11840 11841 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11842 Comps, Exprs, RParenLoc); 11843 } 11844 11845 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11846 SourceLocation BuiltinLoc, 11847 SourceLocation TypeLoc, 11848 ParsedType ParsedArgTy, 11849 ArrayRef<OffsetOfComponent> Components, 11850 SourceLocation RParenLoc) { 11851 11852 TypeSourceInfo *ArgTInfo; 11853 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11854 if (ArgTy.isNull()) 11855 return ExprError(); 11856 11857 if (!ArgTInfo) 11858 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11859 11860 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11861 } 11862 11863 11864 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11865 Expr *CondExpr, 11866 Expr *LHSExpr, Expr *RHSExpr, 11867 SourceLocation RPLoc) { 11868 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11869 11870 ExprValueKind VK = VK_RValue; 11871 ExprObjectKind OK = OK_Ordinary; 11872 QualType resType; 11873 bool ValueDependent = false; 11874 bool CondIsTrue = false; 11875 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11876 resType = Context.DependentTy; 11877 ValueDependent = true; 11878 } else { 11879 // The conditional expression is required to be a constant expression. 11880 llvm::APSInt condEval(32); 11881 ExprResult CondICE 11882 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11883 diag::err_typecheck_choose_expr_requires_constant, false); 11884 if (CondICE.isInvalid()) 11885 return ExprError(); 11886 CondExpr = CondICE.get(); 11887 CondIsTrue = condEval.getZExtValue(); 11888 11889 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11890 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11891 11892 resType = ActiveExpr->getType(); 11893 ValueDependent = ActiveExpr->isValueDependent(); 11894 VK = ActiveExpr->getValueKind(); 11895 OK = ActiveExpr->getObjectKind(); 11896 } 11897 11898 return new (Context) 11899 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11900 CondIsTrue, resType->isDependentType(), ValueDependent); 11901 } 11902 11903 //===----------------------------------------------------------------------===// 11904 // Clang Extensions. 11905 //===----------------------------------------------------------------------===// 11906 11907 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11908 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11909 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11910 11911 if (LangOpts.CPlusPlus) { 11912 Decl *ManglingContextDecl; 11913 if (MangleNumberingContext *MCtx = 11914 getCurrentMangleNumberContext(Block->getDeclContext(), 11915 ManglingContextDecl)) { 11916 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11917 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11918 } 11919 } 11920 11921 PushBlockScope(CurScope, Block); 11922 CurContext->addDecl(Block); 11923 if (CurScope) 11924 PushDeclContext(CurScope, Block); 11925 else 11926 CurContext = Block; 11927 11928 getCurBlock()->HasImplicitReturnType = true; 11929 11930 // Enter a new evaluation context to insulate the block from any 11931 // cleanups from the enclosing full-expression. 11932 PushExpressionEvaluationContext(PotentiallyEvaluated); 11933 } 11934 11935 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11936 Scope *CurScope) { 11937 assert(ParamInfo.getIdentifier() == nullptr && 11938 "block-id should have no identifier!"); 11939 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11940 BlockScopeInfo *CurBlock = getCurBlock(); 11941 11942 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11943 QualType T = Sig->getType(); 11944 11945 // FIXME: We should allow unexpanded parameter packs here, but that would, 11946 // in turn, make the block expression contain unexpanded parameter packs. 11947 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11948 // Drop the parameters. 11949 FunctionProtoType::ExtProtoInfo EPI; 11950 EPI.HasTrailingReturn = false; 11951 EPI.TypeQuals |= DeclSpec::TQ_const; 11952 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11953 Sig = Context.getTrivialTypeSourceInfo(T); 11954 } 11955 11956 // GetTypeForDeclarator always produces a function type for a block 11957 // literal signature. Furthermore, it is always a FunctionProtoType 11958 // unless the function was written with a typedef. 11959 assert(T->isFunctionType() && 11960 "GetTypeForDeclarator made a non-function block signature"); 11961 11962 // Look for an explicit signature in that function type. 11963 FunctionProtoTypeLoc ExplicitSignature; 11964 11965 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11966 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11967 11968 // Check whether that explicit signature was synthesized by 11969 // GetTypeForDeclarator. If so, don't save that as part of the 11970 // written signature. 11971 if (ExplicitSignature.getLocalRangeBegin() == 11972 ExplicitSignature.getLocalRangeEnd()) { 11973 // This would be much cheaper if we stored TypeLocs instead of 11974 // TypeSourceInfos. 11975 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11976 unsigned Size = Result.getFullDataSize(); 11977 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11978 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11979 11980 ExplicitSignature = FunctionProtoTypeLoc(); 11981 } 11982 } 11983 11984 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11985 CurBlock->FunctionType = T; 11986 11987 const FunctionType *Fn = T->getAs<FunctionType>(); 11988 QualType RetTy = Fn->getReturnType(); 11989 bool isVariadic = 11990 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11991 11992 CurBlock->TheDecl->setIsVariadic(isVariadic); 11993 11994 // Context.DependentTy is used as a placeholder for a missing block 11995 // return type. TODO: what should we do with declarators like: 11996 // ^ * { ... } 11997 // If the answer is "apply template argument deduction".... 11998 if (RetTy != Context.DependentTy) { 11999 CurBlock->ReturnType = RetTy; 12000 CurBlock->TheDecl->setBlockMissingReturnType(false); 12001 CurBlock->HasImplicitReturnType = false; 12002 } 12003 12004 // Push block parameters from the declarator if we had them. 12005 SmallVector<ParmVarDecl*, 8> Params; 12006 if (ExplicitSignature) { 12007 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12008 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12009 if (Param->getIdentifier() == nullptr && 12010 !Param->isImplicit() && 12011 !Param->isInvalidDecl() && 12012 !getLangOpts().CPlusPlus) 12013 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12014 Params.push_back(Param); 12015 } 12016 12017 // Fake up parameter variables if we have a typedef, like 12018 // ^ fntype { ... } 12019 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12020 for (const auto &I : Fn->param_types()) { 12021 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12022 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12023 Params.push_back(Param); 12024 } 12025 } 12026 12027 // Set the parameters on the block decl. 12028 if (!Params.empty()) { 12029 CurBlock->TheDecl->setParams(Params); 12030 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 12031 CurBlock->TheDecl->param_end(), 12032 /*CheckParameterNames=*/false); 12033 } 12034 12035 // Finally we can process decl attributes. 12036 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12037 12038 // Put the parameter variables in scope. 12039 for (auto AI : CurBlock->TheDecl->params()) { 12040 AI->setOwningFunction(CurBlock->TheDecl); 12041 12042 // If this has an identifier, add it to the scope stack. 12043 if (AI->getIdentifier()) { 12044 CheckShadow(CurBlock->TheScope, AI); 12045 12046 PushOnScopeChains(AI, CurBlock->TheScope); 12047 } 12048 } 12049 } 12050 12051 /// ActOnBlockError - If there is an error parsing a block, this callback 12052 /// is invoked to pop the information about the block from the action impl. 12053 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12054 // Leave the expression-evaluation context. 12055 DiscardCleanupsInEvaluationContext(); 12056 PopExpressionEvaluationContext(); 12057 12058 // Pop off CurBlock, handle nested blocks. 12059 PopDeclContext(); 12060 PopFunctionScopeInfo(); 12061 } 12062 12063 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12064 /// literal was successfully completed. ^(int x){...} 12065 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12066 Stmt *Body, Scope *CurScope) { 12067 // If blocks are disabled, emit an error. 12068 if (!LangOpts.Blocks) 12069 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12070 12071 // Leave the expression-evaluation context. 12072 if (hasAnyUnrecoverableErrorsInThisFunction()) 12073 DiscardCleanupsInEvaluationContext(); 12074 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 12075 PopExpressionEvaluationContext(); 12076 12077 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12078 12079 if (BSI->HasImplicitReturnType) 12080 deduceClosureReturnType(*BSI); 12081 12082 PopDeclContext(); 12083 12084 QualType RetTy = Context.VoidTy; 12085 if (!BSI->ReturnType.isNull()) 12086 RetTy = BSI->ReturnType; 12087 12088 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12089 QualType BlockTy; 12090 12091 // Set the captured variables on the block. 12092 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12093 SmallVector<BlockDecl::Capture, 4> Captures; 12094 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12095 if (Cap.isThisCapture()) 12096 continue; 12097 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12098 Cap.isNested(), Cap.getInitExpr()); 12099 Captures.push_back(NewCap); 12100 } 12101 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12102 12103 // If the user wrote a function type in some form, try to use that. 12104 if (!BSI->FunctionType.isNull()) { 12105 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12106 12107 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12108 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12109 12110 // Turn protoless block types into nullary block types. 12111 if (isa<FunctionNoProtoType>(FTy)) { 12112 FunctionProtoType::ExtProtoInfo EPI; 12113 EPI.ExtInfo = Ext; 12114 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12115 12116 // Otherwise, if we don't need to change anything about the function type, 12117 // preserve its sugar structure. 12118 } else if (FTy->getReturnType() == RetTy && 12119 (!NoReturn || FTy->getNoReturnAttr())) { 12120 BlockTy = BSI->FunctionType; 12121 12122 // Otherwise, make the minimal modifications to the function type. 12123 } else { 12124 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12125 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12126 EPI.TypeQuals = 0; // FIXME: silently? 12127 EPI.ExtInfo = Ext; 12128 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12129 } 12130 12131 // If we don't have a function type, just build one from nothing. 12132 } else { 12133 FunctionProtoType::ExtProtoInfo EPI; 12134 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12135 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12136 } 12137 12138 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 12139 BSI->TheDecl->param_end()); 12140 BlockTy = Context.getBlockPointerType(BlockTy); 12141 12142 // If needed, diagnose invalid gotos and switches in the block. 12143 if (getCurFunction()->NeedsScopeChecking() && 12144 !PP.isCodeCompletionEnabled()) 12145 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12146 12147 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12148 12149 // Try to apply the named return value optimization. We have to check again 12150 // if we can do this, though, because blocks keep return statements around 12151 // to deduce an implicit return type. 12152 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12153 !BSI->TheDecl->isDependentContext()) 12154 computeNRVO(Body, BSI); 12155 12156 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12157 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12158 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12159 12160 // If the block isn't obviously global, i.e. it captures anything at 12161 // all, then we need to do a few things in the surrounding context: 12162 if (Result->getBlockDecl()->hasCaptures()) { 12163 // First, this expression has a new cleanup object. 12164 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12165 ExprNeedsCleanups = true; 12166 12167 // It also gets a branch-protected scope if any of the captured 12168 // variables needs destruction. 12169 for (const auto &CI : Result->getBlockDecl()->captures()) { 12170 const VarDecl *var = CI.getVariable(); 12171 if (var->getType().isDestructedType() != QualType::DK_none) { 12172 getCurFunction()->setHasBranchProtectedScope(); 12173 break; 12174 } 12175 } 12176 } 12177 12178 return Result; 12179 } 12180 12181 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12182 SourceLocation RPLoc) { 12183 TypeSourceInfo *TInfo; 12184 GetTypeFromParser(Ty, &TInfo); 12185 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12186 } 12187 12188 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12189 Expr *E, TypeSourceInfo *TInfo, 12190 SourceLocation RPLoc) { 12191 Expr *OrigExpr = E; 12192 bool IsMS = false; 12193 12194 // CUDA device code does not support varargs. 12195 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12196 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12197 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12198 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12199 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12200 } 12201 } 12202 12203 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12204 // as Microsoft ABI on an actual Microsoft platform, where 12205 // __builtin_ms_va_list and __builtin_va_list are the same.) 12206 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12207 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12208 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12209 if (Context.hasSameType(MSVaListType, E->getType())) { 12210 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12211 return ExprError(); 12212 IsMS = true; 12213 } 12214 } 12215 12216 // Get the va_list type 12217 QualType VaListType = Context.getBuiltinVaListType(); 12218 if (!IsMS) { 12219 if (VaListType->isArrayType()) { 12220 // Deal with implicit array decay; for example, on x86-64, 12221 // va_list is an array, but it's supposed to decay to 12222 // a pointer for va_arg. 12223 VaListType = Context.getArrayDecayedType(VaListType); 12224 // Make sure the input expression also decays appropriately. 12225 ExprResult Result = UsualUnaryConversions(E); 12226 if (Result.isInvalid()) 12227 return ExprError(); 12228 E = Result.get(); 12229 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12230 // If va_list is a record type and we are compiling in C++ mode, 12231 // check the argument using reference binding. 12232 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12233 Context, Context.getLValueReferenceType(VaListType), false); 12234 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12235 if (Init.isInvalid()) 12236 return ExprError(); 12237 E = Init.getAs<Expr>(); 12238 } else { 12239 // Otherwise, the va_list argument must be an l-value because 12240 // it is modified by va_arg. 12241 if (!E->isTypeDependent() && 12242 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12243 return ExprError(); 12244 } 12245 } 12246 12247 if (!IsMS && !E->isTypeDependent() && 12248 !Context.hasSameType(VaListType, E->getType())) 12249 return ExprError(Diag(E->getLocStart(), 12250 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12251 << OrigExpr->getType() << E->getSourceRange()); 12252 12253 if (!TInfo->getType()->isDependentType()) { 12254 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12255 diag::err_second_parameter_to_va_arg_incomplete, 12256 TInfo->getTypeLoc())) 12257 return ExprError(); 12258 12259 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12260 TInfo->getType(), 12261 diag::err_second_parameter_to_va_arg_abstract, 12262 TInfo->getTypeLoc())) 12263 return ExprError(); 12264 12265 if (!TInfo->getType().isPODType(Context)) { 12266 Diag(TInfo->getTypeLoc().getBeginLoc(), 12267 TInfo->getType()->isObjCLifetimeType() 12268 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12269 : diag::warn_second_parameter_to_va_arg_not_pod) 12270 << TInfo->getType() 12271 << TInfo->getTypeLoc().getSourceRange(); 12272 } 12273 12274 // Check for va_arg where arguments of the given type will be promoted 12275 // (i.e. this va_arg is guaranteed to have undefined behavior). 12276 QualType PromoteType; 12277 if (TInfo->getType()->isPromotableIntegerType()) { 12278 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12279 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12280 PromoteType = QualType(); 12281 } 12282 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12283 PromoteType = Context.DoubleTy; 12284 if (!PromoteType.isNull()) 12285 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12286 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12287 << TInfo->getType() 12288 << PromoteType 12289 << TInfo->getTypeLoc().getSourceRange()); 12290 } 12291 12292 QualType T = TInfo->getType().getNonLValueExprType(Context); 12293 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12294 } 12295 12296 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12297 // The type of __null will be int or long, depending on the size of 12298 // pointers on the target. 12299 QualType Ty; 12300 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12301 if (pw == Context.getTargetInfo().getIntWidth()) 12302 Ty = Context.IntTy; 12303 else if (pw == Context.getTargetInfo().getLongWidth()) 12304 Ty = Context.LongTy; 12305 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12306 Ty = Context.LongLongTy; 12307 else { 12308 llvm_unreachable("I don't know size of pointer!"); 12309 } 12310 12311 return new (Context) GNUNullExpr(Ty, TokenLoc); 12312 } 12313 12314 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12315 bool Diagnose) { 12316 if (!getLangOpts().ObjC1) 12317 return false; 12318 12319 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12320 if (!PT) 12321 return false; 12322 12323 if (!PT->isObjCIdType()) { 12324 // Check if the destination is the 'NSString' interface. 12325 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12326 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12327 return false; 12328 } 12329 12330 // Ignore any parens, implicit casts (should only be 12331 // array-to-pointer decays), and not-so-opaque values. The last is 12332 // important for making this trigger for property assignments. 12333 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12334 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12335 if (OV->getSourceExpr()) 12336 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12337 12338 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12339 if (!SL || !SL->isAscii()) 12340 return false; 12341 if (Diagnose) { 12342 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12343 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12344 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12345 } 12346 return true; 12347 } 12348 12349 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12350 const Expr *SrcExpr) { 12351 if (!DstType->isFunctionPointerType() || 12352 !SrcExpr->getType()->isFunctionType()) 12353 return false; 12354 12355 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12356 if (!DRE) 12357 return false; 12358 12359 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12360 if (!FD) 12361 return false; 12362 12363 return !S.checkAddressOfFunctionIsAvailable(FD, 12364 /*Complain=*/true, 12365 SrcExpr->getLocStart()); 12366 } 12367 12368 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12369 SourceLocation Loc, 12370 QualType DstType, QualType SrcType, 12371 Expr *SrcExpr, AssignmentAction Action, 12372 bool *Complained) { 12373 if (Complained) 12374 *Complained = false; 12375 12376 // Decode the result (notice that AST's are still created for extensions). 12377 bool CheckInferredResultType = false; 12378 bool isInvalid = false; 12379 unsigned DiagKind = 0; 12380 FixItHint Hint; 12381 ConversionFixItGenerator ConvHints; 12382 bool MayHaveConvFixit = false; 12383 bool MayHaveFunctionDiff = false; 12384 const ObjCInterfaceDecl *IFace = nullptr; 12385 const ObjCProtocolDecl *PDecl = nullptr; 12386 12387 switch (ConvTy) { 12388 case Compatible: 12389 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12390 return false; 12391 12392 case PointerToInt: 12393 DiagKind = diag::ext_typecheck_convert_pointer_int; 12394 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12395 MayHaveConvFixit = true; 12396 break; 12397 case IntToPointer: 12398 DiagKind = diag::ext_typecheck_convert_int_pointer; 12399 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12400 MayHaveConvFixit = true; 12401 break; 12402 case IncompatiblePointer: 12403 DiagKind = 12404 (Action == AA_Passing_CFAudited ? 12405 diag::err_arc_typecheck_convert_incompatible_pointer : 12406 diag::ext_typecheck_convert_incompatible_pointer); 12407 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12408 SrcType->isObjCObjectPointerType(); 12409 if (Hint.isNull() && !CheckInferredResultType) { 12410 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12411 } 12412 else if (CheckInferredResultType) { 12413 SrcType = SrcType.getUnqualifiedType(); 12414 DstType = DstType.getUnqualifiedType(); 12415 } 12416 MayHaveConvFixit = true; 12417 break; 12418 case IncompatiblePointerSign: 12419 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12420 break; 12421 case FunctionVoidPointer: 12422 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12423 break; 12424 case IncompatiblePointerDiscardsQualifiers: { 12425 // Perform array-to-pointer decay if necessary. 12426 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12427 12428 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12429 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12430 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12431 DiagKind = diag::err_typecheck_incompatible_address_space; 12432 break; 12433 12434 12435 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12436 DiagKind = diag::err_typecheck_incompatible_ownership; 12437 break; 12438 } 12439 12440 llvm_unreachable("unknown error case for discarding qualifiers!"); 12441 // fallthrough 12442 } 12443 case CompatiblePointerDiscardsQualifiers: 12444 // If the qualifiers lost were because we were applying the 12445 // (deprecated) C++ conversion from a string literal to a char* 12446 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12447 // Ideally, this check would be performed in 12448 // checkPointerTypesForAssignment. However, that would require a 12449 // bit of refactoring (so that the second argument is an 12450 // expression, rather than a type), which should be done as part 12451 // of a larger effort to fix checkPointerTypesForAssignment for 12452 // C++ semantics. 12453 if (getLangOpts().CPlusPlus && 12454 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12455 return false; 12456 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12457 break; 12458 case IncompatibleNestedPointerQualifiers: 12459 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12460 break; 12461 case IntToBlockPointer: 12462 DiagKind = diag::err_int_to_block_pointer; 12463 break; 12464 case IncompatibleBlockPointer: 12465 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12466 break; 12467 case IncompatibleObjCQualifiedId: { 12468 if (SrcType->isObjCQualifiedIdType()) { 12469 const ObjCObjectPointerType *srcOPT = 12470 SrcType->getAs<ObjCObjectPointerType>(); 12471 for (auto *srcProto : srcOPT->quals()) { 12472 PDecl = srcProto; 12473 break; 12474 } 12475 if (const ObjCInterfaceType *IFaceT = 12476 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12477 IFace = IFaceT->getDecl(); 12478 } 12479 else if (DstType->isObjCQualifiedIdType()) { 12480 const ObjCObjectPointerType *dstOPT = 12481 DstType->getAs<ObjCObjectPointerType>(); 12482 for (auto *dstProto : dstOPT->quals()) { 12483 PDecl = dstProto; 12484 break; 12485 } 12486 if (const ObjCInterfaceType *IFaceT = 12487 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12488 IFace = IFaceT->getDecl(); 12489 } 12490 DiagKind = diag::warn_incompatible_qualified_id; 12491 break; 12492 } 12493 case IncompatibleVectors: 12494 DiagKind = diag::warn_incompatible_vectors; 12495 break; 12496 case IncompatibleObjCWeakRef: 12497 DiagKind = diag::err_arc_weak_unavailable_assign; 12498 break; 12499 case Incompatible: 12500 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12501 if (Complained) 12502 *Complained = true; 12503 return true; 12504 } 12505 12506 DiagKind = diag::err_typecheck_convert_incompatible; 12507 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12508 MayHaveConvFixit = true; 12509 isInvalid = true; 12510 MayHaveFunctionDiff = true; 12511 break; 12512 } 12513 12514 QualType FirstType, SecondType; 12515 switch (Action) { 12516 case AA_Assigning: 12517 case AA_Initializing: 12518 // The destination type comes first. 12519 FirstType = DstType; 12520 SecondType = SrcType; 12521 break; 12522 12523 case AA_Returning: 12524 case AA_Passing: 12525 case AA_Passing_CFAudited: 12526 case AA_Converting: 12527 case AA_Sending: 12528 case AA_Casting: 12529 // The source type comes first. 12530 FirstType = SrcType; 12531 SecondType = DstType; 12532 break; 12533 } 12534 12535 PartialDiagnostic FDiag = PDiag(DiagKind); 12536 if (Action == AA_Passing_CFAudited) 12537 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12538 else 12539 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12540 12541 // If we can fix the conversion, suggest the FixIts. 12542 assert(ConvHints.isNull() || Hint.isNull()); 12543 if (!ConvHints.isNull()) { 12544 for (FixItHint &H : ConvHints.Hints) 12545 FDiag << H; 12546 } else { 12547 FDiag << Hint; 12548 } 12549 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12550 12551 if (MayHaveFunctionDiff) 12552 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12553 12554 Diag(Loc, FDiag); 12555 if (DiagKind == diag::warn_incompatible_qualified_id && 12556 PDecl && IFace && !IFace->hasDefinition()) 12557 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12558 << IFace->getName() << PDecl->getName(); 12559 12560 if (SecondType == Context.OverloadTy) 12561 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12562 FirstType, /*TakingAddress=*/true); 12563 12564 if (CheckInferredResultType) 12565 EmitRelatedResultTypeNote(SrcExpr); 12566 12567 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12568 EmitRelatedResultTypeNoteForReturn(DstType); 12569 12570 if (Complained) 12571 *Complained = true; 12572 return isInvalid; 12573 } 12574 12575 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12576 llvm::APSInt *Result) { 12577 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12578 public: 12579 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12580 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12581 } 12582 } Diagnoser; 12583 12584 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12585 } 12586 12587 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12588 llvm::APSInt *Result, 12589 unsigned DiagID, 12590 bool AllowFold) { 12591 class IDDiagnoser : public VerifyICEDiagnoser { 12592 unsigned DiagID; 12593 12594 public: 12595 IDDiagnoser(unsigned DiagID) 12596 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12597 12598 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12599 S.Diag(Loc, DiagID) << SR; 12600 } 12601 } Diagnoser(DiagID); 12602 12603 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12604 } 12605 12606 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12607 SourceRange SR) { 12608 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12609 } 12610 12611 ExprResult 12612 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12613 VerifyICEDiagnoser &Diagnoser, 12614 bool AllowFold) { 12615 SourceLocation DiagLoc = E->getLocStart(); 12616 12617 if (getLangOpts().CPlusPlus11) { 12618 // C++11 [expr.const]p5: 12619 // If an expression of literal class type is used in a context where an 12620 // integral constant expression is required, then that class type shall 12621 // have a single non-explicit conversion function to an integral or 12622 // unscoped enumeration type 12623 ExprResult Converted; 12624 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12625 public: 12626 CXX11ConvertDiagnoser(bool Silent) 12627 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12628 Silent, true) {} 12629 12630 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12631 QualType T) override { 12632 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12633 } 12634 12635 SemaDiagnosticBuilder diagnoseIncomplete( 12636 Sema &S, SourceLocation Loc, QualType T) override { 12637 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12638 } 12639 12640 SemaDiagnosticBuilder diagnoseExplicitConv( 12641 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12642 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12643 } 12644 12645 SemaDiagnosticBuilder noteExplicitConv( 12646 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12647 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12648 << ConvTy->isEnumeralType() << ConvTy; 12649 } 12650 12651 SemaDiagnosticBuilder diagnoseAmbiguous( 12652 Sema &S, SourceLocation Loc, QualType T) override { 12653 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12654 } 12655 12656 SemaDiagnosticBuilder noteAmbiguous( 12657 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12658 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12659 << ConvTy->isEnumeralType() << ConvTy; 12660 } 12661 12662 SemaDiagnosticBuilder diagnoseConversion( 12663 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12664 llvm_unreachable("conversion functions are permitted"); 12665 } 12666 } ConvertDiagnoser(Diagnoser.Suppress); 12667 12668 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12669 ConvertDiagnoser); 12670 if (Converted.isInvalid()) 12671 return Converted; 12672 E = Converted.get(); 12673 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12674 return ExprError(); 12675 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12676 // An ICE must be of integral or unscoped enumeration type. 12677 if (!Diagnoser.Suppress) 12678 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12679 return ExprError(); 12680 } 12681 12682 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12683 // in the non-ICE case. 12684 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12685 if (Result) 12686 *Result = E->EvaluateKnownConstInt(Context); 12687 return E; 12688 } 12689 12690 Expr::EvalResult EvalResult; 12691 SmallVector<PartialDiagnosticAt, 8> Notes; 12692 EvalResult.Diag = &Notes; 12693 12694 // Try to evaluate the expression, and produce diagnostics explaining why it's 12695 // not a constant expression as a side-effect. 12696 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12697 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12698 12699 // In C++11, we can rely on diagnostics being produced for any expression 12700 // which is not a constant expression. If no diagnostics were produced, then 12701 // this is a constant expression. 12702 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12703 if (Result) 12704 *Result = EvalResult.Val.getInt(); 12705 return E; 12706 } 12707 12708 // If our only note is the usual "invalid subexpression" note, just point 12709 // the caret at its location rather than producing an essentially 12710 // redundant note. 12711 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12712 diag::note_invalid_subexpr_in_const_expr) { 12713 DiagLoc = Notes[0].first; 12714 Notes.clear(); 12715 } 12716 12717 if (!Folded || !AllowFold) { 12718 if (!Diagnoser.Suppress) { 12719 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12720 for (const PartialDiagnosticAt &Note : Notes) 12721 Diag(Note.first, Note.second); 12722 } 12723 12724 return ExprError(); 12725 } 12726 12727 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12728 for (const PartialDiagnosticAt &Note : Notes) 12729 Diag(Note.first, Note.second); 12730 12731 if (Result) 12732 *Result = EvalResult.Val.getInt(); 12733 return E; 12734 } 12735 12736 namespace { 12737 // Handle the case where we conclude a expression which we speculatively 12738 // considered to be unevaluated is actually evaluated. 12739 class TransformToPE : public TreeTransform<TransformToPE> { 12740 typedef TreeTransform<TransformToPE> BaseTransform; 12741 12742 public: 12743 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12744 12745 // Make sure we redo semantic analysis 12746 bool AlwaysRebuild() { return true; } 12747 12748 // Make sure we handle LabelStmts correctly. 12749 // FIXME: This does the right thing, but maybe we need a more general 12750 // fix to TreeTransform? 12751 StmtResult TransformLabelStmt(LabelStmt *S) { 12752 S->getDecl()->setStmt(nullptr); 12753 return BaseTransform::TransformLabelStmt(S); 12754 } 12755 12756 // We need to special-case DeclRefExprs referring to FieldDecls which 12757 // are not part of a member pointer formation; normal TreeTransforming 12758 // doesn't catch this case because of the way we represent them in the AST. 12759 // FIXME: This is a bit ugly; is it really the best way to handle this 12760 // case? 12761 // 12762 // Error on DeclRefExprs referring to FieldDecls. 12763 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12764 if (isa<FieldDecl>(E->getDecl()) && 12765 !SemaRef.isUnevaluatedContext()) 12766 return SemaRef.Diag(E->getLocation(), 12767 diag::err_invalid_non_static_member_use) 12768 << E->getDecl() << E->getSourceRange(); 12769 12770 return BaseTransform::TransformDeclRefExpr(E); 12771 } 12772 12773 // Exception: filter out member pointer formation 12774 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12775 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12776 return E; 12777 12778 return BaseTransform::TransformUnaryOperator(E); 12779 } 12780 12781 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12782 // Lambdas never need to be transformed. 12783 return E; 12784 } 12785 }; 12786 } 12787 12788 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12789 assert(isUnevaluatedContext() && 12790 "Should only transform unevaluated expressions"); 12791 ExprEvalContexts.back().Context = 12792 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12793 if (isUnevaluatedContext()) 12794 return E; 12795 return TransformToPE(*this).TransformExpr(E); 12796 } 12797 12798 void 12799 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12800 Decl *LambdaContextDecl, 12801 bool IsDecltype) { 12802 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12803 ExprNeedsCleanups, LambdaContextDecl, 12804 IsDecltype); 12805 ExprNeedsCleanups = false; 12806 if (!MaybeODRUseExprs.empty()) 12807 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12808 } 12809 12810 void 12811 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12812 ReuseLambdaContextDecl_t, 12813 bool IsDecltype) { 12814 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12815 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12816 } 12817 12818 void Sema::PopExpressionEvaluationContext() { 12819 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12820 unsigned NumTypos = Rec.NumTypos; 12821 12822 if (!Rec.Lambdas.empty()) { 12823 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12824 unsigned D; 12825 if (Rec.isUnevaluated()) { 12826 // C++11 [expr.prim.lambda]p2: 12827 // A lambda-expression shall not appear in an unevaluated operand 12828 // (Clause 5). 12829 D = diag::err_lambda_unevaluated_operand; 12830 } else { 12831 // C++1y [expr.const]p2: 12832 // A conditional-expression e is a core constant expression unless the 12833 // evaluation of e, following the rules of the abstract machine, would 12834 // evaluate [...] a lambda-expression. 12835 D = diag::err_lambda_in_constant_expression; 12836 } 12837 for (const auto *L : Rec.Lambdas) 12838 Diag(L->getLocStart(), D); 12839 } else { 12840 // Mark the capture expressions odr-used. This was deferred 12841 // during lambda expression creation. 12842 for (auto *Lambda : Rec.Lambdas) { 12843 for (auto *C : Lambda->capture_inits()) 12844 MarkDeclarationsReferencedInExpr(C); 12845 } 12846 } 12847 } 12848 12849 // When are coming out of an unevaluated context, clear out any 12850 // temporaries that we may have created as part of the evaluation of 12851 // the expression in that context: they aren't relevant because they 12852 // will never be constructed. 12853 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12854 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12855 ExprCleanupObjects.end()); 12856 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12857 CleanupVarDeclMarking(); 12858 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12859 // Otherwise, merge the contexts together. 12860 } else { 12861 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12862 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12863 Rec.SavedMaybeODRUseExprs.end()); 12864 } 12865 12866 // Pop the current expression evaluation context off the stack. 12867 ExprEvalContexts.pop_back(); 12868 12869 if (!ExprEvalContexts.empty()) 12870 ExprEvalContexts.back().NumTypos += NumTypos; 12871 else 12872 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12873 "last ExpressionEvaluationContextRecord"); 12874 } 12875 12876 void Sema::DiscardCleanupsInEvaluationContext() { 12877 ExprCleanupObjects.erase( 12878 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12879 ExprCleanupObjects.end()); 12880 ExprNeedsCleanups = false; 12881 MaybeODRUseExprs.clear(); 12882 } 12883 12884 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12885 if (!E->getType()->isVariablyModifiedType()) 12886 return E; 12887 return TransformToPotentiallyEvaluated(E); 12888 } 12889 12890 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12891 // Do not mark anything as "used" within a dependent context; wait for 12892 // an instantiation. 12893 if (SemaRef.CurContext->isDependentContext()) 12894 return false; 12895 12896 switch (SemaRef.ExprEvalContexts.back().Context) { 12897 case Sema::Unevaluated: 12898 case Sema::UnevaluatedAbstract: 12899 // We are in an expression that is not potentially evaluated; do nothing. 12900 // (Depending on how you read the standard, we actually do need to do 12901 // something here for null pointer constants, but the standard's 12902 // definition of a null pointer constant is completely crazy.) 12903 return false; 12904 12905 case Sema::ConstantEvaluated: 12906 case Sema::PotentiallyEvaluated: 12907 // We are in a potentially evaluated expression (or a constant-expression 12908 // in C++03); we need to do implicit template instantiation, implicitly 12909 // define class members, and mark most declarations as used. 12910 return true; 12911 12912 case Sema::PotentiallyEvaluatedIfUsed: 12913 // Referenced declarations will only be used if the construct in the 12914 // containing expression is used. 12915 return false; 12916 } 12917 llvm_unreachable("Invalid context"); 12918 } 12919 12920 /// \brief Mark a function referenced, and check whether it is odr-used 12921 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12922 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12923 bool MightBeOdrUse) { 12924 assert(Func && "No function?"); 12925 12926 Func->setReferenced(); 12927 12928 // C++11 [basic.def.odr]p3: 12929 // A function whose name appears as a potentially-evaluated expression is 12930 // odr-used if it is the unique lookup result or the selected member of a 12931 // set of overloaded functions [...]. 12932 // 12933 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12934 // can just check that here. 12935 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 12936 12937 // Determine whether we require a function definition to exist, per 12938 // C++11 [temp.inst]p3: 12939 // Unless a function template specialization has been explicitly 12940 // instantiated or explicitly specialized, the function template 12941 // specialization is implicitly instantiated when the specialization is 12942 // referenced in a context that requires a function definition to exist. 12943 // 12944 // We consider constexpr function templates to be referenced in a context 12945 // that requires a definition to exist whenever they are referenced. 12946 // 12947 // FIXME: This instantiates constexpr functions too frequently. If this is 12948 // really an unevaluated context (and we're not just in the definition of a 12949 // function template or overload resolution or other cases which we 12950 // incorrectly consider to be unevaluated contexts), and we're not in a 12951 // subexpression which we actually need to evaluate (for instance, a 12952 // template argument, array bound or an expression in a braced-init-list), 12953 // we are not permitted to instantiate this constexpr function definition. 12954 // 12955 // FIXME: This also implicitly defines special members too frequently. They 12956 // are only supposed to be implicitly defined if they are odr-used, but they 12957 // are not odr-used from constant expressions in unevaluated contexts. 12958 // However, they cannot be referenced if they are deleted, and they are 12959 // deleted whenever the implicit definition of the special member would 12960 // fail (with very few exceptions). 12961 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12962 bool NeedDefinition = 12963 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 12964 (MD && !MD->isUserProvided()))); 12965 12966 // C++14 [temp.expl.spec]p6: 12967 // If a template [...] is explicitly specialized then that specialization 12968 // shall be declared before the first use of that specialization that would 12969 // cause an implicit instantiation to take place, in every translation unit 12970 // in which such a use occurs 12971 if (NeedDefinition && 12972 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 12973 Func->getMemberSpecializationInfo())) 12974 checkSpecializationVisibility(Loc, Func); 12975 12976 // If we don't need to mark the function as used, and we don't need to 12977 // try to provide a definition, there's nothing more to do. 12978 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 12979 (!NeedDefinition || Func->getBody())) 12980 return; 12981 12982 // Note that this declaration has been used. 12983 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12984 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12985 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12986 if (Constructor->isDefaultConstructor()) { 12987 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12988 return; 12989 DefineImplicitDefaultConstructor(Loc, Constructor); 12990 } else if (Constructor->isCopyConstructor()) { 12991 DefineImplicitCopyConstructor(Loc, Constructor); 12992 } else if (Constructor->isMoveConstructor()) { 12993 DefineImplicitMoveConstructor(Loc, Constructor); 12994 } 12995 } else if (Constructor->getInheritedConstructor()) { 12996 DefineInheritingConstructor(Loc, Constructor); 12997 } 12998 } else if (CXXDestructorDecl *Destructor = 12999 dyn_cast<CXXDestructorDecl>(Func)) { 13000 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13001 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13002 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13003 return; 13004 DefineImplicitDestructor(Loc, Destructor); 13005 } 13006 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13007 MarkVTableUsed(Loc, Destructor->getParent()); 13008 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13009 if (MethodDecl->isOverloadedOperator() && 13010 MethodDecl->getOverloadedOperator() == OO_Equal) { 13011 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13012 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13013 if (MethodDecl->isCopyAssignmentOperator()) 13014 DefineImplicitCopyAssignment(Loc, MethodDecl); 13015 else 13016 DefineImplicitMoveAssignment(Loc, MethodDecl); 13017 } 13018 } else if (isa<CXXConversionDecl>(MethodDecl) && 13019 MethodDecl->getParent()->isLambda()) { 13020 CXXConversionDecl *Conversion = 13021 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13022 if (Conversion->isLambdaToBlockPointerConversion()) 13023 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13024 else 13025 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13026 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13027 MarkVTableUsed(Loc, MethodDecl->getParent()); 13028 } 13029 13030 // Recursive functions should be marked when used from another function. 13031 // FIXME: Is this really right? 13032 if (CurContext == Func) return; 13033 13034 // Resolve the exception specification for any function which is 13035 // used: CodeGen will need it. 13036 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13037 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13038 ResolveExceptionSpec(Loc, FPT); 13039 13040 // Implicit instantiation of function templates and member functions of 13041 // class templates. 13042 if (Func->isImplicitlyInstantiable()) { 13043 bool AlreadyInstantiated = false; 13044 SourceLocation PointOfInstantiation = Loc; 13045 if (FunctionTemplateSpecializationInfo *SpecInfo 13046 = Func->getTemplateSpecializationInfo()) { 13047 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13048 SpecInfo->setPointOfInstantiation(Loc); 13049 else if (SpecInfo->getTemplateSpecializationKind() 13050 == TSK_ImplicitInstantiation) { 13051 AlreadyInstantiated = true; 13052 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13053 } 13054 } else if (MemberSpecializationInfo *MSInfo 13055 = Func->getMemberSpecializationInfo()) { 13056 if (MSInfo->getPointOfInstantiation().isInvalid()) 13057 MSInfo->setPointOfInstantiation(Loc); 13058 else if (MSInfo->getTemplateSpecializationKind() 13059 == TSK_ImplicitInstantiation) { 13060 AlreadyInstantiated = true; 13061 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13062 } 13063 } 13064 13065 if (!AlreadyInstantiated || Func->isConstexpr()) { 13066 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13067 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13068 ActiveTemplateInstantiations.size()) 13069 PendingLocalImplicitInstantiations.push_back( 13070 std::make_pair(Func, PointOfInstantiation)); 13071 else if (Func->isConstexpr()) 13072 // Do not defer instantiations of constexpr functions, to avoid the 13073 // expression evaluator needing to call back into Sema if it sees a 13074 // call to such a function. 13075 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13076 else { 13077 PendingInstantiations.push_back(std::make_pair(Func, 13078 PointOfInstantiation)); 13079 // Notify the consumer that a function was implicitly instantiated. 13080 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13081 } 13082 } 13083 } else { 13084 // Walk redefinitions, as some of them may be instantiable. 13085 for (auto i : Func->redecls()) { 13086 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13087 MarkFunctionReferenced(Loc, i, OdrUse); 13088 } 13089 } 13090 13091 if (!OdrUse) return; 13092 13093 // Keep track of used but undefined functions. 13094 if (!Func->isDefined()) { 13095 if (mightHaveNonExternalLinkage(Func)) 13096 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13097 else if (Func->getMostRecentDecl()->isInlined() && 13098 !LangOpts.GNUInline && 13099 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13100 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13101 } 13102 13103 Func->markUsed(Context); 13104 } 13105 13106 static void 13107 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13108 VarDecl *var, DeclContext *DC) { 13109 DeclContext *VarDC = var->getDeclContext(); 13110 13111 // If the parameter still belongs to the translation unit, then 13112 // we're actually just using one parameter in the declaration of 13113 // the next. 13114 if (isa<ParmVarDecl>(var) && 13115 isa<TranslationUnitDecl>(VarDC)) 13116 return; 13117 13118 // For C code, don't diagnose about capture if we're not actually in code 13119 // right now; it's impossible to write a non-constant expression outside of 13120 // function context, so we'll get other (more useful) diagnostics later. 13121 // 13122 // For C++, things get a bit more nasty... it would be nice to suppress this 13123 // diagnostic for certain cases like using a local variable in an array bound 13124 // for a member of a local class, but the correct predicate is not obvious. 13125 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13126 return; 13127 13128 if (isa<CXXMethodDecl>(VarDC) && 13129 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13130 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 13131 << var->getIdentifier(); 13132 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 13133 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 13134 << var->getIdentifier() << fn->getDeclName(); 13135 } else if (isa<BlockDecl>(VarDC)) { 13136 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 13137 << var->getIdentifier(); 13138 } else { 13139 // FIXME: Is there any other context where a local variable can be 13140 // declared? 13141 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 13142 << var->getIdentifier(); 13143 } 13144 13145 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13146 << var->getIdentifier(); 13147 13148 // FIXME: Add additional diagnostic info about class etc. which prevents 13149 // capture. 13150 } 13151 13152 13153 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13154 bool &SubCapturesAreNested, 13155 QualType &CaptureType, 13156 QualType &DeclRefType) { 13157 // Check whether we've already captured it. 13158 if (CSI->CaptureMap.count(Var)) { 13159 // If we found a capture, any subcaptures are nested. 13160 SubCapturesAreNested = true; 13161 13162 // Retrieve the capture type for this variable. 13163 CaptureType = CSI->getCapture(Var).getCaptureType(); 13164 13165 // Compute the type of an expression that refers to this variable. 13166 DeclRefType = CaptureType.getNonReferenceType(); 13167 13168 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13169 // are mutable in the sense that user can change their value - they are 13170 // private instances of the captured declarations. 13171 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13172 if (Cap.isCopyCapture() && 13173 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13174 !(isa<CapturedRegionScopeInfo>(CSI) && 13175 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13176 DeclRefType.addConst(); 13177 return true; 13178 } 13179 return false; 13180 } 13181 13182 // Only block literals, captured statements, and lambda expressions can 13183 // capture; other scopes don't work. 13184 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13185 SourceLocation Loc, 13186 const bool Diagnose, Sema &S) { 13187 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13188 return getLambdaAwareParentOfDeclContext(DC); 13189 else if (Var->hasLocalStorage()) { 13190 if (Diagnose) 13191 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13192 } 13193 return nullptr; 13194 } 13195 13196 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13197 // certain types of variables (unnamed, variably modified types etc.) 13198 // so check for eligibility. 13199 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13200 SourceLocation Loc, 13201 const bool Diagnose, Sema &S) { 13202 13203 bool IsBlock = isa<BlockScopeInfo>(CSI); 13204 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13205 13206 // Lambdas are not allowed to capture unnamed variables 13207 // (e.g. anonymous unions). 13208 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13209 // assuming that's the intent. 13210 if (IsLambda && !Var->getDeclName()) { 13211 if (Diagnose) { 13212 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13213 S.Diag(Var->getLocation(), diag::note_declared_at); 13214 } 13215 return false; 13216 } 13217 13218 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13219 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13220 if (Diagnose) { 13221 S.Diag(Loc, diag::err_ref_vm_type); 13222 S.Diag(Var->getLocation(), diag::note_previous_decl) 13223 << Var->getDeclName(); 13224 } 13225 return false; 13226 } 13227 // Prohibit structs with flexible array members too. 13228 // We cannot capture what is in the tail end of the struct. 13229 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13230 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13231 if (Diagnose) { 13232 if (IsBlock) 13233 S.Diag(Loc, diag::err_ref_flexarray_type); 13234 else 13235 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13236 << Var->getDeclName(); 13237 S.Diag(Var->getLocation(), diag::note_previous_decl) 13238 << Var->getDeclName(); 13239 } 13240 return false; 13241 } 13242 } 13243 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13244 // Lambdas and captured statements are not allowed to capture __block 13245 // variables; they don't support the expected semantics. 13246 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13247 if (Diagnose) { 13248 S.Diag(Loc, diag::err_capture_block_variable) 13249 << Var->getDeclName() << !IsLambda; 13250 S.Diag(Var->getLocation(), diag::note_previous_decl) 13251 << Var->getDeclName(); 13252 } 13253 return false; 13254 } 13255 13256 return true; 13257 } 13258 13259 // Returns true if the capture by block was successful. 13260 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13261 SourceLocation Loc, 13262 const bool BuildAndDiagnose, 13263 QualType &CaptureType, 13264 QualType &DeclRefType, 13265 const bool Nested, 13266 Sema &S) { 13267 Expr *CopyExpr = nullptr; 13268 bool ByRef = false; 13269 13270 // Blocks are not allowed to capture arrays. 13271 if (CaptureType->isArrayType()) { 13272 if (BuildAndDiagnose) { 13273 S.Diag(Loc, diag::err_ref_array_type); 13274 S.Diag(Var->getLocation(), diag::note_previous_decl) 13275 << Var->getDeclName(); 13276 } 13277 return false; 13278 } 13279 13280 // Forbid the block-capture of autoreleasing variables. 13281 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13282 if (BuildAndDiagnose) { 13283 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13284 << /*block*/ 0; 13285 S.Diag(Var->getLocation(), diag::note_previous_decl) 13286 << Var->getDeclName(); 13287 } 13288 return false; 13289 } 13290 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13291 if (HasBlocksAttr || CaptureType->isReferenceType() || 13292 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13293 // Block capture by reference does not change the capture or 13294 // declaration reference types. 13295 ByRef = true; 13296 } else { 13297 // Block capture by copy introduces 'const'. 13298 CaptureType = CaptureType.getNonReferenceType().withConst(); 13299 DeclRefType = CaptureType; 13300 13301 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13302 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13303 // The capture logic needs the destructor, so make sure we mark it. 13304 // Usually this is unnecessary because most local variables have 13305 // their destructors marked at declaration time, but parameters are 13306 // an exception because it's technically only the call site that 13307 // actually requires the destructor. 13308 if (isa<ParmVarDecl>(Var)) 13309 S.FinalizeVarWithDestructor(Var, Record); 13310 13311 // Enter a new evaluation context to insulate the copy 13312 // full-expression. 13313 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13314 13315 // According to the blocks spec, the capture of a variable from 13316 // the stack requires a const copy constructor. This is not true 13317 // of the copy/move done to move a __block variable to the heap. 13318 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13319 DeclRefType.withConst(), 13320 VK_LValue, Loc); 13321 13322 ExprResult Result 13323 = S.PerformCopyInitialization( 13324 InitializedEntity::InitializeBlock(Var->getLocation(), 13325 CaptureType, false), 13326 Loc, DeclRef); 13327 13328 // Build a full-expression copy expression if initialization 13329 // succeeded and used a non-trivial constructor. Recover from 13330 // errors by pretending that the copy isn't necessary. 13331 if (!Result.isInvalid() && 13332 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13333 ->isTrivial()) { 13334 Result = S.MaybeCreateExprWithCleanups(Result); 13335 CopyExpr = Result.get(); 13336 } 13337 } 13338 } 13339 } 13340 13341 // Actually capture the variable. 13342 if (BuildAndDiagnose) 13343 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13344 SourceLocation(), CaptureType, CopyExpr); 13345 13346 return true; 13347 13348 } 13349 13350 13351 /// \brief Capture the given variable in the captured region. 13352 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13353 VarDecl *Var, 13354 SourceLocation Loc, 13355 const bool BuildAndDiagnose, 13356 QualType &CaptureType, 13357 QualType &DeclRefType, 13358 const bool RefersToCapturedVariable, 13359 Sema &S) { 13360 // By default, capture variables by reference. 13361 bool ByRef = true; 13362 // Using an LValue reference type is consistent with Lambdas (see below). 13363 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13364 if (S.IsOpenMPCapturedDecl(Var)) 13365 DeclRefType = DeclRefType.getUnqualifiedType(); 13366 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13367 } 13368 13369 if (ByRef) 13370 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13371 else 13372 CaptureType = DeclRefType; 13373 13374 Expr *CopyExpr = nullptr; 13375 if (BuildAndDiagnose) { 13376 // The current implementation assumes that all variables are captured 13377 // by references. Since there is no capture by copy, no expression 13378 // evaluation will be needed. 13379 RecordDecl *RD = RSI->TheRecordDecl; 13380 13381 FieldDecl *Field 13382 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13383 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13384 nullptr, false, ICIS_NoInit); 13385 Field->setImplicit(true); 13386 Field->setAccess(AS_private); 13387 RD->addDecl(Field); 13388 13389 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13390 DeclRefType, VK_LValue, Loc); 13391 Var->setReferenced(true); 13392 Var->markUsed(S.Context); 13393 } 13394 13395 // Actually capture the variable. 13396 if (BuildAndDiagnose) 13397 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13398 SourceLocation(), CaptureType, CopyExpr); 13399 13400 13401 return true; 13402 } 13403 13404 /// \brief Create a field within the lambda class for the variable 13405 /// being captured. 13406 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13407 QualType FieldType, QualType DeclRefType, 13408 SourceLocation Loc, 13409 bool RefersToCapturedVariable) { 13410 CXXRecordDecl *Lambda = LSI->Lambda; 13411 13412 // Build the non-static data member. 13413 FieldDecl *Field 13414 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13415 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13416 nullptr, false, ICIS_NoInit); 13417 Field->setImplicit(true); 13418 Field->setAccess(AS_private); 13419 Lambda->addDecl(Field); 13420 } 13421 13422 /// \brief Capture the given variable in the lambda. 13423 static bool captureInLambda(LambdaScopeInfo *LSI, 13424 VarDecl *Var, 13425 SourceLocation Loc, 13426 const bool BuildAndDiagnose, 13427 QualType &CaptureType, 13428 QualType &DeclRefType, 13429 const bool RefersToCapturedVariable, 13430 const Sema::TryCaptureKind Kind, 13431 SourceLocation EllipsisLoc, 13432 const bool IsTopScope, 13433 Sema &S) { 13434 13435 // Determine whether we are capturing by reference or by value. 13436 bool ByRef = false; 13437 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13438 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13439 } else { 13440 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13441 } 13442 13443 // Compute the type of the field that will capture this variable. 13444 if (ByRef) { 13445 // C++11 [expr.prim.lambda]p15: 13446 // An entity is captured by reference if it is implicitly or 13447 // explicitly captured but not captured by copy. It is 13448 // unspecified whether additional unnamed non-static data 13449 // members are declared in the closure type for entities 13450 // captured by reference. 13451 // 13452 // FIXME: It is not clear whether we want to build an lvalue reference 13453 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13454 // to do the former, while EDG does the latter. Core issue 1249 will 13455 // clarify, but for now we follow GCC because it's a more permissive and 13456 // easily defensible position. 13457 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13458 } else { 13459 // C++11 [expr.prim.lambda]p14: 13460 // For each entity captured by copy, an unnamed non-static 13461 // data member is declared in the closure type. The 13462 // declaration order of these members is unspecified. The type 13463 // of such a data member is the type of the corresponding 13464 // captured entity if the entity is not a reference to an 13465 // object, or the referenced type otherwise. [Note: If the 13466 // captured entity is a reference to a function, the 13467 // corresponding data member is also a reference to a 13468 // function. - end note ] 13469 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13470 if (!RefType->getPointeeType()->isFunctionType()) 13471 CaptureType = RefType->getPointeeType(); 13472 } 13473 13474 // Forbid the lambda copy-capture of autoreleasing variables. 13475 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13476 if (BuildAndDiagnose) { 13477 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13478 S.Diag(Var->getLocation(), diag::note_previous_decl) 13479 << Var->getDeclName(); 13480 } 13481 return false; 13482 } 13483 13484 // Make sure that by-copy captures are of a complete and non-abstract type. 13485 if (BuildAndDiagnose) { 13486 if (!CaptureType->isDependentType() && 13487 S.RequireCompleteType(Loc, CaptureType, 13488 diag::err_capture_of_incomplete_type, 13489 Var->getDeclName())) 13490 return false; 13491 13492 if (S.RequireNonAbstractType(Loc, CaptureType, 13493 diag::err_capture_of_abstract_type)) 13494 return false; 13495 } 13496 } 13497 13498 // Capture this variable in the lambda. 13499 if (BuildAndDiagnose) 13500 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13501 RefersToCapturedVariable); 13502 13503 // Compute the type of a reference to this captured variable. 13504 if (ByRef) 13505 DeclRefType = CaptureType.getNonReferenceType(); 13506 else { 13507 // C++ [expr.prim.lambda]p5: 13508 // The closure type for a lambda-expression has a public inline 13509 // function call operator [...]. This function call operator is 13510 // declared const (9.3.1) if and only if the lambda-expression’s 13511 // parameter-declaration-clause is not followed by mutable. 13512 DeclRefType = CaptureType.getNonReferenceType(); 13513 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13514 DeclRefType.addConst(); 13515 } 13516 13517 // Add the capture. 13518 if (BuildAndDiagnose) 13519 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13520 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13521 13522 return true; 13523 } 13524 13525 bool Sema::tryCaptureVariable( 13526 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13527 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13528 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13529 // An init-capture is notionally from the context surrounding its 13530 // declaration, but its parent DC is the lambda class. 13531 DeclContext *VarDC = Var->getDeclContext(); 13532 if (Var->isInitCapture()) 13533 VarDC = VarDC->getParent(); 13534 13535 DeclContext *DC = CurContext; 13536 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13537 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13538 // We need to sync up the Declaration Context with the 13539 // FunctionScopeIndexToStopAt 13540 if (FunctionScopeIndexToStopAt) { 13541 unsigned FSIndex = FunctionScopes.size() - 1; 13542 while (FSIndex != MaxFunctionScopesIndex) { 13543 DC = getLambdaAwareParentOfDeclContext(DC); 13544 --FSIndex; 13545 } 13546 } 13547 13548 13549 // If the variable is declared in the current context, there is no need to 13550 // capture it. 13551 if (VarDC == DC) return true; 13552 13553 // Capture global variables if it is required to use private copy of this 13554 // variable. 13555 bool IsGlobal = !Var->hasLocalStorage(); 13556 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13557 return true; 13558 13559 // Walk up the stack to determine whether we can capture the variable, 13560 // performing the "simple" checks that don't depend on type. We stop when 13561 // we've either hit the declared scope of the variable or find an existing 13562 // capture of that variable. We start from the innermost capturing-entity 13563 // (the DC) and ensure that all intervening capturing-entities 13564 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13565 // declcontext can either capture the variable or have already captured 13566 // the variable. 13567 CaptureType = Var->getType(); 13568 DeclRefType = CaptureType.getNonReferenceType(); 13569 bool Nested = false; 13570 bool Explicit = (Kind != TryCapture_Implicit); 13571 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13572 do { 13573 // Only block literals, captured statements, and lambda expressions can 13574 // capture; other scopes don't work. 13575 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13576 ExprLoc, 13577 BuildAndDiagnose, 13578 *this); 13579 // We need to check for the parent *first* because, if we *have* 13580 // private-captured a global variable, we need to recursively capture it in 13581 // intermediate blocks, lambdas, etc. 13582 if (!ParentDC) { 13583 if (IsGlobal) { 13584 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13585 break; 13586 } 13587 return true; 13588 } 13589 13590 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13591 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13592 13593 13594 // Check whether we've already captured it. 13595 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13596 DeclRefType)) 13597 break; 13598 // If we are instantiating a generic lambda call operator body, 13599 // we do not want to capture new variables. What was captured 13600 // during either a lambdas transformation or initial parsing 13601 // should be used. 13602 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13603 if (BuildAndDiagnose) { 13604 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13605 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13606 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13607 Diag(Var->getLocation(), diag::note_previous_decl) 13608 << Var->getDeclName(); 13609 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13610 } else 13611 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13612 } 13613 return true; 13614 } 13615 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13616 // certain types of variables (unnamed, variably modified types etc.) 13617 // so check for eligibility. 13618 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13619 return true; 13620 13621 // Try to capture variable-length arrays types. 13622 if (Var->getType()->isVariablyModifiedType()) { 13623 // We're going to walk down into the type and look for VLA 13624 // expressions. 13625 QualType QTy = Var->getType(); 13626 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13627 QTy = PVD->getOriginalType(); 13628 captureVariablyModifiedType(Context, QTy, CSI); 13629 } 13630 13631 if (getLangOpts().OpenMP) { 13632 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13633 // OpenMP private variables should not be captured in outer scope, so 13634 // just break here. Similarly, global variables that are captured in a 13635 // target region should not be captured outside the scope of the region. 13636 if (RSI->CapRegionKind == CR_OpenMP) { 13637 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13638 // When we detect target captures we are looking from inside the 13639 // target region, therefore we need to propagate the capture from the 13640 // enclosing region. Therefore, the capture is not initially nested. 13641 if (IsTargetCap) 13642 FunctionScopesIndex--; 13643 13644 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13645 Nested = !IsTargetCap; 13646 DeclRefType = DeclRefType.getUnqualifiedType(); 13647 CaptureType = Context.getLValueReferenceType(DeclRefType); 13648 break; 13649 } 13650 } 13651 } 13652 } 13653 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13654 // No capture-default, and this is not an explicit capture 13655 // so cannot capture this variable. 13656 if (BuildAndDiagnose) { 13657 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13658 Diag(Var->getLocation(), diag::note_previous_decl) 13659 << Var->getDeclName(); 13660 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13661 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13662 diag::note_lambda_decl); 13663 // FIXME: If we error out because an outer lambda can not implicitly 13664 // capture a variable that an inner lambda explicitly captures, we 13665 // should have the inner lambda do the explicit capture - because 13666 // it makes for cleaner diagnostics later. This would purely be done 13667 // so that the diagnostic does not misleadingly claim that a variable 13668 // can not be captured by a lambda implicitly even though it is captured 13669 // explicitly. Suggestion: 13670 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13671 // at the function head 13672 // - cache the StartingDeclContext - this must be a lambda 13673 // - captureInLambda in the innermost lambda the variable. 13674 } 13675 return true; 13676 } 13677 13678 FunctionScopesIndex--; 13679 DC = ParentDC; 13680 Explicit = false; 13681 } while (!VarDC->Equals(DC)); 13682 13683 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13684 // computing the type of the capture at each step, checking type-specific 13685 // requirements, and adding captures if requested. 13686 // If the variable had already been captured previously, we start capturing 13687 // at the lambda nested within that one. 13688 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13689 ++I) { 13690 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13691 13692 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13693 if (!captureInBlock(BSI, Var, ExprLoc, 13694 BuildAndDiagnose, CaptureType, 13695 DeclRefType, Nested, *this)) 13696 return true; 13697 Nested = true; 13698 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13699 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13700 BuildAndDiagnose, CaptureType, 13701 DeclRefType, Nested, *this)) 13702 return true; 13703 Nested = true; 13704 } else { 13705 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13706 if (!captureInLambda(LSI, Var, ExprLoc, 13707 BuildAndDiagnose, CaptureType, 13708 DeclRefType, Nested, Kind, EllipsisLoc, 13709 /*IsTopScope*/I == N - 1, *this)) 13710 return true; 13711 Nested = true; 13712 } 13713 } 13714 return false; 13715 } 13716 13717 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13718 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13719 QualType CaptureType; 13720 QualType DeclRefType; 13721 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13722 /*BuildAndDiagnose=*/true, CaptureType, 13723 DeclRefType, nullptr); 13724 } 13725 13726 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13727 QualType CaptureType; 13728 QualType DeclRefType; 13729 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13730 /*BuildAndDiagnose=*/false, CaptureType, 13731 DeclRefType, nullptr); 13732 } 13733 13734 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13735 QualType CaptureType; 13736 QualType DeclRefType; 13737 13738 // Determine whether we can capture this variable. 13739 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13740 /*BuildAndDiagnose=*/false, CaptureType, 13741 DeclRefType, nullptr)) 13742 return QualType(); 13743 13744 return DeclRefType; 13745 } 13746 13747 13748 13749 // If either the type of the variable or the initializer is dependent, 13750 // return false. Otherwise, determine whether the variable is a constant 13751 // expression. Use this if you need to know if a variable that might or 13752 // might not be dependent is truly a constant expression. 13753 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13754 ASTContext &Context) { 13755 13756 if (Var->getType()->isDependentType()) 13757 return false; 13758 const VarDecl *DefVD = nullptr; 13759 Var->getAnyInitializer(DefVD); 13760 if (!DefVD) 13761 return false; 13762 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13763 Expr *Init = cast<Expr>(Eval->Value); 13764 if (Init->isValueDependent()) 13765 return false; 13766 return IsVariableAConstantExpression(Var, Context); 13767 } 13768 13769 13770 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13771 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13772 // an object that satisfies the requirements for appearing in a 13773 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13774 // is immediately applied." This function handles the lvalue-to-rvalue 13775 // conversion part. 13776 MaybeODRUseExprs.erase(E->IgnoreParens()); 13777 13778 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13779 // to a variable that is a constant expression, and if so, identify it as 13780 // a reference to a variable that does not involve an odr-use of that 13781 // variable. 13782 if (LambdaScopeInfo *LSI = getCurLambda()) { 13783 Expr *SansParensExpr = E->IgnoreParens(); 13784 VarDecl *Var = nullptr; 13785 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13786 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13787 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13788 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13789 13790 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13791 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13792 } 13793 } 13794 13795 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13796 Res = CorrectDelayedTyposInExpr(Res); 13797 13798 if (!Res.isUsable()) 13799 return Res; 13800 13801 // If a constant-expression is a reference to a variable where we delay 13802 // deciding whether it is an odr-use, just assume we will apply the 13803 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13804 // (a non-type template argument), we have special handling anyway. 13805 UpdateMarkingForLValueToRValue(Res.get()); 13806 return Res; 13807 } 13808 13809 void Sema::CleanupVarDeclMarking() { 13810 for (Expr *E : MaybeODRUseExprs) { 13811 VarDecl *Var; 13812 SourceLocation Loc; 13813 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13814 Var = cast<VarDecl>(DRE->getDecl()); 13815 Loc = DRE->getLocation(); 13816 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13817 Var = cast<VarDecl>(ME->getMemberDecl()); 13818 Loc = ME->getMemberLoc(); 13819 } else { 13820 llvm_unreachable("Unexpected expression"); 13821 } 13822 13823 MarkVarDeclODRUsed(Var, Loc, *this, 13824 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13825 } 13826 13827 MaybeODRUseExprs.clear(); 13828 } 13829 13830 13831 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13832 VarDecl *Var, Expr *E) { 13833 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13834 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13835 Var->setReferenced(); 13836 13837 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13838 bool MarkODRUsed = true; 13839 13840 // If the context is not potentially evaluated, this is not an odr-use and 13841 // does not trigger instantiation. 13842 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13843 if (SemaRef.isUnevaluatedContext()) 13844 return; 13845 13846 // If we don't yet know whether this context is going to end up being an 13847 // evaluated context, and we're referencing a variable from an enclosing 13848 // scope, add a potential capture. 13849 // 13850 // FIXME: Is this necessary? These contexts are only used for default 13851 // arguments, where local variables can't be used. 13852 const bool RefersToEnclosingScope = 13853 (SemaRef.CurContext != Var->getDeclContext() && 13854 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13855 if (RefersToEnclosingScope) { 13856 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13857 // If a variable could potentially be odr-used, defer marking it so 13858 // until we finish analyzing the full expression for any 13859 // lvalue-to-rvalue 13860 // or discarded value conversions that would obviate odr-use. 13861 // Add it to the list of potential captures that will be analyzed 13862 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13863 // unless the variable is a reference that was initialized by a constant 13864 // expression (this will never need to be captured or odr-used). 13865 assert(E && "Capture variable should be used in an expression."); 13866 if (!Var->getType()->isReferenceType() || 13867 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13868 LSI->addPotentialCapture(E->IgnoreParens()); 13869 } 13870 } 13871 13872 if (!isTemplateInstantiation(TSK)) 13873 return; 13874 13875 // Instantiate, but do not mark as odr-used, variable templates. 13876 MarkODRUsed = false; 13877 } 13878 13879 VarTemplateSpecializationDecl *VarSpec = 13880 dyn_cast<VarTemplateSpecializationDecl>(Var); 13881 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13882 "Can't instantiate a partial template specialization."); 13883 13884 // If this might be a member specialization of a static data member, check 13885 // the specialization is visible. We already did the checks for variable 13886 // template specializations when we created them. 13887 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 13888 SemaRef.checkSpecializationVisibility(Loc, Var); 13889 13890 // Perform implicit instantiation of static data members, static data member 13891 // templates of class templates, and variable template specializations. Delay 13892 // instantiations of variable templates, except for those that could be used 13893 // in a constant expression. 13894 if (isTemplateInstantiation(TSK)) { 13895 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13896 13897 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13898 if (Var->getPointOfInstantiation().isInvalid()) { 13899 // This is a modification of an existing AST node. Notify listeners. 13900 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13901 L->StaticDataMemberInstantiated(Var); 13902 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13903 // Don't bother trying to instantiate it again, unless we might need 13904 // its initializer before we get to the end of the TU. 13905 TryInstantiating = false; 13906 } 13907 13908 if (Var->getPointOfInstantiation().isInvalid()) 13909 Var->setTemplateSpecializationKind(TSK, Loc); 13910 13911 if (TryInstantiating) { 13912 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13913 bool InstantiationDependent = false; 13914 bool IsNonDependent = 13915 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13916 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13917 : true; 13918 13919 // Do not instantiate specializations that are still type-dependent. 13920 if (IsNonDependent) { 13921 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13922 // Do not defer instantiations of variables which could be used in a 13923 // constant expression. 13924 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13925 } else { 13926 SemaRef.PendingInstantiations 13927 .push_back(std::make_pair(Var, PointOfInstantiation)); 13928 } 13929 } 13930 } 13931 } 13932 13933 if (!MarkODRUsed) 13934 return; 13935 13936 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13937 // the requirements for appearing in a constant expression (5.19) and, if 13938 // it is an object, the lvalue-to-rvalue conversion (4.1) 13939 // is immediately applied." We check the first part here, and 13940 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13941 // Note that we use the C++11 definition everywhere because nothing in 13942 // C++03 depends on whether we get the C++03 version correct. The second 13943 // part does not apply to references, since they are not objects. 13944 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13945 // A reference initialized by a constant expression can never be 13946 // odr-used, so simply ignore it. 13947 if (!Var->getType()->isReferenceType()) 13948 SemaRef.MaybeODRUseExprs.insert(E); 13949 } else 13950 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13951 /*MaxFunctionScopeIndex ptr*/ nullptr); 13952 } 13953 13954 /// \brief Mark a variable referenced, and check whether it is odr-used 13955 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13956 /// used directly for normal expressions referring to VarDecl. 13957 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13958 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13959 } 13960 13961 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13962 Decl *D, Expr *E, bool MightBeOdrUse) { 13963 if (SemaRef.isInOpenMPDeclareTargetContext()) 13964 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 13965 13966 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13967 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13968 return; 13969 } 13970 13971 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 13972 13973 // If this is a call to a method via a cast, also mark the method in the 13974 // derived class used in case codegen can devirtualize the call. 13975 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13976 if (!ME) 13977 return; 13978 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13979 if (!MD) 13980 return; 13981 // Only attempt to devirtualize if this is truly a virtual call. 13982 bool IsVirtualCall = MD->isVirtual() && 13983 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13984 if (!IsVirtualCall) 13985 return; 13986 const Expr *Base = ME->getBase(); 13987 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13988 if (!MostDerivedClassDecl) 13989 return; 13990 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13991 if (!DM || DM->isPure()) 13992 return; 13993 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 13994 } 13995 13996 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13997 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13998 // TODO: update this with DR# once a defect report is filed. 13999 // C++11 defect. The address of a pure member should not be an ODR use, even 14000 // if it's a qualified reference. 14001 bool OdrUse = true; 14002 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14003 if (Method->isVirtual()) 14004 OdrUse = false; 14005 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14006 } 14007 14008 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14009 void Sema::MarkMemberReferenced(MemberExpr *E) { 14010 // C++11 [basic.def.odr]p2: 14011 // A non-overloaded function whose name appears as a potentially-evaluated 14012 // expression or a member of a set of candidate functions, if selected by 14013 // overload resolution when referred to from a potentially-evaluated 14014 // expression, is odr-used, unless it is a pure virtual function and its 14015 // name is not explicitly qualified. 14016 bool MightBeOdrUse = true; 14017 if (E->performsVirtualDispatch(getLangOpts())) { 14018 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14019 if (Method->isPure()) 14020 MightBeOdrUse = false; 14021 } 14022 SourceLocation Loc = E->getMemberLoc().isValid() ? 14023 E->getMemberLoc() : E->getLocStart(); 14024 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14025 } 14026 14027 /// \brief Perform marking for a reference to an arbitrary declaration. It 14028 /// marks the declaration referenced, and performs odr-use checking for 14029 /// functions and variables. This method should not be used when building a 14030 /// normal expression which refers to a variable. 14031 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14032 bool MightBeOdrUse) { 14033 if (MightBeOdrUse) { 14034 if (auto *VD = dyn_cast<VarDecl>(D)) { 14035 MarkVariableReferenced(Loc, VD); 14036 return; 14037 } 14038 } 14039 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14040 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14041 return; 14042 } 14043 D->setReferenced(); 14044 } 14045 14046 namespace { 14047 // Mark all of the declarations referenced 14048 // FIXME: Not fully implemented yet! We need to have a better understanding 14049 // of when we're entering 14050 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14051 Sema &S; 14052 SourceLocation Loc; 14053 14054 public: 14055 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14056 14057 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14058 14059 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14060 bool TraverseRecordType(RecordType *T); 14061 }; 14062 } 14063 14064 bool MarkReferencedDecls::TraverseTemplateArgument( 14065 const TemplateArgument &Arg) { 14066 if (Arg.getKind() == TemplateArgument::Declaration) { 14067 if (Decl *D = Arg.getAsDecl()) 14068 S.MarkAnyDeclReferenced(Loc, D, true); 14069 } 14070 14071 return Inherited::TraverseTemplateArgument(Arg); 14072 } 14073 14074 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14075 if (ClassTemplateSpecializationDecl *Spec 14076 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14077 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14078 return TraverseTemplateArguments(Args.data(), Args.size()); 14079 } 14080 14081 return true; 14082 } 14083 14084 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14085 MarkReferencedDecls Marker(*this, Loc); 14086 Marker.TraverseType(Context.getCanonicalType(T)); 14087 } 14088 14089 namespace { 14090 /// \brief Helper class that marks all of the declarations referenced by 14091 /// potentially-evaluated subexpressions as "referenced". 14092 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14093 Sema &S; 14094 bool SkipLocalVariables; 14095 14096 public: 14097 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14098 14099 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14100 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14101 14102 void VisitDeclRefExpr(DeclRefExpr *E) { 14103 // If we were asked not to visit local variables, don't. 14104 if (SkipLocalVariables) { 14105 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14106 if (VD->hasLocalStorage()) 14107 return; 14108 } 14109 14110 S.MarkDeclRefReferenced(E); 14111 } 14112 14113 void VisitMemberExpr(MemberExpr *E) { 14114 S.MarkMemberReferenced(E); 14115 Inherited::VisitMemberExpr(E); 14116 } 14117 14118 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14119 S.MarkFunctionReferenced(E->getLocStart(), 14120 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14121 Visit(E->getSubExpr()); 14122 } 14123 14124 void VisitCXXNewExpr(CXXNewExpr *E) { 14125 if (E->getOperatorNew()) 14126 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14127 if (E->getOperatorDelete()) 14128 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14129 Inherited::VisitCXXNewExpr(E); 14130 } 14131 14132 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14133 if (E->getOperatorDelete()) 14134 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14135 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14136 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14137 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14138 S.MarkFunctionReferenced(E->getLocStart(), 14139 S.LookupDestructor(Record)); 14140 } 14141 14142 Inherited::VisitCXXDeleteExpr(E); 14143 } 14144 14145 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14146 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14147 Inherited::VisitCXXConstructExpr(E); 14148 } 14149 14150 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14151 Visit(E->getExpr()); 14152 } 14153 14154 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14155 Inherited::VisitImplicitCastExpr(E); 14156 14157 if (E->getCastKind() == CK_LValueToRValue) 14158 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14159 } 14160 }; 14161 } 14162 14163 /// \brief Mark any declarations that appear within this expression or any 14164 /// potentially-evaluated subexpressions as "referenced". 14165 /// 14166 /// \param SkipLocalVariables If true, don't mark local variables as 14167 /// 'referenced'. 14168 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14169 bool SkipLocalVariables) { 14170 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14171 } 14172 14173 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14174 /// of the program being compiled. 14175 /// 14176 /// This routine emits the given diagnostic when the code currently being 14177 /// type-checked is "potentially evaluated", meaning that there is a 14178 /// possibility that the code will actually be executable. Code in sizeof() 14179 /// expressions, code used only during overload resolution, etc., are not 14180 /// potentially evaluated. This routine will suppress such diagnostics or, 14181 /// in the absolutely nutty case of potentially potentially evaluated 14182 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14183 /// later. 14184 /// 14185 /// This routine should be used for all diagnostics that describe the run-time 14186 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14187 /// Failure to do so will likely result in spurious diagnostics or failures 14188 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14189 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14190 const PartialDiagnostic &PD) { 14191 switch (ExprEvalContexts.back().Context) { 14192 case Unevaluated: 14193 case UnevaluatedAbstract: 14194 // The argument will never be evaluated, so don't complain. 14195 break; 14196 14197 case ConstantEvaluated: 14198 // Relevant diagnostics should be produced by constant evaluation. 14199 break; 14200 14201 case PotentiallyEvaluated: 14202 case PotentiallyEvaluatedIfUsed: 14203 if (Statement && getCurFunctionOrMethodDecl()) { 14204 FunctionScopes.back()->PossiblyUnreachableDiags. 14205 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14206 } 14207 else 14208 Diag(Loc, PD); 14209 14210 return true; 14211 } 14212 14213 return false; 14214 } 14215 14216 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14217 CallExpr *CE, FunctionDecl *FD) { 14218 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14219 return false; 14220 14221 // If we're inside a decltype's expression, don't check for a valid return 14222 // type or construct temporaries until we know whether this is the last call. 14223 if (ExprEvalContexts.back().IsDecltype) { 14224 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14225 return false; 14226 } 14227 14228 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14229 FunctionDecl *FD; 14230 CallExpr *CE; 14231 14232 public: 14233 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14234 : FD(FD), CE(CE) { } 14235 14236 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14237 if (!FD) { 14238 S.Diag(Loc, diag::err_call_incomplete_return) 14239 << T << CE->getSourceRange(); 14240 return; 14241 } 14242 14243 S.Diag(Loc, diag::err_call_function_incomplete_return) 14244 << CE->getSourceRange() << FD->getDeclName() << T; 14245 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14246 << FD->getDeclName(); 14247 } 14248 } Diagnoser(FD, CE); 14249 14250 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14251 return true; 14252 14253 return false; 14254 } 14255 14256 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14257 // will prevent this condition from triggering, which is what we want. 14258 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14259 SourceLocation Loc; 14260 14261 unsigned diagnostic = diag::warn_condition_is_assignment; 14262 bool IsOrAssign = false; 14263 14264 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14265 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14266 return; 14267 14268 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14269 14270 // Greylist some idioms by putting them into a warning subcategory. 14271 if (ObjCMessageExpr *ME 14272 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14273 Selector Sel = ME->getSelector(); 14274 14275 // self = [<foo> init...] 14276 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14277 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14278 14279 // <foo> = [<bar> nextObject] 14280 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14281 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14282 } 14283 14284 Loc = Op->getOperatorLoc(); 14285 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14286 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14287 return; 14288 14289 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14290 Loc = Op->getOperatorLoc(); 14291 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14292 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14293 else { 14294 // Not an assignment. 14295 return; 14296 } 14297 14298 Diag(Loc, diagnostic) << E->getSourceRange(); 14299 14300 SourceLocation Open = E->getLocStart(); 14301 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14302 Diag(Loc, diag::note_condition_assign_silence) 14303 << FixItHint::CreateInsertion(Open, "(") 14304 << FixItHint::CreateInsertion(Close, ")"); 14305 14306 if (IsOrAssign) 14307 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14308 << FixItHint::CreateReplacement(Loc, "!="); 14309 else 14310 Diag(Loc, diag::note_condition_assign_to_comparison) 14311 << FixItHint::CreateReplacement(Loc, "=="); 14312 } 14313 14314 /// \brief Redundant parentheses over an equality comparison can indicate 14315 /// that the user intended an assignment used as condition. 14316 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14317 // Don't warn if the parens came from a macro. 14318 SourceLocation parenLoc = ParenE->getLocStart(); 14319 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14320 return; 14321 // Don't warn for dependent expressions. 14322 if (ParenE->isTypeDependent()) 14323 return; 14324 14325 Expr *E = ParenE->IgnoreParens(); 14326 14327 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14328 if (opE->getOpcode() == BO_EQ && 14329 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14330 == Expr::MLV_Valid) { 14331 SourceLocation Loc = opE->getOperatorLoc(); 14332 14333 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14334 SourceRange ParenERange = ParenE->getSourceRange(); 14335 Diag(Loc, diag::note_equality_comparison_silence) 14336 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14337 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14338 Diag(Loc, diag::note_equality_comparison_to_assign) 14339 << FixItHint::CreateReplacement(Loc, "="); 14340 } 14341 } 14342 14343 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 14344 DiagnoseAssignmentAsCondition(E); 14345 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14346 DiagnoseEqualityWithExtraParens(parenE); 14347 14348 ExprResult result = CheckPlaceholderExpr(E); 14349 if (result.isInvalid()) return ExprError(); 14350 E = result.get(); 14351 14352 if (!E->isTypeDependent()) { 14353 if (getLangOpts().CPlusPlus) 14354 return CheckCXXBooleanCondition(E); // C++ 6.4p4 14355 14356 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14357 if (ERes.isInvalid()) 14358 return ExprError(); 14359 E = ERes.get(); 14360 14361 QualType T = E->getType(); 14362 if (!T->isScalarType()) { // C99 6.8.4.1p1 14363 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14364 << T << E->getSourceRange(); 14365 return ExprError(); 14366 } 14367 CheckBoolLikeConversion(E, Loc); 14368 } 14369 14370 return E; 14371 } 14372 14373 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 14374 Expr *SubExpr) { 14375 if (!SubExpr) 14376 return ExprError(); 14377 14378 return CheckBooleanCondition(SubExpr, Loc); 14379 } 14380 14381 namespace { 14382 /// A visitor for rebuilding a call to an __unknown_any expression 14383 /// to have an appropriate type. 14384 struct RebuildUnknownAnyFunction 14385 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14386 14387 Sema &S; 14388 14389 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14390 14391 ExprResult VisitStmt(Stmt *S) { 14392 llvm_unreachable("unexpected statement!"); 14393 } 14394 14395 ExprResult VisitExpr(Expr *E) { 14396 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14397 << E->getSourceRange(); 14398 return ExprError(); 14399 } 14400 14401 /// Rebuild an expression which simply semantically wraps another 14402 /// expression which it shares the type and value kind of. 14403 template <class T> ExprResult rebuildSugarExpr(T *E) { 14404 ExprResult SubResult = Visit(E->getSubExpr()); 14405 if (SubResult.isInvalid()) return ExprError(); 14406 14407 Expr *SubExpr = SubResult.get(); 14408 E->setSubExpr(SubExpr); 14409 E->setType(SubExpr->getType()); 14410 E->setValueKind(SubExpr->getValueKind()); 14411 assert(E->getObjectKind() == OK_Ordinary); 14412 return E; 14413 } 14414 14415 ExprResult VisitParenExpr(ParenExpr *E) { 14416 return rebuildSugarExpr(E); 14417 } 14418 14419 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14420 return rebuildSugarExpr(E); 14421 } 14422 14423 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14424 ExprResult SubResult = Visit(E->getSubExpr()); 14425 if (SubResult.isInvalid()) return ExprError(); 14426 14427 Expr *SubExpr = SubResult.get(); 14428 E->setSubExpr(SubExpr); 14429 E->setType(S.Context.getPointerType(SubExpr->getType())); 14430 assert(E->getValueKind() == VK_RValue); 14431 assert(E->getObjectKind() == OK_Ordinary); 14432 return E; 14433 } 14434 14435 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14436 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14437 14438 E->setType(VD->getType()); 14439 14440 assert(E->getValueKind() == VK_RValue); 14441 if (S.getLangOpts().CPlusPlus && 14442 !(isa<CXXMethodDecl>(VD) && 14443 cast<CXXMethodDecl>(VD)->isInstance())) 14444 E->setValueKind(VK_LValue); 14445 14446 return E; 14447 } 14448 14449 ExprResult VisitMemberExpr(MemberExpr *E) { 14450 return resolveDecl(E, E->getMemberDecl()); 14451 } 14452 14453 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14454 return resolveDecl(E, E->getDecl()); 14455 } 14456 }; 14457 } 14458 14459 /// Given a function expression of unknown-any type, try to rebuild it 14460 /// to have a function type. 14461 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14462 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14463 if (Result.isInvalid()) return ExprError(); 14464 return S.DefaultFunctionArrayConversion(Result.get()); 14465 } 14466 14467 namespace { 14468 /// A visitor for rebuilding an expression of type __unknown_anytype 14469 /// into one which resolves the type directly on the referring 14470 /// expression. Strict preservation of the original source 14471 /// structure is not a goal. 14472 struct RebuildUnknownAnyExpr 14473 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14474 14475 Sema &S; 14476 14477 /// The current destination type. 14478 QualType DestType; 14479 14480 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14481 : S(S), DestType(CastType) {} 14482 14483 ExprResult VisitStmt(Stmt *S) { 14484 llvm_unreachable("unexpected statement!"); 14485 } 14486 14487 ExprResult VisitExpr(Expr *E) { 14488 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14489 << E->getSourceRange(); 14490 return ExprError(); 14491 } 14492 14493 ExprResult VisitCallExpr(CallExpr *E); 14494 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14495 14496 /// Rebuild an expression which simply semantically wraps another 14497 /// expression which it shares the type and value kind of. 14498 template <class T> ExprResult rebuildSugarExpr(T *E) { 14499 ExprResult SubResult = Visit(E->getSubExpr()); 14500 if (SubResult.isInvalid()) return ExprError(); 14501 Expr *SubExpr = SubResult.get(); 14502 E->setSubExpr(SubExpr); 14503 E->setType(SubExpr->getType()); 14504 E->setValueKind(SubExpr->getValueKind()); 14505 assert(E->getObjectKind() == OK_Ordinary); 14506 return E; 14507 } 14508 14509 ExprResult VisitParenExpr(ParenExpr *E) { 14510 return rebuildSugarExpr(E); 14511 } 14512 14513 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14514 return rebuildSugarExpr(E); 14515 } 14516 14517 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14518 const PointerType *Ptr = DestType->getAs<PointerType>(); 14519 if (!Ptr) { 14520 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14521 << E->getSourceRange(); 14522 return ExprError(); 14523 } 14524 assert(E->getValueKind() == VK_RValue); 14525 assert(E->getObjectKind() == OK_Ordinary); 14526 E->setType(DestType); 14527 14528 // Build the sub-expression as if it were an object of the pointee type. 14529 DestType = Ptr->getPointeeType(); 14530 ExprResult SubResult = Visit(E->getSubExpr()); 14531 if (SubResult.isInvalid()) return ExprError(); 14532 E->setSubExpr(SubResult.get()); 14533 return E; 14534 } 14535 14536 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14537 14538 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14539 14540 ExprResult VisitMemberExpr(MemberExpr *E) { 14541 return resolveDecl(E, E->getMemberDecl()); 14542 } 14543 14544 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14545 return resolveDecl(E, E->getDecl()); 14546 } 14547 }; 14548 } 14549 14550 /// Rebuilds a call expression which yielded __unknown_anytype. 14551 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14552 Expr *CalleeExpr = E->getCallee(); 14553 14554 enum FnKind { 14555 FK_MemberFunction, 14556 FK_FunctionPointer, 14557 FK_BlockPointer 14558 }; 14559 14560 FnKind Kind; 14561 QualType CalleeType = CalleeExpr->getType(); 14562 if (CalleeType == S.Context.BoundMemberTy) { 14563 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14564 Kind = FK_MemberFunction; 14565 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14566 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14567 CalleeType = Ptr->getPointeeType(); 14568 Kind = FK_FunctionPointer; 14569 } else { 14570 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14571 Kind = FK_BlockPointer; 14572 } 14573 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14574 14575 // Verify that this is a legal result type of a function. 14576 if (DestType->isArrayType() || DestType->isFunctionType()) { 14577 unsigned diagID = diag::err_func_returning_array_function; 14578 if (Kind == FK_BlockPointer) 14579 diagID = diag::err_block_returning_array_function; 14580 14581 S.Diag(E->getExprLoc(), diagID) 14582 << DestType->isFunctionType() << DestType; 14583 return ExprError(); 14584 } 14585 14586 // Otherwise, go ahead and set DestType as the call's result. 14587 E->setType(DestType.getNonLValueExprType(S.Context)); 14588 E->setValueKind(Expr::getValueKindForType(DestType)); 14589 assert(E->getObjectKind() == OK_Ordinary); 14590 14591 // Rebuild the function type, replacing the result type with DestType. 14592 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14593 if (Proto) { 14594 // __unknown_anytype(...) is a special case used by the debugger when 14595 // it has no idea what a function's signature is. 14596 // 14597 // We want to build this call essentially under the K&R 14598 // unprototyped rules, but making a FunctionNoProtoType in C++ 14599 // would foul up all sorts of assumptions. However, we cannot 14600 // simply pass all arguments as variadic arguments, nor can we 14601 // portably just call the function under a non-variadic type; see 14602 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14603 // However, it turns out that in practice it is generally safe to 14604 // call a function declared as "A foo(B,C,D);" under the prototype 14605 // "A foo(B,C,D,...);". The only known exception is with the 14606 // Windows ABI, where any variadic function is implicitly cdecl 14607 // regardless of its normal CC. Therefore we change the parameter 14608 // types to match the types of the arguments. 14609 // 14610 // This is a hack, but it is far superior to moving the 14611 // corresponding target-specific code from IR-gen to Sema/AST. 14612 14613 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14614 SmallVector<QualType, 8> ArgTypes; 14615 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14616 ArgTypes.reserve(E->getNumArgs()); 14617 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14618 Expr *Arg = E->getArg(i); 14619 QualType ArgType = Arg->getType(); 14620 if (E->isLValue()) { 14621 ArgType = S.Context.getLValueReferenceType(ArgType); 14622 } else if (E->isXValue()) { 14623 ArgType = S.Context.getRValueReferenceType(ArgType); 14624 } 14625 ArgTypes.push_back(ArgType); 14626 } 14627 ParamTypes = ArgTypes; 14628 } 14629 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14630 Proto->getExtProtoInfo()); 14631 } else { 14632 DestType = S.Context.getFunctionNoProtoType(DestType, 14633 FnType->getExtInfo()); 14634 } 14635 14636 // Rebuild the appropriate pointer-to-function type. 14637 switch (Kind) { 14638 case FK_MemberFunction: 14639 // Nothing to do. 14640 break; 14641 14642 case FK_FunctionPointer: 14643 DestType = S.Context.getPointerType(DestType); 14644 break; 14645 14646 case FK_BlockPointer: 14647 DestType = S.Context.getBlockPointerType(DestType); 14648 break; 14649 } 14650 14651 // Finally, we can recurse. 14652 ExprResult CalleeResult = Visit(CalleeExpr); 14653 if (!CalleeResult.isUsable()) return ExprError(); 14654 E->setCallee(CalleeResult.get()); 14655 14656 // Bind a temporary if necessary. 14657 return S.MaybeBindToTemporary(E); 14658 } 14659 14660 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14661 // Verify that this is a legal result type of a call. 14662 if (DestType->isArrayType() || DestType->isFunctionType()) { 14663 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14664 << DestType->isFunctionType() << DestType; 14665 return ExprError(); 14666 } 14667 14668 // Rewrite the method result type if available. 14669 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14670 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14671 Method->setReturnType(DestType); 14672 } 14673 14674 // Change the type of the message. 14675 E->setType(DestType.getNonReferenceType()); 14676 E->setValueKind(Expr::getValueKindForType(DestType)); 14677 14678 return S.MaybeBindToTemporary(E); 14679 } 14680 14681 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14682 // The only case we should ever see here is a function-to-pointer decay. 14683 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14684 assert(E->getValueKind() == VK_RValue); 14685 assert(E->getObjectKind() == OK_Ordinary); 14686 14687 E->setType(DestType); 14688 14689 // Rebuild the sub-expression as the pointee (function) type. 14690 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14691 14692 ExprResult Result = Visit(E->getSubExpr()); 14693 if (!Result.isUsable()) return ExprError(); 14694 14695 E->setSubExpr(Result.get()); 14696 return E; 14697 } else if (E->getCastKind() == CK_LValueToRValue) { 14698 assert(E->getValueKind() == VK_RValue); 14699 assert(E->getObjectKind() == OK_Ordinary); 14700 14701 assert(isa<BlockPointerType>(E->getType())); 14702 14703 E->setType(DestType); 14704 14705 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14706 DestType = S.Context.getLValueReferenceType(DestType); 14707 14708 ExprResult Result = Visit(E->getSubExpr()); 14709 if (!Result.isUsable()) return ExprError(); 14710 14711 E->setSubExpr(Result.get()); 14712 return E; 14713 } else { 14714 llvm_unreachable("Unhandled cast type!"); 14715 } 14716 } 14717 14718 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14719 ExprValueKind ValueKind = VK_LValue; 14720 QualType Type = DestType; 14721 14722 // We know how to make this work for certain kinds of decls: 14723 14724 // - functions 14725 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14726 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14727 DestType = Ptr->getPointeeType(); 14728 ExprResult Result = resolveDecl(E, VD); 14729 if (Result.isInvalid()) return ExprError(); 14730 return S.ImpCastExprToType(Result.get(), Type, 14731 CK_FunctionToPointerDecay, VK_RValue); 14732 } 14733 14734 if (!Type->isFunctionType()) { 14735 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14736 << VD << E->getSourceRange(); 14737 return ExprError(); 14738 } 14739 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14740 // We must match the FunctionDecl's type to the hack introduced in 14741 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14742 // type. See the lengthy commentary in that routine. 14743 QualType FDT = FD->getType(); 14744 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14745 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14746 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14747 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14748 SourceLocation Loc = FD->getLocation(); 14749 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14750 FD->getDeclContext(), 14751 Loc, Loc, FD->getNameInfo().getName(), 14752 DestType, FD->getTypeSourceInfo(), 14753 SC_None, false/*isInlineSpecified*/, 14754 FD->hasPrototype(), 14755 false/*isConstexprSpecified*/); 14756 14757 if (FD->getQualifier()) 14758 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14759 14760 SmallVector<ParmVarDecl*, 16> Params; 14761 for (const auto &AI : FT->param_types()) { 14762 ParmVarDecl *Param = 14763 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14764 Param->setScopeInfo(0, Params.size()); 14765 Params.push_back(Param); 14766 } 14767 NewFD->setParams(Params); 14768 DRE->setDecl(NewFD); 14769 VD = DRE->getDecl(); 14770 } 14771 } 14772 14773 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14774 if (MD->isInstance()) { 14775 ValueKind = VK_RValue; 14776 Type = S.Context.BoundMemberTy; 14777 } 14778 14779 // Function references aren't l-values in C. 14780 if (!S.getLangOpts().CPlusPlus) 14781 ValueKind = VK_RValue; 14782 14783 // - variables 14784 } else if (isa<VarDecl>(VD)) { 14785 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14786 Type = RefTy->getPointeeType(); 14787 } else if (Type->isFunctionType()) { 14788 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14789 << VD << E->getSourceRange(); 14790 return ExprError(); 14791 } 14792 14793 // - nothing else 14794 } else { 14795 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14796 << VD << E->getSourceRange(); 14797 return ExprError(); 14798 } 14799 14800 // Modifying the declaration like this is friendly to IR-gen but 14801 // also really dangerous. 14802 VD->setType(DestType); 14803 E->setType(Type); 14804 E->setValueKind(ValueKind); 14805 return E; 14806 } 14807 14808 /// Check a cast of an unknown-any type. We intentionally only 14809 /// trigger this for C-style casts. 14810 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14811 Expr *CastExpr, CastKind &CastKind, 14812 ExprValueKind &VK, CXXCastPath &Path) { 14813 // The type we're casting to must be either void or complete. 14814 if (!CastType->isVoidType() && 14815 RequireCompleteType(TypeRange.getBegin(), CastType, 14816 diag::err_typecheck_cast_to_incomplete)) 14817 return ExprError(); 14818 14819 // Rewrite the casted expression from scratch. 14820 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14821 if (!result.isUsable()) return ExprError(); 14822 14823 CastExpr = result.get(); 14824 VK = CastExpr->getValueKind(); 14825 CastKind = CK_NoOp; 14826 14827 return CastExpr; 14828 } 14829 14830 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14831 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14832 } 14833 14834 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14835 Expr *arg, QualType ¶mType) { 14836 // If the syntactic form of the argument is not an explicit cast of 14837 // any sort, just do default argument promotion. 14838 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14839 if (!castArg) { 14840 ExprResult result = DefaultArgumentPromotion(arg); 14841 if (result.isInvalid()) return ExprError(); 14842 paramType = result.get()->getType(); 14843 return result; 14844 } 14845 14846 // Otherwise, use the type that was written in the explicit cast. 14847 assert(!arg->hasPlaceholderType()); 14848 paramType = castArg->getTypeAsWritten(); 14849 14850 // Copy-initialize a parameter of that type. 14851 InitializedEntity entity = 14852 InitializedEntity::InitializeParameter(Context, paramType, 14853 /*consumed*/ false); 14854 return PerformCopyInitialization(entity, callLoc, arg); 14855 } 14856 14857 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14858 Expr *orig = E; 14859 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14860 while (true) { 14861 E = E->IgnoreParenImpCasts(); 14862 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14863 E = call->getCallee(); 14864 diagID = diag::err_uncasted_call_of_unknown_any; 14865 } else { 14866 break; 14867 } 14868 } 14869 14870 SourceLocation loc; 14871 NamedDecl *d; 14872 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14873 loc = ref->getLocation(); 14874 d = ref->getDecl(); 14875 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14876 loc = mem->getMemberLoc(); 14877 d = mem->getMemberDecl(); 14878 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14879 diagID = diag::err_uncasted_call_of_unknown_any; 14880 loc = msg->getSelectorStartLoc(); 14881 d = msg->getMethodDecl(); 14882 if (!d) { 14883 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14884 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14885 << orig->getSourceRange(); 14886 return ExprError(); 14887 } 14888 } else { 14889 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14890 << E->getSourceRange(); 14891 return ExprError(); 14892 } 14893 14894 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14895 14896 // Never recoverable. 14897 return ExprError(); 14898 } 14899 14900 /// Check for operands with placeholder types and complain if found. 14901 /// Returns true if there was an error and no recovery was possible. 14902 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14903 if (!getLangOpts().CPlusPlus) { 14904 // C cannot handle TypoExpr nodes on either side of a binop because it 14905 // doesn't handle dependent types properly, so make sure any TypoExprs have 14906 // been dealt with before checking the operands. 14907 ExprResult Result = CorrectDelayedTyposInExpr(E); 14908 if (!Result.isUsable()) return ExprError(); 14909 E = Result.get(); 14910 } 14911 14912 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14913 if (!placeholderType) return E; 14914 14915 switch (placeholderType->getKind()) { 14916 14917 // Overloaded expressions. 14918 case BuiltinType::Overload: { 14919 // Try to resolve a single function template specialization. 14920 // This is obligatory. 14921 ExprResult Result = E; 14922 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 14923 return Result; 14924 14925 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 14926 // leaves Result unchanged on failure. 14927 Result = E; 14928 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 14929 return Result; 14930 14931 // If that failed, try to recover with a call. 14932 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 14933 /*complain*/ true); 14934 return Result; 14935 } 14936 14937 // Bound member functions. 14938 case BuiltinType::BoundMember: { 14939 ExprResult result = E; 14940 const Expr *BME = E->IgnoreParens(); 14941 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14942 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14943 if (isa<CXXPseudoDestructorExpr>(BME)) { 14944 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14945 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14946 if (ME->getMemberNameInfo().getName().getNameKind() == 14947 DeclarationName::CXXDestructorName) 14948 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14949 } 14950 tryToRecoverWithCall(result, PD, 14951 /*complain*/ true); 14952 return result; 14953 } 14954 14955 // ARC unbridged casts. 14956 case BuiltinType::ARCUnbridgedCast: { 14957 Expr *realCast = stripARCUnbridgedCast(E); 14958 diagnoseARCUnbridgedCast(realCast); 14959 return realCast; 14960 } 14961 14962 // Expressions of unknown type. 14963 case BuiltinType::UnknownAny: 14964 return diagnoseUnknownAnyExpr(*this, E); 14965 14966 // Pseudo-objects. 14967 case BuiltinType::PseudoObject: 14968 return checkPseudoObjectRValue(E); 14969 14970 case BuiltinType::BuiltinFn: { 14971 // Accept __noop without parens by implicitly converting it to a call expr. 14972 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14973 if (DRE) { 14974 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14975 if (FD->getBuiltinID() == Builtin::BI__noop) { 14976 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14977 CK_BuiltinFnToFnPtr).get(); 14978 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14979 VK_RValue, SourceLocation()); 14980 } 14981 } 14982 14983 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14984 return ExprError(); 14985 } 14986 14987 // Expressions of unknown type. 14988 case BuiltinType::OMPArraySection: 14989 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14990 return ExprError(); 14991 14992 // Everything else should be impossible. 14993 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 14994 case BuiltinType::Id: 14995 #include "clang/Basic/OpenCLImageTypes.def" 14996 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 14997 #define PLACEHOLDER_TYPE(Id, SingletonId) 14998 #include "clang/AST/BuiltinTypes.def" 14999 break; 15000 } 15001 15002 llvm_unreachable("invalid placeholder type!"); 15003 } 15004 15005 bool Sema::CheckCaseExpression(Expr *E) { 15006 if (E->isTypeDependent()) 15007 return true; 15008 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15009 return E->getType()->isIntegralOrEnumerationType(); 15010 return false; 15011 } 15012 15013 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15014 ExprResult 15015 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15016 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15017 "Unknown Objective-C Boolean value!"); 15018 QualType BoolT = Context.ObjCBuiltinBoolTy; 15019 if (!Context.getBOOLDecl()) { 15020 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15021 Sema::LookupOrdinaryName); 15022 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15023 NamedDecl *ND = Result.getFoundDecl(); 15024 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15025 Context.setBOOLDecl(TD); 15026 } 15027 } 15028 if (Context.getBOOLDecl()) 15029 BoolT = Context.getBOOLType(); 15030 return new (Context) 15031 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15032 } 15033