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/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/Template.h" 45 using namespace clang; 46 using namespace sema; 47 48 /// \brief Determine whether the use of this declaration is valid, without 49 /// emitting diagnostics. 50 bool Sema::CanUseDecl(NamedDecl *D) { 51 // See if this is an auto-typed variable whose initializer we are parsing. 52 if (ParsingInitForAutoVars.count(D)) 53 return false; 54 55 // See if this is a deleted function. 56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 57 if (FD->isDeleted()) 58 return false; 59 60 // If the function has a deduced return type, and we can't deduce it, 61 // then we can't use it either. 62 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 63 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 64 return false; 65 } 66 67 // See if this function is unavailable. 68 if (D->getAvailability() == AR_Unavailable && 69 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 70 return false; 71 72 return true; 73 } 74 75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 76 // Warn if this is used but marked unused. 77 if (D->hasAttr<UnusedAttr>()) { 78 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 79 if (!DC->hasAttr<UnusedAttr>()) 80 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 81 } 82 } 83 84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 85 NamedDecl *D, SourceLocation Loc, 86 const ObjCInterfaceDecl *UnknownObjCClass, 87 bool ObjCPropertyAccess) { 88 // See if this declaration is unavailable or deprecated. 89 std::string Message; 90 91 // Forward class declarations get their attributes from their definition. 92 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 93 if (IDecl->getDefinition()) 94 D = IDecl->getDefinition(); 95 } 96 AvailabilityResult Result = D->getAvailability(&Message); 97 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 98 if (Result == AR_Available) { 99 const DeclContext *DC = ECD->getDeclContext(); 100 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 101 Result = TheEnumDecl->getAvailability(&Message); 102 } 103 104 const ObjCPropertyDecl *ObjCPDecl = nullptr; 105 if (Result == AR_Deprecated || Result == AR_Unavailable) { 106 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 107 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 108 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 109 if (PDeclResult == Result) 110 ObjCPDecl = PD; 111 } 112 } 113 } 114 115 switch (Result) { 116 case AR_Available: 117 case AR_NotYetIntroduced: 118 break; 119 120 case AR_Deprecated: 121 if (S.getCurContextAvailability() != AR_Deprecated) 122 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 123 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 124 ObjCPropertyAccess); 125 break; 126 127 case AR_Unavailable: 128 if (S.getCurContextAvailability() != AR_Unavailable) 129 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 130 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 131 ObjCPropertyAccess); 132 break; 133 134 } 135 return Result; 136 } 137 138 /// \brief Emit a note explaining that this function is deleted. 139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 140 assert(Decl->isDeleted()); 141 142 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 143 144 if (Method && Method->isDeleted() && Method->isDefaulted()) { 145 // If the method was explicitly defaulted, point at that declaration. 146 if (!Method->isImplicit()) 147 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 148 149 // Try to diagnose why this special member function was implicitly 150 // deleted. This might fail, if that reason no longer applies. 151 CXXSpecialMember CSM = getSpecialMember(Method); 152 if (CSM != CXXInvalid) 153 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 154 155 return; 156 } 157 158 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 159 if (CXXConstructorDecl *BaseCD = 160 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 161 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 162 if (BaseCD->isDeleted()) { 163 NoteDeletedFunction(BaseCD); 164 } else { 165 // FIXME: An explanation of why exactly it can't be inherited 166 // would be nice. 167 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 168 } 169 return; 170 } 171 } 172 173 Diag(Decl->getLocation(), diag::note_availability_specified_here) 174 << Decl << true; 175 } 176 177 /// \brief Determine whether a FunctionDecl was ever declared with an 178 /// explicit storage class. 179 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 180 for (auto I : D->redecls()) { 181 if (I->getStorageClass() != SC_None) 182 return true; 183 } 184 return false; 185 } 186 187 /// \brief Check whether we're in an extern inline function and referring to a 188 /// variable or function with internal linkage (C11 6.7.4p3). 189 /// 190 /// This is only a warning because we used to silently accept this code, but 191 /// in many cases it will not behave correctly. This is not enabled in C++ mode 192 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 193 /// and so while there may still be user mistakes, most of the time we can't 194 /// prove that there are errors. 195 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 196 const NamedDecl *D, 197 SourceLocation Loc) { 198 // This is disabled under C++; there are too many ways for this to fire in 199 // contexts where the warning is a false positive, or where it is technically 200 // correct but benign. 201 if (S.getLangOpts().CPlusPlus) 202 return; 203 204 // Check if this is an inlined function or method. 205 FunctionDecl *Current = S.getCurFunctionDecl(); 206 if (!Current) 207 return; 208 if (!Current->isInlined()) 209 return; 210 if (!Current->isExternallyVisible()) 211 return; 212 213 // Check if the decl has internal linkage. 214 if (D->getFormalLinkage() != InternalLinkage) 215 return; 216 217 // Downgrade from ExtWarn to Extension if 218 // (1) the supposedly external inline function is in the main file, 219 // and probably won't be included anywhere else. 220 // (2) the thing we're referencing is a pure function. 221 // (3) the thing we're referencing is another inline function. 222 // This last can give us false negatives, but it's better than warning on 223 // wrappers for simple C library functions. 224 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 225 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 226 if (!DowngradeWarning && UsedFn) 227 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 228 229 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 230 : diag::warn_internal_in_extern_inline) 231 << /*IsVar=*/!UsedFn << D; 232 233 S.MaybeSuggestAddingStaticToDecl(Current); 234 235 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 236 << D; 237 } 238 239 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 240 const FunctionDecl *First = Cur->getFirstDecl(); 241 242 // Suggest "static" on the function, if possible. 243 if (!hasAnyExplicitStorageClass(First)) { 244 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 245 Diag(DeclBegin, diag::note_convert_inline_to_static) 246 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 247 } 248 } 249 250 /// \brief Determine whether the use of this declaration is valid, and 251 /// emit any corresponding diagnostics. 252 /// 253 /// This routine diagnoses various problems with referencing 254 /// declarations that can occur when using a declaration. For example, 255 /// it might warn if a deprecated or unavailable declaration is being 256 /// used, or produce an error (and return true) if a C++0x deleted 257 /// function is being used. 258 /// 259 /// \returns true if there was an error (this declaration cannot be 260 /// referenced), false otherwise. 261 /// 262 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 263 const ObjCInterfaceDecl *UnknownObjCClass, 264 bool ObjCPropertyAccess) { 265 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 266 // If there were any diagnostics suppressed by template argument deduction, 267 // emit them now. 268 SuppressedDiagnosticsMap::iterator 269 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 270 if (Pos != SuppressedDiagnostics.end()) { 271 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 272 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 273 Diag(Suppressed[I].first, Suppressed[I].second); 274 275 // Clear out the list of suppressed diagnostics, so that we don't emit 276 // them again for this specialization. However, we don't obsolete this 277 // entry from the table, because we want to avoid ever emitting these 278 // diagnostics again. 279 Suppressed.clear(); 280 } 281 282 // C++ [basic.start.main]p3: 283 // The function 'main' shall not be used within a program. 284 if (cast<FunctionDecl>(D)->isMain()) 285 Diag(Loc, diag::ext_main_used); 286 } 287 288 // See if this is an auto-typed variable whose initializer we are parsing. 289 if (ParsingInitForAutoVars.count(D)) { 290 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 291 << D->getDeclName(); 292 return true; 293 } 294 295 // See if this is a deleted function. 296 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 297 if (FD->isDeleted()) { 298 Diag(Loc, diag::err_deleted_function_use); 299 NoteDeletedFunction(FD); 300 return true; 301 } 302 303 // If the function has a deduced return type, and we can't deduce it, 304 // then we can't use it either. 305 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 306 DeduceReturnType(FD, Loc)) 307 return true; 308 } 309 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess); 310 311 DiagnoseUnusedOfDecl(*this, D, Loc); 312 313 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 314 315 return false; 316 } 317 318 /// \brief Retrieve the message suffix that should be added to a 319 /// diagnostic complaining about the given function being deleted or 320 /// unavailable. 321 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 322 std::string Message; 323 if (FD->getAvailability(&Message)) 324 return ": " + Message; 325 326 return std::string(); 327 } 328 329 /// DiagnoseSentinelCalls - This routine checks whether a call or 330 /// message-send is to a declaration with the sentinel attribute, and 331 /// if so, it checks that the requirements of the sentinel are 332 /// satisfied. 333 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 334 ArrayRef<Expr *> Args) { 335 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 336 if (!attr) 337 return; 338 339 // The number of formal parameters of the declaration. 340 unsigned numFormalParams; 341 342 // The kind of declaration. This is also an index into a %select in 343 // the diagnostic. 344 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 345 346 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 347 numFormalParams = MD->param_size(); 348 calleeType = CT_Method; 349 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 350 numFormalParams = FD->param_size(); 351 calleeType = CT_Function; 352 } else if (isa<VarDecl>(D)) { 353 QualType type = cast<ValueDecl>(D)->getType(); 354 const FunctionType *fn = nullptr; 355 if (const PointerType *ptr = type->getAs<PointerType>()) { 356 fn = ptr->getPointeeType()->getAs<FunctionType>(); 357 if (!fn) return; 358 calleeType = CT_Function; 359 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 360 fn = ptr->getPointeeType()->castAs<FunctionType>(); 361 calleeType = CT_Block; 362 } else { 363 return; 364 } 365 366 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 367 numFormalParams = proto->getNumParams(); 368 } else { 369 numFormalParams = 0; 370 } 371 } else { 372 return; 373 } 374 375 // "nullPos" is the number of formal parameters at the end which 376 // effectively count as part of the variadic arguments. This is 377 // useful if you would prefer to not have *any* formal parameters, 378 // but the language forces you to have at least one. 379 unsigned nullPos = attr->getNullPos(); 380 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 381 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 382 383 // The number of arguments which should follow the sentinel. 384 unsigned numArgsAfterSentinel = attr->getSentinel(); 385 386 // If there aren't enough arguments for all the formal parameters, 387 // the sentinel, and the args after the sentinel, complain. 388 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 389 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 390 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 391 return; 392 } 393 394 // Otherwise, find the sentinel expression. 395 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 396 if (!sentinelExpr) return; 397 if (sentinelExpr->isValueDependent()) return; 398 if (Context.isSentinelNullExpr(sentinelExpr)) return; 399 400 // Pick a reasonable string to insert. Optimistically use 'nil' or 401 // 'NULL' if those are actually defined in the context. Only use 402 // 'nil' for ObjC methods, where it's much more likely that the 403 // variadic arguments form a list of object pointers. 404 SourceLocation MissingNilLoc 405 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 406 std::string NullValue; 407 if (calleeType == CT_Method && 408 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 409 NullValue = "nil"; 410 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 411 NullValue = "NULL"; 412 else 413 NullValue = "(void*) 0"; 414 415 if (MissingNilLoc.isInvalid()) 416 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 417 else 418 Diag(MissingNilLoc, diag::warn_missing_sentinel) 419 << int(calleeType) 420 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 421 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 422 } 423 424 SourceRange Sema::getExprRange(Expr *E) const { 425 return E ? E->getSourceRange() : SourceRange(); 426 } 427 428 //===----------------------------------------------------------------------===// 429 // Standard Promotions and Conversions 430 //===----------------------------------------------------------------------===// 431 432 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 433 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 434 // Handle any placeholder expressions which made it here. 435 if (E->getType()->isPlaceholderType()) { 436 ExprResult result = CheckPlaceholderExpr(E); 437 if (result.isInvalid()) return ExprError(); 438 E = result.get(); 439 } 440 441 QualType Ty = E->getType(); 442 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 443 444 if (Ty->isFunctionType()) { 445 // If we are here, we are not calling a function but taking 446 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 447 if (getLangOpts().OpenCL) { 448 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 449 return ExprError(); 450 } 451 E = ImpCastExprToType(E, Context.getPointerType(Ty), 452 CK_FunctionToPointerDecay).get(); 453 } else if (Ty->isArrayType()) { 454 // In C90 mode, arrays only promote to pointers if the array expression is 455 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 456 // type 'array of type' is converted to an expression that has type 'pointer 457 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 458 // that has type 'array of type' ...". The relevant change is "an lvalue" 459 // (C90) to "an expression" (C99). 460 // 461 // C++ 4.2p1: 462 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 463 // T" can be converted to an rvalue of type "pointer to T". 464 // 465 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 466 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 467 CK_ArrayToPointerDecay).get(); 468 } 469 return E; 470 } 471 472 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 473 // Check to see if we are dereferencing a null pointer. If so, 474 // and if not volatile-qualified, this is undefined behavior that the 475 // optimizer will delete, so warn about it. People sometimes try to use this 476 // to get a deterministic trap and are surprised by clang's behavior. This 477 // only handles the pattern "*null", which is a very syntactic check. 478 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 479 if (UO->getOpcode() == UO_Deref && 480 UO->getSubExpr()->IgnoreParenCasts()-> 481 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 482 !UO->getType().isVolatileQualified()) { 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::warn_indirection_through_null) 485 << UO->getSubExpr()->getSourceRange()); 486 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 487 S.PDiag(diag::note_indirection_through_null)); 488 } 489 } 490 491 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 492 SourceLocation AssignLoc, 493 const Expr* RHS) { 494 const ObjCIvarDecl *IV = OIRE->getDecl(); 495 if (!IV) 496 return; 497 498 DeclarationName MemberName = IV->getDeclName(); 499 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 500 if (!Member || !Member->isStr("isa")) 501 return; 502 503 const Expr *Base = OIRE->getBase(); 504 QualType BaseType = Base->getType(); 505 if (OIRE->isArrow()) 506 BaseType = BaseType->getPointeeType(); 507 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 508 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 509 ObjCInterfaceDecl *ClassDeclared = nullptr; 510 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 511 if (!ClassDeclared->getSuperClass() 512 && (*ClassDeclared->ivar_begin()) == IV) { 513 if (RHS) { 514 NamedDecl *ObjectSetClass = 515 S.LookupSingleName(S.TUScope, 516 &S.Context.Idents.get("object_setClass"), 517 SourceLocation(), S.LookupOrdinaryName); 518 if (ObjectSetClass) { 519 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 520 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 521 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 522 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 523 AssignLoc), ",") << 524 FixItHint::CreateInsertion(RHSLocEnd, ")"); 525 } 526 else 527 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 528 } else { 529 NamedDecl *ObjectGetClass = 530 S.LookupSingleName(S.TUScope, 531 &S.Context.Idents.get("object_getClass"), 532 SourceLocation(), S.LookupOrdinaryName); 533 if (ObjectGetClass) 534 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 535 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 536 FixItHint::CreateReplacement( 537 SourceRange(OIRE->getOpLoc(), 538 OIRE->getLocEnd()), ")"); 539 else 540 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 541 } 542 S.Diag(IV->getLocation(), diag::note_ivar_decl); 543 } 544 } 545 } 546 547 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 548 // Handle any placeholder expressions which made it here. 549 if (E->getType()->isPlaceholderType()) { 550 ExprResult result = CheckPlaceholderExpr(E); 551 if (result.isInvalid()) return ExprError(); 552 E = result.get(); 553 } 554 555 // C++ [conv.lval]p1: 556 // A glvalue of a non-function, non-array type T can be 557 // converted to a prvalue. 558 if (!E->isGLValue()) return E; 559 560 QualType T = E->getType(); 561 assert(!T.isNull() && "r-value conversion on typeless expression?"); 562 563 // We don't want to throw lvalue-to-rvalue casts on top of 564 // expressions of certain types in C++. 565 if (getLangOpts().CPlusPlus && 566 (E->getType() == Context.OverloadTy || 567 T->isDependentType() || 568 T->isRecordType())) 569 return E; 570 571 // The C standard is actually really unclear on this point, and 572 // DR106 tells us what the result should be but not why. It's 573 // generally best to say that void types just doesn't undergo 574 // lvalue-to-rvalue at all. Note that expressions of unqualified 575 // 'void' type are never l-values, but qualified void can be. 576 if (T->isVoidType()) 577 return E; 578 579 // OpenCL usually rejects direct accesses to values of 'half' type. 580 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 581 T->isHalfType()) { 582 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 583 << 0 << T; 584 return ExprError(); 585 } 586 587 CheckForNullPointerDereference(*this, E); 588 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 589 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 590 &Context.Idents.get("object_getClass"), 591 SourceLocation(), LookupOrdinaryName); 592 if (ObjectGetClass) 593 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 594 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 595 FixItHint::CreateReplacement( 596 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 597 else 598 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 599 } 600 else if (const ObjCIvarRefExpr *OIRE = 601 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 602 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 603 604 // C++ [conv.lval]p1: 605 // [...] If T is a non-class type, the type of the prvalue is the 606 // cv-unqualified version of T. Otherwise, the type of the 607 // rvalue is T. 608 // 609 // C99 6.3.2.1p2: 610 // If the lvalue has qualified type, the value has the unqualified 611 // version of the type of the lvalue; otherwise, the value has the 612 // type of the lvalue. 613 if (T.hasQualifiers()) 614 T = T.getUnqualifiedType(); 615 616 UpdateMarkingForLValueToRValue(E); 617 618 // Loading a __weak object implicitly retains the value, so we need a cleanup to 619 // balance that. 620 if (getLangOpts().ObjCAutoRefCount && 621 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 622 ExprNeedsCleanups = true; 623 624 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 625 nullptr, VK_RValue); 626 627 // C11 6.3.2.1p2: 628 // ... if the lvalue has atomic type, the value has the non-atomic version 629 // of the type of the lvalue ... 630 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 631 T = Atomic->getValueType().getUnqualifiedType(); 632 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 633 nullptr, VK_RValue); 634 } 635 636 return Res; 637 } 638 639 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 640 ExprResult Res = DefaultFunctionArrayConversion(E); 641 if (Res.isInvalid()) 642 return ExprError(); 643 Res = DefaultLvalueConversion(Res.get()); 644 if (Res.isInvalid()) 645 return ExprError(); 646 return Res; 647 } 648 649 /// CallExprUnaryConversions - a special case of an unary conversion 650 /// performed on a function designator of a call expression. 651 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 652 QualType Ty = E->getType(); 653 ExprResult Res = E; 654 // Only do implicit cast for a function type, but not for a pointer 655 // to function type. 656 if (Ty->isFunctionType()) { 657 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 658 CK_FunctionToPointerDecay).get(); 659 if (Res.isInvalid()) 660 return ExprError(); 661 } 662 Res = DefaultLvalueConversion(Res.get()); 663 if (Res.isInvalid()) 664 return ExprError(); 665 return Res.get(); 666 } 667 668 /// UsualUnaryConversions - Performs various conversions that are common to most 669 /// operators (C99 6.3). The conversions of array and function types are 670 /// sometimes suppressed. For example, the array->pointer conversion doesn't 671 /// apply if the array is an argument to the sizeof or address (&) operators. 672 /// In these instances, this routine should *not* be called. 673 ExprResult Sema::UsualUnaryConversions(Expr *E) { 674 // First, convert to an r-value. 675 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 676 if (Res.isInvalid()) 677 return ExprError(); 678 E = Res.get(); 679 680 QualType Ty = E->getType(); 681 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 682 683 // Half FP have to be promoted to float unless it is natively supported 684 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 685 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 686 687 // Try to perform integral promotions if the object has a theoretically 688 // promotable type. 689 if (Ty->isIntegralOrUnscopedEnumerationType()) { 690 // C99 6.3.1.1p2: 691 // 692 // The following may be used in an expression wherever an int or 693 // unsigned int may be used: 694 // - an object or expression with an integer type whose integer 695 // conversion rank is less than or equal to the rank of int 696 // and unsigned int. 697 // - A bit-field of type _Bool, int, signed int, or unsigned int. 698 // 699 // If an int can represent all values of the original type, the 700 // value is converted to an int; otherwise, it is converted to an 701 // unsigned int. These are called the integer promotions. All 702 // other types are unchanged by the integer promotions. 703 704 QualType PTy = Context.isPromotableBitField(E); 705 if (!PTy.isNull()) { 706 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 707 return E; 708 } 709 if (Ty->isPromotableIntegerType()) { 710 QualType PT = Context.getPromotedIntegerType(Ty); 711 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 712 return E; 713 } 714 } 715 return E; 716 } 717 718 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 719 /// do not have a prototype. Arguments that have type float or __fp16 720 /// are promoted to double. All other argument types are converted by 721 /// UsualUnaryConversions(). 722 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 723 QualType Ty = E->getType(); 724 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 725 726 ExprResult Res = UsualUnaryConversions(E); 727 if (Res.isInvalid()) 728 return ExprError(); 729 E = Res.get(); 730 731 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 732 // double. 733 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 734 if (BTy && (BTy->getKind() == BuiltinType::Half || 735 BTy->getKind() == BuiltinType::Float)) 736 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 737 738 // C++ performs lvalue-to-rvalue conversion as a default argument 739 // promotion, even on class types, but note: 740 // C++11 [conv.lval]p2: 741 // When an lvalue-to-rvalue conversion occurs in an unevaluated 742 // operand or a subexpression thereof the value contained in the 743 // referenced object is not accessed. Otherwise, if the glvalue 744 // has a class type, the conversion copy-initializes a temporary 745 // of type T from the glvalue and the result of the conversion 746 // is a prvalue for the temporary. 747 // FIXME: add some way to gate this entire thing for correctness in 748 // potentially potentially evaluated contexts. 749 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 750 ExprResult Temp = PerformCopyInitialization( 751 InitializedEntity::InitializeTemporary(E->getType()), 752 E->getExprLoc(), E); 753 if (Temp.isInvalid()) 754 return ExprError(); 755 E = Temp.get(); 756 } 757 758 return E; 759 } 760 761 /// Determine the degree of POD-ness for an expression. 762 /// Incomplete types are considered POD, since this check can be performed 763 /// when we're in an unevaluated context. 764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 765 if (Ty->isIncompleteType()) { 766 // C++11 [expr.call]p7: 767 // After these conversions, if the argument does not have arithmetic, 768 // enumeration, pointer, pointer to member, or class type, the program 769 // is ill-formed. 770 // 771 // Since we've already performed array-to-pointer and function-to-pointer 772 // decay, the only such type in C++ is cv void. This also handles 773 // initializer lists as variadic arguments. 774 if (Ty->isVoidType()) 775 return VAK_Invalid; 776 777 if (Ty->isObjCObjectType()) 778 return VAK_Invalid; 779 return VAK_Valid; 780 } 781 782 if (Ty.isCXX98PODType(Context)) 783 return VAK_Valid; 784 785 // C++11 [expr.call]p7: 786 // Passing a potentially-evaluated argument of class type (Clause 9) 787 // having a non-trivial copy constructor, a non-trivial move constructor, 788 // or a non-trivial destructor, with no corresponding parameter, 789 // is conditionally-supported with implementation-defined semantics. 790 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 791 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 792 if (!Record->hasNonTrivialCopyConstructor() && 793 !Record->hasNonTrivialMoveConstructor() && 794 !Record->hasNonTrivialDestructor()) 795 return VAK_ValidInCXX11; 796 797 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 798 return VAK_Valid; 799 800 if (Ty->isObjCObjectType()) 801 return VAK_Invalid; 802 803 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 804 // permitted to reject them. We should consider doing so. 805 return VAK_Undefined; 806 } 807 808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 809 // Don't allow one to pass an Objective-C interface to a vararg. 810 const QualType &Ty = E->getType(); 811 VarArgKind VAK = isValidVarArgType(Ty); 812 813 // Complain about passing non-POD types through varargs. 814 switch (VAK) { 815 case VAK_ValidInCXX11: 816 DiagRuntimeBehavior( 817 E->getLocStart(), nullptr, 818 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 819 << Ty << CT); 820 // Fall through. 821 case VAK_Valid: 822 if (Ty->isRecordType()) { 823 // This is unlikely to be what the user intended. If the class has a 824 // 'c_str' member function, the user probably meant to call that. 825 DiagRuntimeBehavior(E->getLocStart(), nullptr, 826 PDiag(diag::warn_pass_class_arg_to_vararg) 827 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 828 } 829 break; 830 831 case VAK_Undefined: 832 DiagRuntimeBehavior( 833 E->getLocStart(), nullptr, 834 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 835 << getLangOpts().CPlusPlus11 << Ty << CT); 836 break; 837 838 case VAK_Invalid: 839 if (Ty->isObjCObjectType()) 840 DiagRuntimeBehavior( 841 E->getLocStart(), nullptr, 842 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 843 << Ty << CT); 844 else 845 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 846 << isa<InitListExpr>(E) << Ty << CT; 847 break; 848 } 849 } 850 851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 852 /// will create a trap if the resulting type is not a POD type. 853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 854 FunctionDecl *FDecl) { 855 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 856 // Strip the unbridged-cast placeholder expression off, if applicable. 857 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 858 (CT == VariadicMethod || 859 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 860 E = stripARCUnbridgedCast(E); 861 862 // Otherwise, do normal placeholder checking. 863 } else { 864 ExprResult ExprRes = CheckPlaceholderExpr(E); 865 if (ExprRes.isInvalid()) 866 return ExprError(); 867 E = ExprRes.get(); 868 } 869 } 870 871 ExprResult ExprRes = DefaultArgumentPromotion(E); 872 if (ExprRes.isInvalid()) 873 return ExprError(); 874 E = ExprRes.get(); 875 876 // Diagnostics regarding non-POD argument types are 877 // emitted along with format string checking in Sema::CheckFunctionCall(). 878 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 879 // Turn this into a trap. 880 CXXScopeSpec SS; 881 SourceLocation TemplateKWLoc; 882 UnqualifiedId Name; 883 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 884 E->getLocStart()); 885 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 886 Name, true, false); 887 if (TrapFn.isInvalid()) 888 return ExprError(); 889 890 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 891 E->getLocStart(), None, 892 E->getLocEnd()); 893 if (Call.isInvalid()) 894 return ExprError(); 895 896 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 897 Call.get(), E); 898 if (Comma.isInvalid()) 899 return ExprError(); 900 return Comma.get(); 901 } 902 903 if (!getLangOpts().CPlusPlus && 904 RequireCompleteType(E->getExprLoc(), E->getType(), 905 diag::err_call_incomplete_argument)) 906 return ExprError(); 907 908 return E; 909 } 910 911 /// \brief Converts an integer to complex float type. Helper function of 912 /// UsualArithmeticConversions() 913 /// 914 /// \return false if the integer expression is an integer type and is 915 /// successfully converted to the complex type. 916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 917 ExprResult &ComplexExpr, 918 QualType IntTy, 919 QualType ComplexTy, 920 bool SkipCast) { 921 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 922 if (SkipCast) return false; 923 if (IntTy->isIntegerType()) { 924 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 925 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 926 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 927 CK_FloatingRealToComplex); 928 } else { 929 assert(IntTy->isComplexIntegerType()); 930 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 931 CK_IntegralComplexToFloatingComplex); 932 } 933 return false; 934 } 935 936 /// \brief Takes two complex float types and converts them to the same type. 937 /// Helper function of UsualArithmeticConversions() 938 static QualType 939 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 940 ExprResult &RHS, QualType LHSType, 941 QualType RHSType, 942 bool IsCompAssign) { 943 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 944 945 if (order < 0) { 946 // _Complex float -> _Complex double 947 if (!IsCompAssign) 948 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingComplexCast); 949 return RHSType; 950 } 951 if (order > 0) 952 // _Complex float -> _Complex double 953 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingComplexCast); 954 return LHSType; 955 } 956 957 /// \brief Converts otherExpr to complex float and promotes complexExpr if 958 /// necessary. Helper function of UsualArithmeticConversions() 959 static QualType handleOtherComplexFloatConversion(Sema &S, 960 ExprResult &ComplexExpr, 961 ExprResult &OtherExpr, 962 QualType ComplexTy, 963 QualType OtherTy, 964 bool ConvertComplexExpr, 965 bool ConvertOtherExpr) { 966 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 967 968 // If just the complexExpr is complex, the otherExpr needs to be converted, 969 // and the complexExpr might need to be promoted. 970 if (order > 0) { // complexExpr is wider 971 // float -> _Complex double 972 if (ConvertOtherExpr) { 973 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 974 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), fp, CK_FloatingCast); 975 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), ComplexTy, 976 CK_FloatingRealToComplex); 977 } 978 return ComplexTy; 979 } 980 981 // otherTy is at least as wide. Find its corresponding complex type. 982 QualType result = (order == 0 ? ComplexTy : 983 S.Context.getComplexType(OtherTy)); 984 985 // double -> _Complex double 986 if (ConvertOtherExpr) 987 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), result, 988 CK_FloatingRealToComplex); 989 990 // _Complex float -> _Complex double 991 if (ConvertComplexExpr && order < 0) 992 ComplexExpr = S.ImpCastExprToType(ComplexExpr.get(), result, 993 CK_FloatingComplexCast); 994 995 return result; 996 } 997 998 /// \brief Handle arithmetic conversion with complex types. Helper function of 999 /// UsualArithmeticConversions() 1000 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1001 ExprResult &RHS, QualType LHSType, 1002 QualType RHSType, 1003 bool IsCompAssign) { 1004 // if we have an integer operand, the result is the complex type. 1005 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1006 /*skipCast*/false)) 1007 return LHSType; 1008 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1009 /*skipCast*/IsCompAssign)) 1010 return RHSType; 1011 1012 // This handles complex/complex, complex/float, or float/complex. 1013 // When both operands are complex, the shorter operand is converted to the 1014 // type of the longer, and that is the type of the result. This corresponds 1015 // to what is done when combining two real floating-point operands. 1016 // The fun begins when size promotion occur across type domains. 1017 // From H&S 6.3.4: When one operand is complex and the other is a real 1018 // floating-point type, the less precise type is converted, within it's 1019 // real or complex domain, to the precision of the other type. For example, 1020 // when combining a "long double" with a "double _Complex", the 1021 // "double _Complex" is promoted to "long double _Complex". 1022 1023 bool LHSComplexFloat = LHSType->isComplexType(); 1024 bool RHSComplexFloat = RHSType->isComplexType(); 1025 1026 // If both are complex, just cast to the more precise type. 1027 if (LHSComplexFloat && RHSComplexFloat) 1028 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1029 LHSType, RHSType, 1030 IsCompAssign); 1031 1032 // If only one operand is complex, promote it if necessary and convert the 1033 // other operand to complex. 1034 if (LHSComplexFloat) 1035 return handleOtherComplexFloatConversion( 1036 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1037 /*convertOtherExpr*/ true); 1038 1039 assert(RHSComplexFloat); 1040 return handleOtherComplexFloatConversion( 1041 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1042 /*convertOtherExpr*/ !IsCompAssign); 1043 } 1044 1045 /// \brief Hande arithmetic conversion from integer to float. Helper function 1046 /// of UsualArithmeticConversions() 1047 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1048 ExprResult &IntExpr, 1049 QualType FloatTy, QualType IntTy, 1050 bool ConvertFloat, bool ConvertInt) { 1051 if (IntTy->isIntegerType()) { 1052 if (ConvertInt) 1053 // Convert intExpr to the lhs floating point type. 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1055 CK_IntegralToFloating); 1056 return FloatTy; 1057 } 1058 1059 // Convert both sides to the appropriate complex float. 1060 assert(IntTy->isComplexIntegerType()); 1061 QualType result = S.Context.getComplexType(FloatTy); 1062 1063 // _Complex int -> _Complex float 1064 if (ConvertInt) 1065 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1066 CK_IntegralComplexToFloatingComplex); 1067 1068 // float -> _Complex float 1069 if (ConvertFloat) 1070 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1071 CK_FloatingRealToComplex); 1072 1073 return result; 1074 } 1075 1076 /// \brief Handle arithmethic conversion with floating point types. Helper 1077 /// function of UsualArithmeticConversions() 1078 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1079 ExprResult &RHS, QualType LHSType, 1080 QualType RHSType, bool IsCompAssign) { 1081 bool LHSFloat = LHSType->isRealFloatingType(); 1082 bool RHSFloat = RHSType->isRealFloatingType(); 1083 1084 // If we have two real floating types, convert the smaller operand 1085 // to the bigger result. 1086 if (LHSFloat && RHSFloat) { 1087 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1088 if (order > 0) { 1089 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1090 return LHSType; 1091 } 1092 1093 assert(order < 0 && "illegal float comparison"); 1094 if (!IsCompAssign) 1095 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1096 return RHSType; 1097 } 1098 1099 if (LHSFloat) 1100 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1101 /*convertFloat=*/!IsCompAssign, 1102 /*convertInt=*/ true); 1103 assert(RHSFloat); 1104 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1105 /*convertInt=*/ true, 1106 /*convertFloat=*/!IsCompAssign); 1107 } 1108 1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1110 1111 namespace { 1112 /// These helper callbacks are placed in an anonymous namespace to 1113 /// permit their use as function template parameters. 1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1115 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1116 } 1117 1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1119 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1120 CK_IntegralComplexCast); 1121 } 1122 } 1123 1124 /// \brief Handle integer arithmetic conversions. Helper function of 1125 /// UsualArithmeticConversions() 1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1128 ExprResult &RHS, QualType LHSType, 1129 QualType RHSType, bool IsCompAssign) { 1130 // The rules for this case are in C99 6.3.1.8 1131 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1132 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1133 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1134 if (LHSSigned == RHSSigned) { 1135 // Same signedness; use the higher-ranked type 1136 if (order >= 0) { 1137 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1138 return LHSType; 1139 } else if (!IsCompAssign) 1140 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1141 return RHSType; 1142 } else if (order != (LHSSigned ? 1 : -1)) { 1143 // The unsigned type has greater than or equal rank to the 1144 // signed type, so use the unsigned type 1145 if (RHSSigned) { 1146 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1147 return LHSType; 1148 } else if (!IsCompAssign) 1149 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1150 return RHSType; 1151 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1152 // The two types are different widths; if we are here, that 1153 // means the signed type is larger than the unsigned type, so 1154 // use the signed type. 1155 if (LHSSigned) { 1156 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1157 return LHSType; 1158 } else if (!IsCompAssign) 1159 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1160 return RHSType; 1161 } else { 1162 // The signed type is higher-ranked than the unsigned type, 1163 // but isn't actually any bigger (like unsigned int and long 1164 // on most 32-bit systems). Use the unsigned type corresponding 1165 // to the signed type. 1166 QualType result = 1167 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1168 RHS = (*doRHSCast)(S, RHS.get(), result); 1169 if (!IsCompAssign) 1170 LHS = (*doLHSCast)(S, LHS.get(), result); 1171 return result; 1172 } 1173 } 1174 1175 /// \brief Handle conversions with GCC complex int extension. Helper function 1176 /// of UsualArithmeticConversions() 1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1178 ExprResult &RHS, QualType LHSType, 1179 QualType RHSType, 1180 bool IsCompAssign) { 1181 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1182 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1183 1184 if (LHSComplexInt && RHSComplexInt) { 1185 QualType LHSEltType = LHSComplexInt->getElementType(); 1186 QualType RHSEltType = RHSComplexInt->getElementType(); 1187 QualType ScalarType = 1188 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1189 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1190 1191 return S.Context.getComplexType(ScalarType); 1192 } 1193 1194 if (LHSComplexInt) { 1195 QualType LHSEltType = LHSComplexInt->getElementType(); 1196 QualType ScalarType = 1197 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1198 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1199 QualType ComplexType = S.Context.getComplexType(ScalarType); 1200 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1201 CK_IntegralRealToComplex); 1202 1203 return ComplexType; 1204 } 1205 1206 assert(RHSComplexInt); 1207 1208 QualType RHSEltType = RHSComplexInt->getElementType(); 1209 QualType ScalarType = 1210 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1211 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1212 QualType ComplexType = S.Context.getComplexType(ScalarType); 1213 1214 if (!IsCompAssign) 1215 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1216 CK_IntegralRealToComplex); 1217 return ComplexType; 1218 } 1219 1220 /// UsualArithmeticConversions - Performs various conversions that are common to 1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1222 /// routine returns the first non-arithmetic type found. The client is 1223 /// responsible for emitting appropriate error diagnostics. 1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1225 bool IsCompAssign) { 1226 if (!IsCompAssign) { 1227 LHS = UsualUnaryConversions(LHS.get()); 1228 if (LHS.isInvalid()) 1229 return QualType(); 1230 } 1231 1232 RHS = UsualUnaryConversions(RHS.get()); 1233 if (RHS.isInvalid()) 1234 return QualType(); 1235 1236 // For conversion purposes, we ignore any qualifiers. 1237 // For example, "const float" and "float" are equivalent. 1238 QualType LHSType = 1239 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1240 QualType RHSType = 1241 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1242 1243 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1244 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1245 LHSType = AtomicLHS->getValueType(); 1246 1247 // If both types are identical, no conversion is needed. 1248 if (LHSType == RHSType) 1249 return LHSType; 1250 1251 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1252 // The caller can deal with this (e.g. pointer + int). 1253 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1254 return QualType(); 1255 1256 // Apply unary and bitfield promotions to the LHS's type. 1257 QualType LHSUnpromotedType = LHSType; 1258 if (LHSType->isPromotableIntegerType()) 1259 LHSType = Context.getPromotedIntegerType(LHSType); 1260 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1261 if (!LHSBitfieldPromoteTy.isNull()) 1262 LHSType = LHSBitfieldPromoteTy; 1263 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1264 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1265 1266 // If both types are identical, no conversion is needed. 1267 if (LHSType == RHSType) 1268 return LHSType; 1269 1270 // At this point, we have two different arithmetic types. 1271 1272 // Handle complex types first (C99 6.3.1.8p1). 1273 if (LHSType->isComplexType() || RHSType->isComplexType()) 1274 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1275 IsCompAssign); 1276 1277 // Now handle "real" floating types (i.e. float, double, long double). 1278 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1279 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1280 IsCompAssign); 1281 1282 // Handle GCC complex int extension. 1283 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1284 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1285 IsCompAssign); 1286 1287 // Finally, we have two differing integer types. 1288 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1289 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1290 } 1291 1292 1293 //===----------------------------------------------------------------------===// 1294 // Semantic Analysis for various Expression Types 1295 //===----------------------------------------------------------------------===// 1296 1297 1298 ExprResult 1299 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1300 SourceLocation DefaultLoc, 1301 SourceLocation RParenLoc, 1302 Expr *ControllingExpr, 1303 ArrayRef<ParsedType> ArgTypes, 1304 ArrayRef<Expr *> ArgExprs) { 1305 unsigned NumAssocs = ArgTypes.size(); 1306 assert(NumAssocs == ArgExprs.size()); 1307 1308 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1309 for (unsigned i = 0; i < NumAssocs; ++i) { 1310 if (ArgTypes[i]) 1311 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1312 else 1313 Types[i] = nullptr; 1314 } 1315 1316 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1317 ControllingExpr, 1318 llvm::makeArrayRef(Types, NumAssocs), 1319 ArgExprs); 1320 delete [] Types; 1321 return ER; 1322 } 1323 1324 ExprResult 1325 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1326 SourceLocation DefaultLoc, 1327 SourceLocation RParenLoc, 1328 Expr *ControllingExpr, 1329 ArrayRef<TypeSourceInfo *> Types, 1330 ArrayRef<Expr *> Exprs) { 1331 unsigned NumAssocs = Types.size(); 1332 assert(NumAssocs == Exprs.size()); 1333 if (ControllingExpr->getType()->isPlaceholderType()) { 1334 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1335 if (result.isInvalid()) return ExprError(); 1336 ControllingExpr = result.get(); 1337 } 1338 1339 bool TypeErrorFound = false, 1340 IsResultDependent = ControllingExpr->isTypeDependent(), 1341 ContainsUnexpandedParameterPack 1342 = ControllingExpr->containsUnexpandedParameterPack(); 1343 1344 for (unsigned i = 0; i < NumAssocs; ++i) { 1345 if (Exprs[i]->containsUnexpandedParameterPack()) 1346 ContainsUnexpandedParameterPack = true; 1347 1348 if (Types[i]) { 1349 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1350 ContainsUnexpandedParameterPack = true; 1351 1352 if (Types[i]->getType()->isDependentType()) { 1353 IsResultDependent = true; 1354 } else { 1355 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1356 // complete object type other than a variably modified type." 1357 unsigned D = 0; 1358 if (Types[i]->getType()->isIncompleteType()) 1359 D = diag::err_assoc_type_incomplete; 1360 else if (!Types[i]->getType()->isObjectType()) 1361 D = diag::err_assoc_type_nonobject; 1362 else if (Types[i]->getType()->isVariablyModifiedType()) 1363 D = diag::err_assoc_type_variably_modified; 1364 1365 if (D != 0) { 1366 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1367 << Types[i]->getTypeLoc().getSourceRange() 1368 << Types[i]->getType(); 1369 TypeErrorFound = true; 1370 } 1371 1372 // C11 6.5.1.1p2 "No two generic associations in the same generic 1373 // selection shall specify compatible types." 1374 for (unsigned j = i+1; j < NumAssocs; ++j) 1375 if (Types[j] && !Types[j]->getType()->isDependentType() && 1376 Context.typesAreCompatible(Types[i]->getType(), 1377 Types[j]->getType())) { 1378 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1379 diag::err_assoc_compatible_types) 1380 << Types[j]->getTypeLoc().getSourceRange() 1381 << Types[j]->getType() 1382 << Types[i]->getType(); 1383 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1384 diag::note_compat_assoc) 1385 << Types[i]->getTypeLoc().getSourceRange() 1386 << Types[i]->getType(); 1387 TypeErrorFound = true; 1388 } 1389 } 1390 } 1391 } 1392 if (TypeErrorFound) 1393 return ExprError(); 1394 1395 // If we determined that the generic selection is result-dependent, don't 1396 // try to compute the result expression. 1397 if (IsResultDependent) 1398 return new (Context) GenericSelectionExpr( 1399 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1400 ContainsUnexpandedParameterPack); 1401 1402 SmallVector<unsigned, 1> CompatIndices; 1403 unsigned DefaultIndex = -1U; 1404 for (unsigned i = 0; i < NumAssocs; ++i) { 1405 if (!Types[i]) 1406 DefaultIndex = i; 1407 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1408 Types[i]->getType())) 1409 CompatIndices.push_back(i); 1410 } 1411 1412 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1413 // type compatible with at most one of the types named in its generic 1414 // association list." 1415 if (CompatIndices.size() > 1) { 1416 // We strip parens here because the controlling expression is typically 1417 // parenthesized in macro definitions. 1418 ControllingExpr = ControllingExpr->IgnoreParens(); 1419 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1420 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1421 << (unsigned) CompatIndices.size(); 1422 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1423 E = CompatIndices.end(); I != E; ++I) { 1424 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1425 diag::note_compat_assoc) 1426 << Types[*I]->getTypeLoc().getSourceRange() 1427 << Types[*I]->getType(); 1428 } 1429 return ExprError(); 1430 } 1431 1432 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1433 // its controlling expression shall have type compatible with exactly one of 1434 // the types named in its generic association list." 1435 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1436 // We strip parens here because the controlling expression is typically 1437 // parenthesized in macro definitions. 1438 ControllingExpr = ControllingExpr->IgnoreParens(); 1439 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1440 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1441 return ExprError(); 1442 } 1443 1444 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1445 // type name that is compatible with the type of the controlling expression, 1446 // then the result expression of the generic selection is the expression 1447 // in that generic association. Otherwise, the result expression of the 1448 // generic selection is the expression in the default generic association." 1449 unsigned ResultIndex = 1450 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1451 1452 return new (Context) GenericSelectionExpr( 1453 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1454 ContainsUnexpandedParameterPack, ResultIndex); 1455 } 1456 1457 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1458 /// location of the token and the offset of the ud-suffix within it. 1459 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1460 unsigned Offset) { 1461 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1462 S.getLangOpts()); 1463 } 1464 1465 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1466 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1467 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1468 IdentifierInfo *UDSuffix, 1469 SourceLocation UDSuffixLoc, 1470 ArrayRef<Expr*> Args, 1471 SourceLocation LitEndLoc) { 1472 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1473 1474 QualType ArgTy[2]; 1475 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1476 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1477 if (ArgTy[ArgIdx]->isArrayType()) 1478 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1479 } 1480 1481 DeclarationName OpName = 1482 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1483 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1484 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1485 1486 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1487 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1488 /*AllowRaw*/false, /*AllowTemplate*/false, 1489 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1490 return ExprError(); 1491 1492 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1493 } 1494 1495 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1496 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1497 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1498 /// multiple tokens. However, the common case is that StringToks points to one 1499 /// string. 1500 /// 1501 ExprResult 1502 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1503 assert(!StringToks.empty() && "Must have at least one string!"); 1504 1505 StringLiteralParser Literal(StringToks, PP); 1506 if (Literal.hadError) 1507 return ExprError(); 1508 1509 SmallVector<SourceLocation, 4> StringTokLocs; 1510 for (unsigned i = 0; i != StringToks.size(); ++i) 1511 StringTokLocs.push_back(StringToks[i].getLocation()); 1512 1513 QualType CharTy = Context.CharTy; 1514 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1515 if (Literal.isWide()) { 1516 CharTy = Context.getWideCharType(); 1517 Kind = StringLiteral::Wide; 1518 } else if (Literal.isUTF8()) { 1519 Kind = StringLiteral::UTF8; 1520 } else if (Literal.isUTF16()) { 1521 CharTy = Context.Char16Ty; 1522 Kind = StringLiteral::UTF16; 1523 } else if (Literal.isUTF32()) { 1524 CharTy = Context.Char32Ty; 1525 Kind = StringLiteral::UTF32; 1526 } else if (Literal.isPascal()) { 1527 CharTy = Context.UnsignedCharTy; 1528 } 1529 1530 QualType CharTyConst = CharTy; 1531 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1532 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1533 CharTyConst.addConst(); 1534 1535 // Get an array type for the string, according to C99 6.4.5. This includes 1536 // the nul terminator character as well as the string length for pascal 1537 // strings. 1538 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1539 llvm::APInt(32, Literal.GetNumStringChars()+1), 1540 ArrayType::Normal, 0); 1541 1542 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1543 if (getLangOpts().OpenCL) { 1544 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1545 } 1546 1547 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1548 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1549 Kind, Literal.Pascal, StrTy, 1550 &StringTokLocs[0], 1551 StringTokLocs.size()); 1552 if (Literal.getUDSuffix().empty()) 1553 return Lit; 1554 1555 // We're building a user-defined literal. 1556 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1557 SourceLocation UDSuffixLoc = 1558 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1559 Literal.getUDSuffixOffset()); 1560 1561 // Make sure we're allowed user-defined literals here. 1562 if (!UDLScope) 1563 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1564 1565 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1566 // operator "" X (str, len) 1567 QualType SizeType = Context.getSizeType(); 1568 1569 DeclarationName OpName = 1570 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1571 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1572 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1573 1574 QualType ArgTy[] = { 1575 Context.getArrayDecayedType(StrTy), SizeType 1576 }; 1577 1578 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1579 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1580 /*AllowRaw*/false, /*AllowTemplate*/false, 1581 /*AllowStringTemplate*/true)) { 1582 1583 case LOLR_Cooked: { 1584 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1585 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1586 StringTokLocs[0]); 1587 Expr *Args[] = { Lit, LenArg }; 1588 1589 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1590 } 1591 1592 case LOLR_StringTemplate: { 1593 TemplateArgumentListInfo ExplicitArgs; 1594 1595 unsigned CharBits = Context.getIntWidth(CharTy); 1596 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1597 llvm::APSInt Value(CharBits, CharIsUnsigned); 1598 1599 TemplateArgument TypeArg(CharTy); 1600 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1601 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1602 1603 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1604 Value = Lit->getCodeUnit(I); 1605 TemplateArgument Arg(Context, Value, CharTy); 1606 TemplateArgumentLocInfo ArgInfo; 1607 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1608 } 1609 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1610 &ExplicitArgs); 1611 } 1612 case LOLR_Raw: 1613 case LOLR_Template: 1614 llvm_unreachable("unexpected literal operator lookup result"); 1615 case LOLR_Error: 1616 return ExprError(); 1617 } 1618 llvm_unreachable("unexpected literal operator lookup result"); 1619 } 1620 1621 ExprResult 1622 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1623 SourceLocation Loc, 1624 const CXXScopeSpec *SS) { 1625 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1626 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1627 } 1628 1629 /// BuildDeclRefExpr - Build an expression that references a 1630 /// declaration that does not require a closure capture. 1631 ExprResult 1632 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1633 const DeclarationNameInfo &NameInfo, 1634 const CXXScopeSpec *SS, NamedDecl *FoundD, 1635 const TemplateArgumentListInfo *TemplateArgs) { 1636 if (getLangOpts().CUDA) 1637 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1638 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1639 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1640 CalleeTarget = IdentifyCUDATarget(Callee); 1641 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1642 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1643 << CalleeTarget << D->getIdentifier() << CallerTarget; 1644 Diag(D->getLocation(), diag::note_previous_decl) 1645 << D->getIdentifier(); 1646 return ExprError(); 1647 } 1648 } 1649 1650 bool refersToEnclosingScope = 1651 (CurContext != D->getDeclContext() && 1652 D->getDeclContext()->isFunctionOrMethod()) || 1653 (isa<VarDecl>(D) && 1654 cast<VarDecl>(D)->isInitCapture()); 1655 1656 DeclRefExpr *E; 1657 if (isa<VarTemplateSpecializationDecl>(D)) { 1658 VarTemplateSpecializationDecl *VarSpec = 1659 cast<VarTemplateSpecializationDecl>(D); 1660 1661 E = DeclRefExpr::Create( 1662 Context, 1663 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1664 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1665 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1666 } else { 1667 assert(!TemplateArgs && "No template arguments for non-variable" 1668 " template specialization references"); 1669 E = DeclRefExpr::Create( 1670 Context, 1671 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1672 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1673 } 1674 1675 MarkDeclRefReferenced(E); 1676 1677 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1678 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1679 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1680 recordUseOfEvaluatedWeak(E); 1681 1682 // Just in case we're building an illegal pointer-to-member. 1683 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1684 if (FD && FD->isBitField()) 1685 E->setObjectKind(OK_BitField); 1686 1687 return E; 1688 } 1689 1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1691 /// possibly a list of template arguments. 1692 /// 1693 /// If this produces template arguments, it is permitted to call 1694 /// DecomposeTemplateName. 1695 /// 1696 /// This actually loses a lot of source location information for 1697 /// non-standard name kinds; we should consider preserving that in 1698 /// some way. 1699 void 1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1701 TemplateArgumentListInfo &Buffer, 1702 DeclarationNameInfo &NameInfo, 1703 const TemplateArgumentListInfo *&TemplateArgs) { 1704 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1705 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1706 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1707 1708 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1709 Id.TemplateId->NumArgs); 1710 translateTemplateArguments(TemplateArgsPtr, Buffer); 1711 1712 TemplateName TName = Id.TemplateId->Template.get(); 1713 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1714 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1715 TemplateArgs = &Buffer; 1716 } else { 1717 NameInfo = GetNameFromUnqualifiedId(Id); 1718 TemplateArgs = nullptr; 1719 } 1720 } 1721 1722 /// Diagnose an empty lookup. 1723 /// 1724 /// \return false if new lookup candidates were found 1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1726 CorrectionCandidateCallback &CCC, 1727 TemplateArgumentListInfo *ExplicitTemplateArgs, 1728 ArrayRef<Expr *> Args) { 1729 DeclarationName Name = R.getLookupName(); 1730 1731 unsigned diagnostic = diag::err_undeclared_var_use; 1732 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1733 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1734 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1735 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1736 diagnostic = diag::err_undeclared_use; 1737 diagnostic_suggest = diag::err_undeclared_use_suggest; 1738 } 1739 1740 // If the original lookup was an unqualified lookup, fake an 1741 // unqualified lookup. This is useful when (for example) the 1742 // original lookup would not have found something because it was a 1743 // dependent name. 1744 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1745 ? CurContext : nullptr; 1746 while (DC) { 1747 if (isa<CXXRecordDecl>(DC)) { 1748 LookupQualifiedName(R, DC); 1749 1750 if (!R.empty()) { 1751 // Don't give errors about ambiguities in this lookup. 1752 R.suppressDiagnostics(); 1753 1754 // During a default argument instantiation the CurContext points 1755 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1756 // function parameter list, hence add an explicit check. 1757 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1758 ActiveTemplateInstantiations.back().Kind == 1759 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1760 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1761 bool isInstance = CurMethod && 1762 CurMethod->isInstance() && 1763 DC == CurMethod->getParent() && !isDefaultArgument; 1764 1765 1766 // Give a code modification hint to insert 'this->'. 1767 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1768 // Actually quite difficult! 1769 if (getLangOpts().MSVCCompat) 1770 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1771 if (isInstance) { 1772 Diag(R.getNameLoc(), diagnostic) << Name 1773 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1774 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1775 CallsUndergoingInstantiation.back()->getCallee()); 1776 1777 CXXMethodDecl *DepMethod; 1778 if (CurMethod->isDependentContext()) 1779 DepMethod = CurMethod; 1780 else if (CurMethod->getTemplatedKind() == 1781 FunctionDecl::TK_FunctionTemplateSpecialization) 1782 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1783 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1784 else 1785 DepMethod = cast<CXXMethodDecl>( 1786 CurMethod->getInstantiatedFromMemberFunction()); 1787 assert(DepMethod && "No template pattern found"); 1788 1789 QualType DepThisType = DepMethod->getThisType(Context); 1790 CheckCXXThisCapture(R.getNameLoc()); 1791 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1792 R.getNameLoc(), DepThisType, false); 1793 TemplateArgumentListInfo TList; 1794 if (ULE->hasExplicitTemplateArgs()) 1795 ULE->copyTemplateArgumentsInto(TList); 1796 1797 CXXScopeSpec SS; 1798 SS.Adopt(ULE->getQualifierLoc()); 1799 CXXDependentScopeMemberExpr *DepExpr = 1800 CXXDependentScopeMemberExpr::Create( 1801 Context, DepThis, DepThisType, true, SourceLocation(), 1802 SS.getWithLocInContext(Context), 1803 ULE->getTemplateKeywordLoc(), nullptr, 1804 R.getLookupNameInfo(), 1805 ULE->hasExplicitTemplateArgs() ? &TList : nullptr); 1806 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1807 } else { 1808 Diag(R.getNameLoc(), diagnostic) << Name; 1809 } 1810 1811 // Do we really want to note all of these? 1812 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1813 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1814 1815 // Return true if we are inside a default argument instantiation 1816 // and the found name refers to an instance member function, otherwise 1817 // the function calling DiagnoseEmptyLookup will try to create an 1818 // implicit member call and this is wrong for default argument. 1819 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1820 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1821 return true; 1822 } 1823 1824 // Tell the callee to try to recover. 1825 return false; 1826 } 1827 1828 R.clear(); 1829 } 1830 1831 // In Microsoft mode, if we are performing lookup from within a friend 1832 // function definition declared at class scope then we must set 1833 // DC to the lexical parent to be able to search into the parent 1834 // class. 1835 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1836 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1837 DC->getLexicalParent()->isRecord()) 1838 DC = DC->getLexicalParent(); 1839 else 1840 DC = DC->getParent(); 1841 } 1842 1843 // We didn't find anything, so try to correct for a typo. 1844 TypoCorrection Corrected; 1845 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1846 S, &SS, CCC, CTK_ErrorRecovery))) { 1847 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1848 bool DroppedSpecifier = 1849 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1850 R.setLookupName(Corrected.getCorrection()); 1851 1852 bool AcceptableWithRecovery = false; 1853 bool AcceptableWithoutRecovery = false; 1854 NamedDecl *ND = Corrected.getCorrectionDecl(); 1855 if (ND) { 1856 if (Corrected.isOverloaded()) { 1857 OverloadCandidateSet OCS(R.getNameLoc(), 1858 OverloadCandidateSet::CSK_Normal); 1859 OverloadCandidateSet::iterator Best; 1860 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1861 CDEnd = Corrected.end(); 1862 CD != CDEnd; ++CD) { 1863 if (FunctionTemplateDecl *FTD = 1864 dyn_cast<FunctionTemplateDecl>(*CD)) 1865 AddTemplateOverloadCandidate( 1866 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1867 Args, OCS); 1868 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1869 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1870 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1871 Args, OCS); 1872 } 1873 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1874 case OR_Success: 1875 ND = Best->Function; 1876 Corrected.setCorrectionDecl(ND); 1877 break; 1878 default: 1879 // FIXME: Arbitrarily pick the first declaration for the note. 1880 Corrected.setCorrectionDecl(ND); 1881 break; 1882 } 1883 } 1884 R.addDecl(ND); 1885 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1886 CXXRecordDecl *Record = nullptr; 1887 if (Corrected.getCorrectionSpecifier()) { 1888 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1889 Record = Ty->getAsCXXRecordDecl(); 1890 } 1891 if (!Record) 1892 Record = cast<CXXRecordDecl>( 1893 ND->getDeclContext()->getRedeclContext()); 1894 R.setNamingClass(Record); 1895 } 1896 1897 AcceptableWithRecovery = 1898 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1899 // FIXME: If we ended up with a typo for a type name or 1900 // Objective-C class name, we're in trouble because the parser 1901 // is in the wrong place to recover. Suggest the typo 1902 // correction, but don't make it a fix-it since we're not going 1903 // to recover well anyway. 1904 AcceptableWithoutRecovery = 1905 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1906 } else { 1907 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1908 // because we aren't able to recover. 1909 AcceptableWithoutRecovery = true; 1910 } 1911 1912 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1913 unsigned NoteID = (Corrected.getCorrectionDecl() && 1914 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1915 ? diag::note_implicit_param_decl 1916 : diag::note_previous_decl; 1917 if (SS.isEmpty()) 1918 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1919 PDiag(NoteID), AcceptableWithRecovery); 1920 else 1921 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1922 << Name << computeDeclContext(SS, false) 1923 << DroppedSpecifier << SS.getRange(), 1924 PDiag(NoteID), AcceptableWithRecovery); 1925 1926 // Tell the callee whether to try to recover. 1927 return !AcceptableWithRecovery; 1928 } 1929 } 1930 R.clear(); 1931 1932 // Emit a special diagnostic for failed member lookups. 1933 // FIXME: computing the declaration context might fail here (?) 1934 if (!SS.isEmpty()) { 1935 Diag(R.getNameLoc(), diag::err_no_member) 1936 << Name << computeDeclContext(SS, false) 1937 << SS.getRange(); 1938 return true; 1939 } 1940 1941 // Give up, we can't recover. 1942 Diag(R.getNameLoc(), diagnostic) << Name; 1943 return true; 1944 } 1945 1946 /// In Microsoft mode, if we are inside a template class whose parent class has 1947 /// dependent base classes, and we can't resolve an unqualified identifier, then 1948 /// assume the identifier is a member of a dependent base class. We can only 1949 /// recover successfully in static methods, instance methods, and other contexts 1950 /// where 'this' is available. This doesn't precisely match MSVC's 1951 /// instantiation model, but it's close enough. 1952 static Expr * 1953 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1954 DeclarationNameInfo &NameInfo, 1955 SourceLocation TemplateKWLoc, 1956 const TemplateArgumentListInfo *TemplateArgs) { 1957 // Only try to recover from lookup into dependent bases in static methods or 1958 // contexts where 'this' is available. 1959 QualType ThisType = S.getCurrentThisType(); 1960 const CXXRecordDecl *RD = nullptr; 1961 if (!ThisType.isNull()) 1962 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1963 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1964 RD = MD->getParent(); 1965 if (!RD || !RD->hasAnyDependentBases()) 1966 return nullptr; 1967 1968 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1969 // is available, suggest inserting 'this->' as a fixit. 1970 SourceLocation Loc = NameInfo.getLoc(); 1971 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1972 DB << NameInfo.getName() << RD; 1973 1974 if (!ThisType.isNull()) { 1975 DB << FixItHint::CreateInsertion(Loc, "this->"); 1976 return CXXDependentScopeMemberExpr::Create( 1977 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 1978 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 1979 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 1980 } 1981 1982 // Synthesize a fake NNS that points to the derived class. This will 1983 // perform name lookup during template instantiation. 1984 CXXScopeSpec SS; 1985 auto *NNS = 1986 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 1987 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 1988 return DependentScopeDeclRefExpr::Create( 1989 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 1990 TemplateArgs); 1991 } 1992 1993 ExprResult Sema::ActOnIdExpression(Scope *S, 1994 CXXScopeSpec &SS, 1995 SourceLocation TemplateKWLoc, 1996 UnqualifiedId &Id, 1997 bool HasTrailingLParen, 1998 bool IsAddressOfOperand, 1999 CorrectionCandidateCallback *CCC, 2000 bool IsInlineAsmIdentifier) { 2001 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2002 "cannot be direct & operand and have a trailing lparen"); 2003 if (SS.isInvalid()) 2004 return ExprError(); 2005 2006 TemplateArgumentListInfo TemplateArgsBuffer; 2007 2008 // Decompose the UnqualifiedId into the following data. 2009 DeclarationNameInfo NameInfo; 2010 const TemplateArgumentListInfo *TemplateArgs; 2011 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2012 2013 DeclarationName Name = NameInfo.getName(); 2014 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2015 SourceLocation NameLoc = NameInfo.getLoc(); 2016 2017 // C++ [temp.dep.expr]p3: 2018 // An id-expression is type-dependent if it contains: 2019 // -- an identifier that was declared with a dependent type, 2020 // (note: handled after lookup) 2021 // -- a template-id that is dependent, 2022 // (note: handled in BuildTemplateIdExpr) 2023 // -- a conversion-function-id that specifies a dependent type, 2024 // -- a nested-name-specifier that contains a class-name that 2025 // names a dependent type. 2026 // Determine whether this is a member of an unknown specialization; 2027 // we need to handle these differently. 2028 bool DependentID = false; 2029 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2030 Name.getCXXNameType()->isDependentType()) { 2031 DependentID = true; 2032 } else if (SS.isSet()) { 2033 if (DeclContext *DC = computeDeclContext(SS, false)) { 2034 if (RequireCompleteDeclContext(SS, DC)) 2035 return ExprError(); 2036 } else { 2037 DependentID = true; 2038 } 2039 } 2040 2041 if (DependentID) 2042 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2043 IsAddressOfOperand, TemplateArgs); 2044 2045 // Perform the required lookup. 2046 LookupResult R(*this, NameInfo, 2047 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2048 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2049 if (TemplateArgs) { 2050 // Lookup the template name again to correctly establish the context in 2051 // which it was found. This is really unfortunate as we already did the 2052 // lookup to determine that it was a template name in the first place. If 2053 // this becomes a performance hit, we can work harder to preserve those 2054 // results until we get here but it's likely not worth it. 2055 bool MemberOfUnknownSpecialization; 2056 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2057 MemberOfUnknownSpecialization); 2058 2059 if (MemberOfUnknownSpecialization || 2060 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2061 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2062 IsAddressOfOperand, TemplateArgs); 2063 } else { 2064 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2065 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2066 2067 // If the result might be in a dependent base class, this is a dependent 2068 // id-expression. 2069 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2070 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2071 IsAddressOfOperand, TemplateArgs); 2072 2073 // If this reference is in an Objective-C method, then we need to do 2074 // some special Objective-C lookup, too. 2075 if (IvarLookupFollowUp) { 2076 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2077 if (E.isInvalid()) 2078 return ExprError(); 2079 2080 if (Expr *Ex = E.getAs<Expr>()) 2081 return Ex; 2082 } 2083 } 2084 2085 if (R.isAmbiguous()) 2086 return ExprError(); 2087 2088 // This could be an implicitly declared function reference (legal in C90, 2089 // extension in C99, forbidden in C++). 2090 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2091 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2092 if (D) R.addDecl(D); 2093 } 2094 2095 // Determine whether this name might be a candidate for 2096 // argument-dependent lookup. 2097 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2098 2099 if (R.empty() && !ADL) { 2100 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2101 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2102 TemplateKWLoc, TemplateArgs)) 2103 return E; 2104 } 2105 2106 // Don't diagnose an empty lookup for inline assembly. 2107 if (IsInlineAsmIdentifier) 2108 return ExprError(); 2109 2110 // If this name wasn't predeclared and if this is not a function 2111 // call, diagnose the problem. 2112 CorrectionCandidateCallback DefaultValidator; 2113 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2114 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2115 "Typo correction callback misconfigured"); 2116 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2117 return ExprError(); 2118 2119 assert(!R.empty() && 2120 "DiagnoseEmptyLookup returned false but added no results"); 2121 2122 // If we found an Objective-C instance variable, let 2123 // LookupInObjCMethod build the appropriate expression to 2124 // reference the ivar. 2125 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2126 R.clear(); 2127 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2128 // In a hopelessly buggy code, Objective-C instance variable 2129 // lookup fails and no expression will be built to reference it. 2130 if (!E.isInvalid() && !E.get()) 2131 return ExprError(); 2132 return E; 2133 } 2134 } 2135 2136 // This is guaranteed from this point on. 2137 assert(!R.empty() || ADL); 2138 2139 // Check whether this might be a C++ implicit instance member access. 2140 // C++ [class.mfct.non-static]p3: 2141 // When an id-expression that is not part of a class member access 2142 // syntax and not used to form a pointer to member is used in the 2143 // body of a non-static member function of class X, if name lookup 2144 // resolves the name in the id-expression to a non-static non-type 2145 // member of some class C, the id-expression is transformed into a 2146 // class member access expression using (*this) as the 2147 // postfix-expression to the left of the . operator. 2148 // 2149 // But we don't actually need to do this for '&' operands if R 2150 // resolved to a function or overloaded function set, because the 2151 // expression is ill-formed if it actually works out to be a 2152 // non-static member function: 2153 // 2154 // C++ [expr.ref]p4: 2155 // Otherwise, if E1.E2 refers to a non-static member function. . . 2156 // [t]he expression can be used only as the left-hand operand of a 2157 // member function call. 2158 // 2159 // There are other safeguards against such uses, but it's important 2160 // to get this right here so that we don't end up making a 2161 // spuriously dependent expression if we're inside a dependent 2162 // instance method. 2163 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2164 bool MightBeImplicitMember; 2165 if (!IsAddressOfOperand) 2166 MightBeImplicitMember = true; 2167 else if (!SS.isEmpty()) 2168 MightBeImplicitMember = false; 2169 else if (R.isOverloadedResult()) 2170 MightBeImplicitMember = false; 2171 else if (R.isUnresolvableResult()) 2172 MightBeImplicitMember = true; 2173 else 2174 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2175 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2176 isa<MSPropertyDecl>(R.getFoundDecl()); 2177 2178 if (MightBeImplicitMember) 2179 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2180 R, TemplateArgs); 2181 } 2182 2183 if (TemplateArgs || TemplateKWLoc.isValid()) { 2184 2185 // In C++1y, if this is a variable template id, then check it 2186 // in BuildTemplateIdExpr(). 2187 // The single lookup result must be a variable template declaration. 2188 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2189 Id.TemplateId->Kind == TNK_Var_template) { 2190 assert(R.getAsSingle<VarTemplateDecl>() && 2191 "There should only be one declaration found."); 2192 } 2193 2194 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2195 } 2196 2197 return BuildDeclarationNameExpr(SS, R, ADL); 2198 } 2199 2200 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2201 /// declaration name, generally during template instantiation. 2202 /// There's a large number of things which don't need to be done along 2203 /// this path. 2204 ExprResult 2205 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2206 const DeclarationNameInfo &NameInfo, 2207 bool IsAddressOfOperand, 2208 TypeSourceInfo **RecoveryTSI) { 2209 DeclContext *DC = computeDeclContext(SS, false); 2210 if (!DC) 2211 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2212 NameInfo, /*TemplateArgs=*/nullptr); 2213 2214 if (RequireCompleteDeclContext(SS, DC)) 2215 return ExprError(); 2216 2217 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2218 LookupQualifiedName(R, DC); 2219 2220 if (R.isAmbiguous()) 2221 return ExprError(); 2222 2223 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2224 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2225 NameInfo, /*TemplateArgs=*/nullptr); 2226 2227 if (R.empty()) { 2228 Diag(NameInfo.getLoc(), diag::err_no_member) 2229 << NameInfo.getName() << DC << SS.getRange(); 2230 return ExprError(); 2231 } 2232 2233 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2234 // Diagnose a missing typename if this resolved unambiguously to a type in 2235 // a dependent context. If we can recover with a type, downgrade this to 2236 // a warning in Microsoft compatibility mode. 2237 unsigned DiagID = diag::err_typename_missing; 2238 if (RecoveryTSI && getLangOpts().MSVCCompat) 2239 DiagID = diag::ext_typename_missing; 2240 SourceLocation Loc = SS.getBeginLoc(); 2241 auto D = Diag(Loc, DiagID); 2242 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2243 << SourceRange(Loc, NameInfo.getEndLoc()); 2244 2245 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2246 // context. 2247 if (!RecoveryTSI) 2248 return ExprError(); 2249 2250 // Only issue the fixit if we're prepared to recover. 2251 D << FixItHint::CreateInsertion(Loc, "typename "); 2252 2253 // Recover by pretending this was an elaborated type. 2254 QualType Ty = Context.getTypeDeclType(TD); 2255 TypeLocBuilder TLB; 2256 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2257 2258 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2259 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2260 QTL.setElaboratedKeywordLoc(SourceLocation()); 2261 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2262 2263 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2264 2265 return ExprEmpty(); 2266 } 2267 2268 // Defend against this resolving to an implicit member access. We usually 2269 // won't get here if this might be a legitimate a class member (we end up in 2270 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2271 // a pointer-to-member or in an unevaluated context in C++11. 2272 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2273 return BuildPossibleImplicitMemberExpr(SS, 2274 /*TemplateKWLoc=*/SourceLocation(), 2275 R, /*TemplateArgs=*/nullptr); 2276 2277 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2278 } 2279 2280 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2281 /// detected that we're currently inside an ObjC method. Perform some 2282 /// additional lookup. 2283 /// 2284 /// Ideally, most of this would be done by lookup, but there's 2285 /// actually quite a lot of extra work involved. 2286 /// 2287 /// Returns a null sentinel to indicate trivial success. 2288 ExprResult 2289 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2290 IdentifierInfo *II, bool AllowBuiltinCreation) { 2291 SourceLocation Loc = Lookup.getNameLoc(); 2292 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2293 2294 // Check for error condition which is already reported. 2295 if (!CurMethod) 2296 return ExprError(); 2297 2298 // There are two cases to handle here. 1) scoped lookup could have failed, 2299 // in which case we should look for an ivar. 2) scoped lookup could have 2300 // found a decl, but that decl is outside the current instance method (i.e. 2301 // a global variable). In these two cases, we do a lookup for an ivar with 2302 // this name, if the lookup sucedes, we replace it our current decl. 2303 2304 // If we're in a class method, we don't normally want to look for 2305 // ivars. But if we don't find anything else, and there's an 2306 // ivar, that's an error. 2307 bool IsClassMethod = CurMethod->isClassMethod(); 2308 2309 bool LookForIvars; 2310 if (Lookup.empty()) 2311 LookForIvars = true; 2312 else if (IsClassMethod) 2313 LookForIvars = false; 2314 else 2315 LookForIvars = (Lookup.isSingleResult() && 2316 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2317 ObjCInterfaceDecl *IFace = nullptr; 2318 if (LookForIvars) { 2319 IFace = CurMethod->getClassInterface(); 2320 ObjCInterfaceDecl *ClassDeclared; 2321 ObjCIvarDecl *IV = nullptr; 2322 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2323 // Diagnose using an ivar in a class method. 2324 if (IsClassMethod) 2325 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2326 << IV->getDeclName()); 2327 2328 // If we're referencing an invalid decl, just return this as a silent 2329 // error node. The error diagnostic was already emitted on the decl. 2330 if (IV->isInvalidDecl()) 2331 return ExprError(); 2332 2333 // Check if referencing a field with __attribute__((deprecated)). 2334 if (DiagnoseUseOfDecl(IV, Loc)) 2335 return ExprError(); 2336 2337 // Diagnose the use of an ivar outside of the declaring class. 2338 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2339 !declaresSameEntity(ClassDeclared, IFace) && 2340 !getLangOpts().DebuggerSupport) 2341 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2342 2343 // FIXME: This should use a new expr for a direct reference, don't 2344 // turn this into Self->ivar, just return a BareIVarExpr or something. 2345 IdentifierInfo &II = Context.Idents.get("self"); 2346 UnqualifiedId SelfName; 2347 SelfName.setIdentifier(&II, SourceLocation()); 2348 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2349 CXXScopeSpec SelfScopeSpec; 2350 SourceLocation TemplateKWLoc; 2351 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2352 SelfName, false, false); 2353 if (SelfExpr.isInvalid()) 2354 return ExprError(); 2355 2356 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2357 if (SelfExpr.isInvalid()) 2358 return ExprError(); 2359 2360 MarkAnyDeclReferenced(Loc, IV, true); 2361 2362 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2363 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2364 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2365 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2366 2367 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2368 Loc, IV->getLocation(), 2369 SelfExpr.get(), 2370 true, true); 2371 2372 if (getLangOpts().ObjCAutoRefCount) { 2373 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2374 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2375 recordUseOfEvaluatedWeak(Result); 2376 } 2377 if (CurContext->isClosure()) 2378 Diag(Loc, diag::warn_implicitly_retains_self) 2379 << FixItHint::CreateInsertion(Loc, "self->"); 2380 } 2381 2382 return Result; 2383 } 2384 } else if (CurMethod->isInstanceMethod()) { 2385 // We should warn if a local variable hides an ivar. 2386 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2387 ObjCInterfaceDecl *ClassDeclared; 2388 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2389 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2390 declaresSameEntity(IFace, ClassDeclared)) 2391 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2392 } 2393 } 2394 } else if (Lookup.isSingleResult() && 2395 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2396 // If accessing a stand-alone ivar in a class method, this is an error. 2397 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2398 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2399 << IV->getDeclName()); 2400 } 2401 2402 if (Lookup.empty() && II && AllowBuiltinCreation) { 2403 // FIXME. Consolidate this with similar code in LookupName. 2404 if (unsigned BuiltinID = II->getBuiltinID()) { 2405 if (!(getLangOpts().CPlusPlus && 2406 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2407 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2408 S, Lookup.isForRedeclaration(), 2409 Lookup.getNameLoc()); 2410 if (D) Lookup.addDecl(D); 2411 } 2412 } 2413 } 2414 // Sentinel value saying that we didn't do anything special. 2415 return ExprResult((Expr *)nullptr); 2416 } 2417 2418 /// \brief Cast a base object to a member's actual type. 2419 /// 2420 /// Logically this happens in three phases: 2421 /// 2422 /// * First we cast from the base type to the naming class. 2423 /// The naming class is the class into which we were looking 2424 /// when we found the member; it's the qualifier type if a 2425 /// qualifier was provided, and otherwise it's the base type. 2426 /// 2427 /// * Next we cast from the naming class to the declaring class. 2428 /// If the member we found was brought into a class's scope by 2429 /// a using declaration, this is that class; otherwise it's 2430 /// the class declaring the member. 2431 /// 2432 /// * Finally we cast from the declaring class to the "true" 2433 /// declaring class of the member. This conversion does not 2434 /// obey access control. 2435 ExprResult 2436 Sema::PerformObjectMemberConversion(Expr *From, 2437 NestedNameSpecifier *Qualifier, 2438 NamedDecl *FoundDecl, 2439 NamedDecl *Member) { 2440 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2441 if (!RD) 2442 return From; 2443 2444 QualType DestRecordType; 2445 QualType DestType; 2446 QualType FromRecordType; 2447 QualType FromType = From->getType(); 2448 bool PointerConversions = false; 2449 if (isa<FieldDecl>(Member)) { 2450 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2451 2452 if (FromType->getAs<PointerType>()) { 2453 DestType = Context.getPointerType(DestRecordType); 2454 FromRecordType = FromType->getPointeeType(); 2455 PointerConversions = true; 2456 } else { 2457 DestType = DestRecordType; 2458 FromRecordType = FromType; 2459 } 2460 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2461 if (Method->isStatic()) 2462 return From; 2463 2464 DestType = Method->getThisType(Context); 2465 DestRecordType = DestType->getPointeeType(); 2466 2467 if (FromType->getAs<PointerType>()) { 2468 FromRecordType = FromType->getPointeeType(); 2469 PointerConversions = true; 2470 } else { 2471 FromRecordType = FromType; 2472 DestType = DestRecordType; 2473 } 2474 } else { 2475 // No conversion necessary. 2476 return From; 2477 } 2478 2479 if (DestType->isDependentType() || FromType->isDependentType()) 2480 return From; 2481 2482 // If the unqualified types are the same, no conversion is necessary. 2483 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2484 return From; 2485 2486 SourceRange FromRange = From->getSourceRange(); 2487 SourceLocation FromLoc = FromRange.getBegin(); 2488 2489 ExprValueKind VK = From->getValueKind(); 2490 2491 // C++ [class.member.lookup]p8: 2492 // [...] Ambiguities can often be resolved by qualifying a name with its 2493 // class name. 2494 // 2495 // If the member was a qualified name and the qualified referred to a 2496 // specific base subobject type, we'll cast to that intermediate type 2497 // first and then to the object in which the member is declared. That allows 2498 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2499 // 2500 // class Base { public: int x; }; 2501 // class Derived1 : public Base { }; 2502 // class Derived2 : public Base { }; 2503 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2504 // 2505 // void VeryDerived::f() { 2506 // x = 17; // error: ambiguous base subobjects 2507 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2508 // } 2509 if (Qualifier && Qualifier->getAsType()) { 2510 QualType QType = QualType(Qualifier->getAsType(), 0); 2511 assert(QType->isRecordType() && "lookup done with non-record type"); 2512 2513 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2514 2515 // In C++98, the qualifier type doesn't actually have to be a base 2516 // type of the object type, in which case we just ignore it. 2517 // Otherwise build the appropriate casts. 2518 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2519 CXXCastPath BasePath; 2520 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2521 FromLoc, FromRange, &BasePath)) 2522 return ExprError(); 2523 2524 if (PointerConversions) 2525 QType = Context.getPointerType(QType); 2526 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2527 VK, &BasePath).get(); 2528 2529 FromType = QType; 2530 FromRecordType = QRecordType; 2531 2532 // If the qualifier type was the same as the destination type, 2533 // we're done. 2534 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2535 return From; 2536 } 2537 } 2538 2539 bool IgnoreAccess = false; 2540 2541 // If we actually found the member through a using declaration, cast 2542 // down to the using declaration's type. 2543 // 2544 // Pointer equality is fine here because only one declaration of a 2545 // class ever has member declarations. 2546 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2547 assert(isa<UsingShadowDecl>(FoundDecl)); 2548 QualType URecordType = Context.getTypeDeclType( 2549 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2550 2551 // We only need to do this if the naming-class to declaring-class 2552 // conversion is non-trivial. 2553 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2554 assert(IsDerivedFrom(FromRecordType, URecordType)); 2555 CXXCastPath BasePath; 2556 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2557 FromLoc, FromRange, &BasePath)) 2558 return ExprError(); 2559 2560 QualType UType = URecordType; 2561 if (PointerConversions) 2562 UType = Context.getPointerType(UType); 2563 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2564 VK, &BasePath).get(); 2565 FromType = UType; 2566 FromRecordType = URecordType; 2567 } 2568 2569 // We don't do access control for the conversion from the 2570 // declaring class to the true declaring class. 2571 IgnoreAccess = true; 2572 } 2573 2574 CXXCastPath BasePath; 2575 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2576 FromLoc, FromRange, &BasePath, 2577 IgnoreAccess)) 2578 return ExprError(); 2579 2580 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2581 VK, &BasePath); 2582 } 2583 2584 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2585 const LookupResult &R, 2586 bool HasTrailingLParen) { 2587 // Only when used directly as the postfix-expression of a call. 2588 if (!HasTrailingLParen) 2589 return false; 2590 2591 // Never if a scope specifier was provided. 2592 if (SS.isSet()) 2593 return false; 2594 2595 // Only in C++ or ObjC++. 2596 if (!getLangOpts().CPlusPlus) 2597 return false; 2598 2599 // Turn off ADL when we find certain kinds of declarations during 2600 // normal lookup: 2601 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2602 NamedDecl *D = *I; 2603 2604 // C++0x [basic.lookup.argdep]p3: 2605 // -- a declaration of a class member 2606 // Since using decls preserve this property, we check this on the 2607 // original decl. 2608 if (D->isCXXClassMember()) 2609 return false; 2610 2611 // C++0x [basic.lookup.argdep]p3: 2612 // -- a block-scope function declaration that is not a 2613 // using-declaration 2614 // NOTE: we also trigger this for function templates (in fact, we 2615 // don't check the decl type at all, since all other decl types 2616 // turn off ADL anyway). 2617 if (isa<UsingShadowDecl>(D)) 2618 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2619 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2620 return false; 2621 2622 // C++0x [basic.lookup.argdep]p3: 2623 // -- a declaration that is neither a function or a function 2624 // template 2625 // And also for builtin functions. 2626 if (isa<FunctionDecl>(D)) { 2627 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2628 2629 // But also builtin functions. 2630 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2631 return false; 2632 } else if (!isa<FunctionTemplateDecl>(D)) 2633 return false; 2634 } 2635 2636 return true; 2637 } 2638 2639 2640 /// Diagnoses obvious problems with the use of the given declaration 2641 /// as an expression. This is only actually called for lookups that 2642 /// were not overloaded, and it doesn't promise that the declaration 2643 /// will in fact be used. 2644 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2645 if (isa<TypedefNameDecl>(D)) { 2646 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2647 return true; 2648 } 2649 2650 if (isa<ObjCInterfaceDecl>(D)) { 2651 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2652 return true; 2653 } 2654 2655 if (isa<NamespaceDecl>(D)) { 2656 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2657 return true; 2658 } 2659 2660 return false; 2661 } 2662 2663 ExprResult 2664 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2665 LookupResult &R, 2666 bool NeedsADL) { 2667 // If this is a single, fully-resolved result and we don't need ADL, 2668 // just build an ordinary singleton decl ref. 2669 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2670 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2671 R.getRepresentativeDecl()); 2672 2673 // We only need to check the declaration if there's exactly one 2674 // result, because in the overloaded case the results can only be 2675 // functions and function templates. 2676 if (R.isSingleResult() && 2677 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2678 return ExprError(); 2679 2680 // Otherwise, just build an unresolved lookup expression. Suppress 2681 // any lookup-related diagnostics; we'll hash these out later, when 2682 // we've picked a target. 2683 R.suppressDiagnostics(); 2684 2685 UnresolvedLookupExpr *ULE 2686 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2687 SS.getWithLocInContext(Context), 2688 R.getLookupNameInfo(), 2689 NeedsADL, R.isOverloadedResult(), 2690 R.begin(), R.end()); 2691 2692 return ULE; 2693 } 2694 2695 /// \brief Complete semantic analysis for a reference to the given declaration. 2696 ExprResult Sema::BuildDeclarationNameExpr( 2697 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2698 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2699 assert(D && "Cannot refer to a NULL declaration"); 2700 assert(!isa<FunctionTemplateDecl>(D) && 2701 "Cannot refer unambiguously to a function template"); 2702 2703 SourceLocation Loc = NameInfo.getLoc(); 2704 if (CheckDeclInExpr(*this, Loc, D)) 2705 return ExprError(); 2706 2707 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2708 // Specifically diagnose references to class templates that are missing 2709 // a template argument list. 2710 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2711 << Template << SS.getRange(); 2712 Diag(Template->getLocation(), diag::note_template_decl_here); 2713 return ExprError(); 2714 } 2715 2716 // Make sure that we're referring to a value. 2717 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2718 if (!VD) { 2719 Diag(Loc, diag::err_ref_non_value) 2720 << D << SS.getRange(); 2721 Diag(D->getLocation(), diag::note_declared_at); 2722 return ExprError(); 2723 } 2724 2725 // Check whether this declaration can be used. Note that we suppress 2726 // this check when we're going to perform argument-dependent lookup 2727 // on this function name, because this might not be the function 2728 // that overload resolution actually selects. 2729 if (DiagnoseUseOfDecl(VD, Loc)) 2730 return ExprError(); 2731 2732 // Only create DeclRefExpr's for valid Decl's. 2733 if (VD->isInvalidDecl()) 2734 return ExprError(); 2735 2736 // Handle members of anonymous structs and unions. If we got here, 2737 // and the reference is to a class member indirect field, then this 2738 // must be the subject of a pointer-to-member expression. 2739 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2740 if (!indirectField->isCXXClassMember()) 2741 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2742 indirectField); 2743 2744 { 2745 QualType type = VD->getType(); 2746 ExprValueKind valueKind = VK_RValue; 2747 2748 switch (D->getKind()) { 2749 // Ignore all the non-ValueDecl kinds. 2750 #define ABSTRACT_DECL(kind) 2751 #define VALUE(type, base) 2752 #define DECL(type, base) \ 2753 case Decl::type: 2754 #include "clang/AST/DeclNodes.inc" 2755 llvm_unreachable("invalid value decl kind"); 2756 2757 // These shouldn't make it here. 2758 case Decl::ObjCAtDefsField: 2759 case Decl::ObjCIvar: 2760 llvm_unreachable("forming non-member reference to ivar?"); 2761 2762 // Enum constants are always r-values and never references. 2763 // Unresolved using declarations are dependent. 2764 case Decl::EnumConstant: 2765 case Decl::UnresolvedUsingValue: 2766 valueKind = VK_RValue; 2767 break; 2768 2769 // Fields and indirect fields that got here must be for 2770 // pointer-to-member expressions; we just call them l-values for 2771 // internal consistency, because this subexpression doesn't really 2772 // exist in the high-level semantics. 2773 case Decl::Field: 2774 case Decl::IndirectField: 2775 assert(getLangOpts().CPlusPlus && 2776 "building reference to field in C?"); 2777 2778 // These can't have reference type in well-formed programs, but 2779 // for internal consistency we do this anyway. 2780 type = type.getNonReferenceType(); 2781 valueKind = VK_LValue; 2782 break; 2783 2784 // Non-type template parameters are either l-values or r-values 2785 // depending on the type. 2786 case Decl::NonTypeTemplateParm: { 2787 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2788 type = reftype->getPointeeType(); 2789 valueKind = VK_LValue; // even if the parameter is an r-value reference 2790 break; 2791 } 2792 2793 // For non-references, we need to strip qualifiers just in case 2794 // the template parameter was declared as 'const int' or whatever. 2795 valueKind = VK_RValue; 2796 type = type.getUnqualifiedType(); 2797 break; 2798 } 2799 2800 case Decl::Var: 2801 case Decl::VarTemplateSpecialization: 2802 case Decl::VarTemplatePartialSpecialization: 2803 // In C, "extern void blah;" is valid and is an r-value. 2804 if (!getLangOpts().CPlusPlus && 2805 !type.hasQualifiers() && 2806 type->isVoidType()) { 2807 valueKind = VK_RValue; 2808 break; 2809 } 2810 // fallthrough 2811 2812 case Decl::ImplicitParam: 2813 case Decl::ParmVar: { 2814 // These are always l-values. 2815 valueKind = VK_LValue; 2816 type = type.getNonReferenceType(); 2817 2818 // FIXME: Does the addition of const really only apply in 2819 // potentially-evaluated contexts? Since the variable isn't actually 2820 // captured in an unevaluated context, it seems that the answer is no. 2821 if (!isUnevaluatedContext()) { 2822 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2823 if (!CapturedType.isNull()) 2824 type = CapturedType; 2825 } 2826 2827 break; 2828 } 2829 2830 case Decl::Function: { 2831 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2832 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2833 type = Context.BuiltinFnTy; 2834 valueKind = VK_RValue; 2835 break; 2836 } 2837 } 2838 2839 const FunctionType *fty = type->castAs<FunctionType>(); 2840 2841 // If we're referring to a function with an __unknown_anytype 2842 // result type, make the entire expression __unknown_anytype. 2843 if (fty->getReturnType() == Context.UnknownAnyTy) { 2844 type = Context.UnknownAnyTy; 2845 valueKind = VK_RValue; 2846 break; 2847 } 2848 2849 // Functions are l-values in C++. 2850 if (getLangOpts().CPlusPlus) { 2851 valueKind = VK_LValue; 2852 break; 2853 } 2854 2855 // C99 DR 316 says that, if a function type comes from a 2856 // function definition (without a prototype), that type is only 2857 // used for checking compatibility. Therefore, when referencing 2858 // the function, we pretend that we don't have the full function 2859 // type. 2860 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2861 isa<FunctionProtoType>(fty)) 2862 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2863 fty->getExtInfo()); 2864 2865 // Functions are r-values in C. 2866 valueKind = VK_RValue; 2867 break; 2868 } 2869 2870 case Decl::MSProperty: 2871 valueKind = VK_LValue; 2872 break; 2873 2874 case Decl::CXXMethod: 2875 // If we're referring to a method with an __unknown_anytype 2876 // result type, make the entire expression __unknown_anytype. 2877 // This should only be possible with a type written directly. 2878 if (const FunctionProtoType *proto 2879 = dyn_cast<FunctionProtoType>(VD->getType())) 2880 if (proto->getReturnType() == Context.UnknownAnyTy) { 2881 type = Context.UnknownAnyTy; 2882 valueKind = VK_RValue; 2883 break; 2884 } 2885 2886 // C++ methods are l-values if static, r-values if non-static. 2887 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2888 valueKind = VK_LValue; 2889 break; 2890 } 2891 // fallthrough 2892 2893 case Decl::CXXConversion: 2894 case Decl::CXXDestructor: 2895 case Decl::CXXConstructor: 2896 valueKind = VK_RValue; 2897 break; 2898 } 2899 2900 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2901 TemplateArgs); 2902 } 2903 } 2904 2905 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2906 PredefinedExpr::IdentType IT) { 2907 // Pick the current block, lambda, captured statement or function. 2908 Decl *currentDecl = nullptr; 2909 if (const BlockScopeInfo *BSI = getCurBlock()) 2910 currentDecl = BSI->TheDecl; 2911 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2912 currentDecl = LSI->CallOperator; 2913 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2914 currentDecl = CSI->TheCapturedDecl; 2915 else 2916 currentDecl = getCurFunctionOrMethodDecl(); 2917 2918 if (!currentDecl) { 2919 Diag(Loc, diag::ext_predef_outside_function); 2920 currentDecl = Context.getTranslationUnitDecl(); 2921 } 2922 2923 QualType ResTy; 2924 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2925 ResTy = Context.DependentTy; 2926 else { 2927 // Pre-defined identifiers are of type char[x], where x is the length of 2928 // the string. 2929 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2930 2931 llvm::APInt LengthI(32, Length + 1); 2932 if (IT == PredefinedExpr::LFunction) 2933 ResTy = Context.WideCharTy.withConst(); 2934 else 2935 ResTy = Context.CharTy.withConst(); 2936 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2937 } 2938 2939 return new (Context) PredefinedExpr(Loc, ResTy, IT); 2940 } 2941 2942 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2943 PredefinedExpr::IdentType IT; 2944 2945 switch (Kind) { 2946 default: llvm_unreachable("Unknown simple primary expr!"); 2947 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2948 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2949 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2950 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 2951 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2952 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2953 } 2954 2955 return BuildPredefinedExpr(Loc, IT); 2956 } 2957 2958 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2959 SmallString<16> CharBuffer; 2960 bool Invalid = false; 2961 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2962 if (Invalid) 2963 return ExprError(); 2964 2965 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2966 PP, Tok.getKind()); 2967 if (Literal.hadError()) 2968 return ExprError(); 2969 2970 QualType Ty; 2971 if (Literal.isWide()) 2972 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2973 else if (Literal.isUTF16()) 2974 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2975 else if (Literal.isUTF32()) 2976 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2977 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2978 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2979 else 2980 Ty = Context.CharTy; // 'x' -> char in C++ 2981 2982 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2983 if (Literal.isWide()) 2984 Kind = CharacterLiteral::Wide; 2985 else if (Literal.isUTF16()) 2986 Kind = CharacterLiteral::UTF16; 2987 else if (Literal.isUTF32()) 2988 Kind = CharacterLiteral::UTF32; 2989 2990 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2991 Tok.getLocation()); 2992 2993 if (Literal.getUDSuffix().empty()) 2994 return Lit; 2995 2996 // We're building a user-defined literal. 2997 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2998 SourceLocation UDSuffixLoc = 2999 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3000 3001 // Make sure we're allowed user-defined literals here. 3002 if (!UDLScope) 3003 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3004 3005 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3006 // operator "" X (ch) 3007 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3008 Lit, Tok.getLocation()); 3009 } 3010 3011 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3012 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3013 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3014 Context.IntTy, Loc); 3015 } 3016 3017 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3018 QualType Ty, SourceLocation Loc) { 3019 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3020 3021 using llvm::APFloat; 3022 APFloat Val(Format); 3023 3024 APFloat::opStatus result = Literal.GetFloatValue(Val); 3025 3026 // Overflow is always an error, but underflow is only an error if 3027 // we underflowed to zero (APFloat reports denormals as underflow). 3028 if ((result & APFloat::opOverflow) || 3029 ((result & APFloat::opUnderflow) && Val.isZero())) { 3030 unsigned diagnostic; 3031 SmallString<20> buffer; 3032 if (result & APFloat::opOverflow) { 3033 diagnostic = diag::warn_float_overflow; 3034 APFloat::getLargest(Format).toString(buffer); 3035 } else { 3036 diagnostic = diag::warn_float_underflow; 3037 APFloat::getSmallest(Format).toString(buffer); 3038 } 3039 3040 S.Diag(Loc, diagnostic) 3041 << Ty 3042 << StringRef(buffer.data(), buffer.size()); 3043 } 3044 3045 bool isExact = (result == APFloat::opOK); 3046 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3047 } 3048 3049 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3050 // Fast path for a single digit (which is quite common). A single digit 3051 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3052 if (Tok.getLength() == 1) { 3053 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3054 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3055 } 3056 3057 SmallString<128> SpellingBuffer; 3058 // NumericLiteralParser wants to overread by one character. Add padding to 3059 // the buffer in case the token is copied to the buffer. If getSpelling() 3060 // returns a StringRef to the memory buffer, it should have a null char at 3061 // the EOF, so it is also safe. 3062 SpellingBuffer.resize(Tok.getLength() + 1); 3063 3064 // Get the spelling of the token, which eliminates trigraphs, etc. 3065 bool Invalid = false; 3066 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3067 if (Invalid) 3068 return ExprError(); 3069 3070 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3071 if (Literal.hadError) 3072 return ExprError(); 3073 3074 if (Literal.hasUDSuffix()) { 3075 // We're building a user-defined literal. 3076 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3077 SourceLocation UDSuffixLoc = 3078 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3079 3080 // Make sure we're allowed user-defined literals here. 3081 if (!UDLScope) 3082 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3083 3084 QualType CookedTy; 3085 if (Literal.isFloatingLiteral()) { 3086 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3087 // long double, the literal is treated as a call of the form 3088 // operator "" X (f L) 3089 CookedTy = Context.LongDoubleTy; 3090 } else { 3091 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3092 // unsigned long long, the literal is treated as a call of the form 3093 // operator "" X (n ULL) 3094 CookedTy = Context.UnsignedLongLongTy; 3095 } 3096 3097 DeclarationName OpName = 3098 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3099 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3100 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3101 3102 SourceLocation TokLoc = Tok.getLocation(); 3103 3104 // Perform literal operator lookup to determine if we're building a raw 3105 // literal or a cooked one. 3106 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3107 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3108 /*AllowRaw*/true, /*AllowTemplate*/true, 3109 /*AllowStringTemplate*/false)) { 3110 case LOLR_Error: 3111 return ExprError(); 3112 3113 case LOLR_Cooked: { 3114 Expr *Lit; 3115 if (Literal.isFloatingLiteral()) { 3116 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3117 } else { 3118 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3119 if (Literal.GetIntegerValue(ResultVal)) 3120 Diag(Tok.getLocation(), diag::err_integer_too_large); 3121 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3122 Tok.getLocation()); 3123 } 3124 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3125 } 3126 3127 case LOLR_Raw: { 3128 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3129 // literal is treated as a call of the form 3130 // operator "" X ("n") 3131 unsigned Length = Literal.getUDSuffixOffset(); 3132 QualType StrTy = Context.getConstantArrayType( 3133 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3134 ArrayType::Normal, 0); 3135 Expr *Lit = StringLiteral::Create( 3136 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3137 /*Pascal*/false, StrTy, &TokLoc, 1); 3138 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3139 } 3140 3141 case LOLR_Template: { 3142 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3143 // template), L is treated as a call fo the form 3144 // operator "" X <'c1', 'c2', ... 'ck'>() 3145 // where n is the source character sequence c1 c2 ... ck. 3146 TemplateArgumentListInfo ExplicitArgs; 3147 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3148 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3149 llvm::APSInt Value(CharBits, CharIsUnsigned); 3150 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3151 Value = TokSpelling[I]; 3152 TemplateArgument Arg(Context, Value, Context.CharTy); 3153 TemplateArgumentLocInfo ArgInfo; 3154 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3155 } 3156 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3157 &ExplicitArgs); 3158 } 3159 case LOLR_StringTemplate: 3160 llvm_unreachable("unexpected literal operator lookup result"); 3161 } 3162 } 3163 3164 Expr *Res; 3165 3166 if (Literal.isFloatingLiteral()) { 3167 QualType Ty; 3168 if (Literal.isFloat) 3169 Ty = Context.FloatTy; 3170 else if (!Literal.isLong) 3171 Ty = Context.DoubleTy; 3172 else 3173 Ty = Context.LongDoubleTy; 3174 3175 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3176 3177 if (Ty == Context.DoubleTy) { 3178 if (getLangOpts().SinglePrecisionConstants) { 3179 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3180 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3181 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3182 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3183 } 3184 } 3185 } else if (!Literal.isIntegerLiteral()) { 3186 return ExprError(); 3187 } else { 3188 QualType Ty; 3189 3190 // 'long long' is a C99 or C++11 feature. 3191 if (!getLangOpts().C99 && Literal.isLongLong) { 3192 if (getLangOpts().CPlusPlus) 3193 Diag(Tok.getLocation(), 3194 getLangOpts().CPlusPlus11 ? 3195 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3196 else 3197 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3198 } 3199 3200 // Get the value in the widest-possible width. 3201 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3202 // The microsoft literal suffix extensions support 128-bit literals, which 3203 // may be wider than [u]intmax_t. 3204 // FIXME: Actually, they don't. We seem to have accidentally invented the 3205 // i128 suffix. 3206 if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 && 3207 Context.getTargetInfo().hasInt128Type()) 3208 MaxWidth = 128; 3209 llvm::APInt ResultVal(MaxWidth, 0); 3210 3211 if (Literal.GetIntegerValue(ResultVal)) { 3212 // If this value didn't fit into uintmax_t, error and force to ull. 3213 Diag(Tok.getLocation(), diag::err_integer_too_large); 3214 Ty = Context.UnsignedLongLongTy; 3215 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3216 "long long is not intmax_t?"); 3217 } else { 3218 // If this value fits into a ULL, try to figure out what else it fits into 3219 // according to the rules of C99 6.4.4.1p5. 3220 3221 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3222 // be an unsigned int. 3223 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3224 3225 // Check from smallest to largest, picking the smallest type we can. 3226 unsigned Width = 0; 3227 3228 // Microsoft specific integer suffixes are explicitly sized. 3229 if (Literal.MicrosoftInteger) { 3230 if (Literal.MicrosoftInteger > MaxWidth) { 3231 // If this target doesn't support __int128, error and force to ull. 3232 Diag(Tok.getLocation(), diag::err_int128_unsupported); 3233 Width = MaxWidth; 3234 Ty = Context.getIntMaxType(); 3235 } else { 3236 Width = Literal.MicrosoftInteger; 3237 Ty = Context.getIntTypeForBitwidth(Width, 3238 /*Signed=*/!Literal.isUnsigned); 3239 } 3240 } 3241 3242 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3243 // Are int/unsigned possibilities? 3244 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3245 3246 // Does it fit in a unsigned int? 3247 if (ResultVal.isIntN(IntSize)) { 3248 // Does it fit in a signed int? 3249 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3250 Ty = Context.IntTy; 3251 else if (AllowUnsigned) 3252 Ty = Context.UnsignedIntTy; 3253 Width = IntSize; 3254 } 3255 } 3256 3257 // Are long/unsigned long possibilities? 3258 if (Ty.isNull() && !Literal.isLongLong) { 3259 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3260 3261 // Does it fit in a unsigned long? 3262 if (ResultVal.isIntN(LongSize)) { 3263 // Does it fit in a signed long? 3264 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3265 Ty = Context.LongTy; 3266 else if (AllowUnsigned) 3267 Ty = Context.UnsignedLongTy; 3268 Width = LongSize; 3269 } 3270 } 3271 3272 // Check long long if needed. 3273 if (Ty.isNull()) { 3274 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3275 3276 // Does it fit in a unsigned long long? 3277 if (ResultVal.isIntN(LongLongSize)) { 3278 // Does it fit in a signed long long? 3279 // To be compatible with MSVC, hex integer literals ending with the 3280 // LL or i64 suffix are always signed in Microsoft mode. 3281 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3282 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3283 Ty = Context.LongLongTy; 3284 else if (AllowUnsigned) 3285 Ty = Context.UnsignedLongLongTy; 3286 Width = LongLongSize; 3287 } 3288 } 3289 3290 // If we still couldn't decide a type, we probably have something that 3291 // does not fit in a signed long long, but has no U suffix. 3292 if (Ty.isNull()) { 3293 Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed); 3294 Ty = Context.UnsignedLongLongTy; 3295 Width = Context.getTargetInfo().getLongLongWidth(); 3296 } 3297 3298 if (ResultVal.getBitWidth() != Width) 3299 ResultVal = ResultVal.trunc(Width); 3300 } 3301 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3302 } 3303 3304 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3305 if (Literal.isImaginary) 3306 Res = new (Context) ImaginaryLiteral(Res, 3307 Context.getComplexType(Res->getType())); 3308 3309 return Res; 3310 } 3311 3312 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3313 assert(E && "ActOnParenExpr() missing expr"); 3314 return new (Context) ParenExpr(L, R, E); 3315 } 3316 3317 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3318 SourceLocation Loc, 3319 SourceRange ArgRange) { 3320 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3321 // scalar or vector data type argument..." 3322 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3323 // type (C99 6.2.5p18) or void. 3324 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3325 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3326 << T << ArgRange; 3327 return true; 3328 } 3329 3330 assert((T->isVoidType() || !T->isIncompleteType()) && 3331 "Scalar types should always be complete"); 3332 return false; 3333 } 3334 3335 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3336 SourceLocation Loc, 3337 SourceRange ArgRange, 3338 UnaryExprOrTypeTrait TraitKind) { 3339 // Invalid types must be hard errors for SFINAE in C++. 3340 if (S.LangOpts.CPlusPlus) 3341 return true; 3342 3343 // C99 6.5.3.4p1: 3344 if (T->isFunctionType() && 3345 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3346 // sizeof(function)/alignof(function) is allowed as an extension. 3347 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3348 << TraitKind << ArgRange; 3349 return false; 3350 } 3351 3352 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3353 // this is an error (OpenCL v1.1 s6.3.k) 3354 if (T->isVoidType()) { 3355 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3356 : diag::ext_sizeof_alignof_void_type; 3357 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3358 return false; 3359 } 3360 3361 return true; 3362 } 3363 3364 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3365 SourceLocation Loc, 3366 SourceRange ArgRange, 3367 UnaryExprOrTypeTrait TraitKind) { 3368 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3369 // runtime doesn't allow it. 3370 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3371 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3372 << T << (TraitKind == UETT_SizeOf) 3373 << ArgRange; 3374 return true; 3375 } 3376 3377 return false; 3378 } 3379 3380 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3381 /// pointer type is equal to T) and emit a warning if it is. 3382 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3383 Expr *E) { 3384 // Don't warn if the operation changed the type. 3385 if (T != E->getType()) 3386 return; 3387 3388 // Now look for array decays. 3389 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3390 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3391 return; 3392 3393 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3394 << ICE->getType() 3395 << ICE->getSubExpr()->getType(); 3396 } 3397 3398 /// \brief Check the constraints on expression operands to unary type expression 3399 /// and type traits. 3400 /// 3401 /// Completes any types necessary and validates the constraints on the operand 3402 /// expression. The logic mostly mirrors the type-based overload, but may modify 3403 /// the expression as it completes the type for that expression through template 3404 /// instantiation, etc. 3405 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3406 UnaryExprOrTypeTrait ExprKind) { 3407 QualType ExprTy = E->getType(); 3408 assert(!ExprTy->isReferenceType()); 3409 3410 if (ExprKind == UETT_VecStep) 3411 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3412 E->getSourceRange()); 3413 3414 // Whitelist some types as extensions 3415 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3416 E->getSourceRange(), ExprKind)) 3417 return false; 3418 3419 // 'alignof' applied to an expression only requires the base element type of 3420 // the expression to be complete. 'sizeof' requires the expression's type to 3421 // be complete (and will attempt to complete it if it's an array of unknown 3422 // bound). 3423 if (ExprKind == UETT_AlignOf) { 3424 if (RequireCompleteType(E->getExprLoc(), 3425 Context.getBaseElementType(E->getType()), 3426 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3427 E->getSourceRange())) 3428 return true; 3429 } else { 3430 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3431 ExprKind, E->getSourceRange())) 3432 return true; 3433 } 3434 3435 // Completing the expression's type may have changed it. 3436 ExprTy = E->getType(); 3437 assert(!ExprTy->isReferenceType()); 3438 3439 if (ExprTy->isFunctionType()) { 3440 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3441 << ExprKind << E->getSourceRange(); 3442 return true; 3443 } 3444 3445 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3446 E->getSourceRange(), ExprKind)) 3447 return true; 3448 3449 if (ExprKind == UETT_SizeOf) { 3450 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3451 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3452 QualType OType = PVD->getOriginalType(); 3453 QualType Type = PVD->getType(); 3454 if (Type->isPointerType() && OType->isArrayType()) { 3455 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3456 << Type << OType; 3457 Diag(PVD->getLocation(), diag::note_declared_at); 3458 } 3459 } 3460 } 3461 3462 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3463 // decays into a pointer and returns an unintended result. This is most 3464 // likely a typo for "sizeof(array) op x". 3465 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3466 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3467 BO->getLHS()); 3468 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3469 BO->getRHS()); 3470 } 3471 } 3472 3473 return false; 3474 } 3475 3476 /// \brief Check the constraints on operands to unary expression and type 3477 /// traits. 3478 /// 3479 /// This will complete any types necessary, and validate the various constraints 3480 /// on those operands. 3481 /// 3482 /// The UsualUnaryConversions() function is *not* called by this routine. 3483 /// C99 6.3.2.1p[2-4] all state: 3484 /// Except when it is the operand of the sizeof operator ... 3485 /// 3486 /// C++ [expr.sizeof]p4 3487 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3488 /// standard conversions are not applied to the operand of sizeof. 3489 /// 3490 /// This policy is followed for all of the unary trait expressions. 3491 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3492 SourceLocation OpLoc, 3493 SourceRange ExprRange, 3494 UnaryExprOrTypeTrait ExprKind) { 3495 if (ExprType->isDependentType()) 3496 return false; 3497 3498 // C++ [expr.sizeof]p2: 3499 // When applied to a reference or a reference type, the result 3500 // is the size of the referenced type. 3501 // C++11 [expr.alignof]p3: 3502 // When alignof is applied to a reference type, the result 3503 // shall be the alignment of the referenced type. 3504 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3505 ExprType = Ref->getPointeeType(); 3506 3507 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3508 // When alignof or _Alignof is applied to an array type, the result 3509 // is the alignment of the element type. 3510 if (ExprKind == UETT_AlignOf) 3511 ExprType = Context.getBaseElementType(ExprType); 3512 3513 if (ExprKind == UETT_VecStep) 3514 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3515 3516 // Whitelist some types as extensions 3517 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3518 ExprKind)) 3519 return false; 3520 3521 if (RequireCompleteType(OpLoc, ExprType, 3522 diag::err_sizeof_alignof_incomplete_type, 3523 ExprKind, ExprRange)) 3524 return true; 3525 3526 if (ExprType->isFunctionType()) { 3527 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3528 << ExprKind << ExprRange; 3529 return true; 3530 } 3531 3532 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3533 ExprKind)) 3534 return true; 3535 3536 return false; 3537 } 3538 3539 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3540 E = E->IgnoreParens(); 3541 3542 // Cannot know anything else if the expression is dependent. 3543 if (E->isTypeDependent()) 3544 return false; 3545 3546 if (E->getObjectKind() == OK_BitField) { 3547 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3548 << 1 << E->getSourceRange(); 3549 return true; 3550 } 3551 3552 ValueDecl *D = nullptr; 3553 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3554 D = DRE->getDecl(); 3555 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3556 D = ME->getMemberDecl(); 3557 } 3558 3559 // If it's a field, require the containing struct to have a 3560 // complete definition so that we can compute the layout. 3561 // 3562 // This can happen in C++11 onwards, either by naming the member 3563 // in a way that is not transformed into a member access expression 3564 // (in an unevaluated operand, for instance), or by naming the member 3565 // in a trailing-return-type. 3566 // 3567 // For the record, since __alignof__ on expressions is a GCC 3568 // extension, GCC seems to permit this but always gives the 3569 // nonsensical answer 0. 3570 // 3571 // We don't really need the layout here --- we could instead just 3572 // directly check for all the appropriate alignment-lowing 3573 // attributes --- but that would require duplicating a lot of 3574 // logic that just isn't worth duplicating for such a marginal 3575 // use-case. 3576 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3577 // Fast path this check, since we at least know the record has a 3578 // definition if we can find a member of it. 3579 if (!FD->getParent()->isCompleteDefinition()) { 3580 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3581 << E->getSourceRange(); 3582 return true; 3583 } 3584 3585 // Otherwise, if it's a field, and the field doesn't have 3586 // reference type, then it must have a complete type (or be a 3587 // flexible array member, which we explicitly want to 3588 // white-list anyway), which makes the following checks trivial. 3589 if (!FD->getType()->isReferenceType()) 3590 return false; 3591 } 3592 3593 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3594 } 3595 3596 bool Sema::CheckVecStepExpr(Expr *E) { 3597 E = E->IgnoreParens(); 3598 3599 // Cannot know anything else if the expression is dependent. 3600 if (E->isTypeDependent()) 3601 return false; 3602 3603 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3604 } 3605 3606 /// \brief Build a sizeof or alignof expression given a type operand. 3607 ExprResult 3608 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3609 SourceLocation OpLoc, 3610 UnaryExprOrTypeTrait ExprKind, 3611 SourceRange R) { 3612 if (!TInfo) 3613 return ExprError(); 3614 3615 QualType T = TInfo->getType(); 3616 3617 if (!T->isDependentType() && 3618 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3619 return ExprError(); 3620 3621 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3622 return new (Context) UnaryExprOrTypeTraitExpr( 3623 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3624 } 3625 3626 /// \brief Build a sizeof or alignof expression given an expression 3627 /// operand. 3628 ExprResult 3629 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3630 UnaryExprOrTypeTrait ExprKind) { 3631 ExprResult PE = CheckPlaceholderExpr(E); 3632 if (PE.isInvalid()) 3633 return ExprError(); 3634 3635 E = PE.get(); 3636 3637 // Verify that the operand is valid. 3638 bool isInvalid = false; 3639 if (E->isTypeDependent()) { 3640 // Delay type-checking for type-dependent expressions. 3641 } else if (ExprKind == UETT_AlignOf) { 3642 isInvalid = CheckAlignOfExpr(*this, E); 3643 } else if (ExprKind == UETT_VecStep) { 3644 isInvalid = CheckVecStepExpr(E); 3645 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3646 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3647 isInvalid = true; 3648 } else { 3649 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3650 } 3651 3652 if (isInvalid) 3653 return ExprError(); 3654 3655 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3656 PE = TransformToPotentiallyEvaluated(E); 3657 if (PE.isInvalid()) return ExprError(); 3658 E = PE.get(); 3659 } 3660 3661 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3662 return new (Context) UnaryExprOrTypeTraitExpr( 3663 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3664 } 3665 3666 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3667 /// expr and the same for @c alignof and @c __alignof 3668 /// Note that the ArgRange is invalid if isType is false. 3669 ExprResult 3670 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3671 UnaryExprOrTypeTrait ExprKind, bool IsType, 3672 void *TyOrEx, const SourceRange &ArgRange) { 3673 // If error parsing type, ignore. 3674 if (!TyOrEx) return ExprError(); 3675 3676 if (IsType) { 3677 TypeSourceInfo *TInfo; 3678 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3679 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3680 } 3681 3682 Expr *ArgEx = (Expr *)TyOrEx; 3683 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3684 return Result; 3685 } 3686 3687 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3688 bool IsReal) { 3689 if (V.get()->isTypeDependent()) 3690 return S.Context.DependentTy; 3691 3692 // _Real and _Imag are only l-values for normal l-values. 3693 if (V.get()->getObjectKind() != OK_Ordinary) { 3694 V = S.DefaultLvalueConversion(V.get()); 3695 if (V.isInvalid()) 3696 return QualType(); 3697 } 3698 3699 // These operators return the element type of a complex type. 3700 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3701 return CT->getElementType(); 3702 3703 // Otherwise they pass through real integer and floating point types here. 3704 if (V.get()->getType()->isArithmeticType()) 3705 return V.get()->getType(); 3706 3707 // Test for placeholders. 3708 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3709 if (PR.isInvalid()) return QualType(); 3710 if (PR.get() != V.get()) { 3711 V = PR; 3712 return CheckRealImagOperand(S, V, Loc, IsReal); 3713 } 3714 3715 // Reject anything else. 3716 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3717 << (IsReal ? "__real" : "__imag"); 3718 return QualType(); 3719 } 3720 3721 3722 3723 ExprResult 3724 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3725 tok::TokenKind Kind, Expr *Input) { 3726 UnaryOperatorKind Opc; 3727 switch (Kind) { 3728 default: llvm_unreachable("Unknown unary op!"); 3729 case tok::plusplus: Opc = UO_PostInc; break; 3730 case tok::minusminus: Opc = UO_PostDec; break; 3731 } 3732 3733 // Since this might is a postfix expression, get rid of ParenListExprs. 3734 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3735 if (Result.isInvalid()) return ExprError(); 3736 Input = Result.get(); 3737 3738 return BuildUnaryOp(S, OpLoc, Opc, Input); 3739 } 3740 3741 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3742 /// 3743 /// \return true on error 3744 static bool checkArithmeticOnObjCPointer(Sema &S, 3745 SourceLocation opLoc, 3746 Expr *op) { 3747 assert(op->getType()->isObjCObjectPointerType()); 3748 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3749 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3750 return false; 3751 3752 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3753 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3754 << op->getSourceRange(); 3755 return true; 3756 } 3757 3758 ExprResult 3759 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3760 Expr *idx, SourceLocation rbLoc) { 3761 // Since this might be a postfix expression, get rid of ParenListExprs. 3762 if (isa<ParenListExpr>(base)) { 3763 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3764 if (result.isInvalid()) return ExprError(); 3765 base = result.get(); 3766 } 3767 3768 // Handle any non-overload placeholder types in the base and index 3769 // expressions. We can't handle overloads here because the other 3770 // operand might be an overloadable type, in which case the overload 3771 // resolution for the operator overload should get the first crack 3772 // at the overload. 3773 if (base->getType()->isNonOverloadPlaceholderType()) { 3774 ExprResult result = CheckPlaceholderExpr(base); 3775 if (result.isInvalid()) return ExprError(); 3776 base = result.get(); 3777 } 3778 if (idx->getType()->isNonOverloadPlaceholderType()) { 3779 ExprResult result = CheckPlaceholderExpr(idx); 3780 if (result.isInvalid()) return ExprError(); 3781 idx = result.get(); 3782 } 3783 3784 // Build an unanalyzed expression if either operand is type-dependent. 3785 if (getLangOpts().CPlusPlus && 3786 (base->isTypeDependent() || idx->isTypeDependent())) { 3787 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3788 VK_LValue, OK_Ordinary, rbLoc); 3789 } 3790 3791 // Use C++ overloaded-operator rules if either operand has record 3792 // type. The spec says to do this if either type is *overloadable*, 3793 // but enum types can't declare subscript operators or conversion 3794 // operators, so there's nothing interesting for overload resolution 3795 // to do if there aren't any record types involved. 3796 // 3797 // ObjC pointers have their own subscripting logic that is not tied 3798 // to overload resolution and so should not take this path. 3799 if (getLangOpts().CPlusPlus && 3800 (base->getType()->isRecordType() || 3801 (!base->getType()->isObjCObjectPointerType() && 3802 idx->getType()->isRecordType()))) { 3803 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3804 } 3805 3806 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3807 } 3808 3809 ExprResult 3810 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3811 Expr *Idx, SourceLocation RLoc) { 3812 Expr *LHSExp = Base; 3813 Expr *RHSExp = Idx; 3814 3815 // Perform default conversions. 3816 if (!LHSExp->getType()->getAs<VectorType>()) { 3817 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3818 if (Result.isInvalid()) 3819 return ExprError(); 3820 LHSExp = Result.get(); 3821 } 3822 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3823 if (Result.isInvalid()) 3824 return ExprError(); 3825 RHSExp = Result.get(); 3826 3827 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3828 ExprValueKind VK = VK_LValue; 3829 ExprObjectKind OK = OK_Ordinary; 3830 3831 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3832 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3833 // in the subscript position. As a result, we need to derive the array base 3834 // and index from the expression types. 3835 Expr *BaseExpr, *IndexExpr; 3836 QualType ResultType; 3837 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3838 BaseExpr = LHSExp; 3839 IndexExpr = RHSExp; 3840 ResultType = Context.DependentTy; 3841 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3842 BaseExpr = LHSExp; 3843 IndexExpr = RHSExp; 3844 ResultType = PTy->getPointeeType(); 3845 } else if (const ObjCObjectPointerType *PTy = 3846 LHSTy->getAs<ObjCObjectPointerType>()) { 3847 BaseExpr = LHSExp; 3848 IndexExpr = RHSExp; 3849 3850 // Use custom logic if this should be the pseudo-object subscript 3851 // expression. 3852 if (!LangOpts.isSubscriptPointerArithmetic()) 3853 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 3854 nullptr); 3855 3856 ResultType = PTy->getPointeeType(); 3857 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3858 // Handle the uncommon case of "123[Ptr]". 3859 BaseExpr = RHSExp; 3860 IndexExpr = LHSExp; 3861 ResultType = PTy->getPointeeType(); 3862 } else if (const ObjCObjectPointerType *PTy = 3863 RHSTy->getAs<ObjCObjectPointerType>()) { 3864 // Handle the uncommon case of "123[Ptr]". 3865 BaseExpr = RHSExp; 3866 IndexExpr = LHSExp; 3867 ResultType = PTy->getPointeeType(); 3868 if (!LangOpts.isSubscriptPointerArithmetic()) { 3869 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3870 << ResultType << BaseExpr->getSourceRange(); 3871 return ExprError(); 3872 } 3873 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3874 BaseExpr = LHSExp; // vectors: V[123] 3875 IndexExpr = RHSExp; 3876 VK = LHSExp->getValueKind(); 3877 if (VK != VK_RValue) 3878 OK = OK_VectorComponent; 3879 3880 // FIXME: need to deal with const... 3881 ResultType = VTy->getElementType(); 3882 } else if (LHSTy->isArrayType()) { 3883 // If we see an array that wasn't promoted by 3884 // DefaultFunctionArrayLvalueConversion, it must be an array that 3885 // wasn't promoted because of the C90 rule that doesn't 3886 // allow promoting non-lvalue arrays. Warn, then 3887 // force the promotion here. 3888 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3889 LHSExp->getSourceRange(); 3890 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3891 CK_ArrayToPointerDecay).get(); 3892 LHSTy = LHSExp->getType(); 3893 3894 BaseExpr = LHSExp; 3895 IndexExpr = RHSExp; 3896 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3897 } else if (RHSTy->isArrayType()) { 3898 // Same as previous, except for 123[f().a] case 3899 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3900 RHSExp->getSourceRange(); 3901 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3902 CK_ArrayToPointerDecay).get(); 3903 RHSTy = RHSExp->getType(); 3904 3905 BaseExpr = RHSExp; 3906 IndexExpr = LHSExp; 3907 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3908 } else { 3909 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3910 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3911 } 3912 // C99 6.5.2.1p1 3913 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3914 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3915 << IndexExpr->getSourceRange()); 3916 3917 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3918 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3919 && !IndexExpr->isTypeDependent()) 3920 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3921 3922 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3923 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3924 // type. Note that Functions are not objects, and that (in C99 parlance) 3925 // incomplete types are not object types. 3926 if (ResultType->isFunctionType()) { 3927 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3928 << ResultType << BaseExpr->getSourceRange(); 3929 return ExprError(); 3930 } 3931 3932 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3933 // GNU extension: subscripting on pointer to void 3934 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3935 << BaseExpr->getSourceRange(); 3936 3937 // C forbids expressions of unqualified void type from being l-values. 3938 // See IsCForbiddenLValueType. 3939 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3940 } else if (!ResultType->isDependentType() && 3941 RequireCompleteType(LLoc, ResultType, 3942 diag::err_subscript_incomplete_type, BaseExpr)) 3943 return ExprError(); 3944 3945 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3946 !ResultType.isCForbiddenLValueType()); 3947 3948 return new (Context) 3949 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 3950 } 3951 3952 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3953 FunctionDecl *FD, 3954 ParmVarDecl *Param) { 3955 if (Param->hasUnparsedDefaultArg()) { 3956 Diag(CallLoc, 3957 diag::err_use_of_default_argument_to_function_declared_later) << 3958 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3959 Diag(UnparsedDefaultArgLocs[Param], 3960 diag::note_default_argument_declared_here); 3961 return ExprError(); 3962 } 3963 3964 if (Param->hasUninstantiatedDefaultArg()) { 3965 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3966 3967 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3968 Param); 3969 3970 // Instantiate the expression. 3971 MultiLevelTemplateArgumentList MutiLevelArgList 3972 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 3973 3974 InstantiatingTemplate Inst(*this, CallLoc, Param, 3975 MutiLevelArgList.getInnermost()); 3976 if (Inst.isInvalid()) 3977 return ExprError(); 3978 3979 ExprResult Result; 3980 { 3981 // C++ [dcl.fct.default]p5: 3982 // The names in the [default argument] expression are bound, and 3983 // the semantic constraints are checked, at the point where the 3984 // default argument expression appears. 3985 ContextRAII SavedContext(*this, FD); 3986 LocalInstantiationScope Local(*this); 3987 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3988 } 3989 if (Result.isInvalid()) 3990 return ExprError(); 3991 3992 // Check the expression as an initializer for the parameter. 3993 InitializedEntity Entity 3994 = InitializedEntity::InitializeParameter(Context, Param); 3995 InitializationKind Kind 3996 = InitializationKind::CreateCopy(Param->getLocation(), 3997 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3998 Expr *ResultE = Result.getAs<Expr>(); 3999 4000 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4001 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4002 if (Result.isInvalid()) 4003 return ExprError(); 4004 4005 Expr *Arg = Result.getAs<Expr>(); 4006 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4007 // Build the default argument expression. 4008 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4009 } 4010 4011 // If the default expression creates temporaries, we need to 4012 // push them to the current stack of expression temporaries so they'll 4013 // be properly destroyed. 4014 // FIXME: We should really be rebuilding the default argument with new 4015 // bound temporaries; see the comment in PR5810. 4016 // We don't need to do that with block decls, though, because 4017 // blocks in default argument expression can never capture anything. 4018 if (isa<ExprWithCleanups>(Param->getInit())) { 4019 // Set the "needs cleanups" bit regardless of whether there are 4020 // any explicit objects. 4021 ExprNeedsCleanups = true; 4022 4023 // Append all the objects to the cleanup list. Right now, this 4024 // should always be a no-op, because blocks in default argument 4025 // expressions should never be able to capture anything. 4026 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4027 "default argument expression has capturing blocks?"); 4028 } 4029 4030 // We already type-checked the argument, so we know it works. 4031 // Just mark all of the declarations in this potentially-evaluated expression 4032 // as being "referenced". 4033 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4034 /*SkipLocalVariables=*/true); 4035 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4036 } 4037 4038 4039 Sema::VariadicCallType 4040 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4041 Expr *Fn) { 4042 if (Proto && Proto->isVariadic()) { 4043 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4044 return VariadicConstructor; 4045 else if (Fn && Fn->getType()->isBlockPointerType()) 4046 return VariadicBlock; 4047 else if (FDecl) { 4048 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4049 if (Method->isInstance()) 4050 return VariadicMethod; 4051 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4052 return VariadicMethod; 4053 return VariadicFunction; 4054 } 4055 return VariadicDoesNotApply; 4056 } 4057 4058 namespace { 4059 class FunctionCallCCC : public FunctionCallFilterCCC { 4060 public: 4061 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4062 unsigned NumArgs, MemberExpr *ME) 4063 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4064 FunctionName(FuncName) {} 4065 4066 bool ValidateCandidate(const TypoCorrection &candidate) override { 4067 if (!candidate.getCorrectionSpecifier() || 4068 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4069 return false; 4070 } 4071 4072 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4073 } 4074 4075 private: 4076 const IdentifierInfo *const FunctionName; 4077 }; 4078 } 4079 4080 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4081 FunctionDecl *FDecl, 4082 ArrayRef<Expr *> Args) { 4083 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4084 DeclarationName FuncName = FDecl->getDeclName(); 4085 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4086 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4087 4088 if (TypoCorrection Corrected = S.CorrectTypo( 4089 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4090 S.getScopeForContext(S.CurContext), nullptr, CCC, 4091 Sema::CTK_ErrorRecovery)) { 4092 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4093 if (Corrected.isOverloaded()) { 4094 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4095 OverloadCandidateSet::iterator Best; 4096 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4097 CDEnd = Corrected.end(); 4098 CD != CDEnd; ++CD) { 4099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4100 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4101 OCS); 4102 } 4103 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4104 case OR_Success: 4105 ND = Best->Function; 4106 Corrected.setCorrectionDecl(ND); 4107 break; 4108 default: 4109 break; 4110 } 4111 } 4112 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4113 return Corrected; 4114 } 4115 } 4116 } 4117 return TypoCorrection(); 4118 } 4119 4120 /// ConvertArgumentsForCall - Converts the arguments specified in 4121 /// Args/NumArgs to the parameter types of the function FDecl with 4122 /// function prototype Proto. Call is the call expression itself, and 4123 /// Fn is the function expression. For a C++ member function, this 4124 /// routine does not attempt to convert the object argument. Returns 4125 /// true if the call is ill-formed. 4126 bool 4127 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4128 FunctionDecl *FDecl, 4129 const FunctionProtoType *Proto, 4130 ArrayRef<Expr *> Args, 4131 SourceLocation RParenLoc, 4132 bool IsExecConfig) { 4133 // Bail out early if calling a builtin with custom typechecking. 4134 // We don't need to do this in the 4135 if (FDecl) 4136 if (unsigned ID = FDecl->getBuiltinID()) 4137 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4138 return false; 4139 4140 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4141 // assignment, to the types of the corresponding parameter, ... 4142 unsigned NumParams = Proto->getNumParams(); 4143 bool Invalid = false; 4144 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4145 unsigned FnKind = Fn->getType()->isBlockPointerType() 4146 ? 1 /* block */ 4147 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4148 : 0 /* function */); 4149 4150 // If too few arguments are available (and we don't have default 4151 // arguments for the remaining parameters), don't make the call. 4152 if (Args.size() < NumParams) { 4153 if (Args.size() < MinArgs) { 4154 TypoCorrection TC; 4155 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4156 unsigned diag_id = 4157 MinArgs == NumParams && !Proto->isVariadic() 4158 ? diag::err_typecheck_call_too_few_args_suggest 4159 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4160 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4161 << static_cast<unsigned>(Args.size()) 4162 << TC.getCorrectionRange()); 4163 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4164 Diag(RParenLoc, 4165 MinArgs == NumParams && !Proto->isVariadic() 4166 ? diag::err_typecheck_call_too_few_args_one 4167 : diag::err_typecheck_call_too_few_args_at_least_one) 4168 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4169 else 4170 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4171 ? diag::err_typecheck_call_too_few_args 4172 : diag::err_typecheck_call_too_few_args_at_least) 4173 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4174 << Fn->getSourceRange(); 4175 4176 // Emit the location of the prototype. 4177 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4178 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4179 << FDecl; 4180 4181 return true; 4182 } 4183 Call->setNumArgs(Context, NumParams); 4184 } 4185 4186 // If too many are passed and not variadic, error on the extras and drop 4187 // them. 4188 if (Args.size() > NumParams) { 4189 if (!Proto->isVariadic()) { 4190 TypoCorrection TC; 4191 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4192 unsigned diag_id = 4193 MinArgs == NumParams && !Proto->isVariadic() 4194 ? diag::err_typecheck_call_too_many_args_suggest 4195 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4196 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4197 << static_cast<unsigned>(Args.size()) 4198 << TC.getCorrectionRange()); 4199 } else if (NumParams == 1 && FDecl && 4200 FDecl->getParamDecl(0)->getDeclName()) 4201 Diag(Args[NumParams]->getLocStart(), 4202 MinArgs == NumParams 4203 ? diag::err_typecheck_call_too_many_args_one 4204 : diag::err_typecheck_call_too_many_args_at_most_one) 4205 << FnKind << FDecl->getParamDecl(0) 4206 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4207 << SourceRange(Args[NumParams]->getLocStart(), 4208 Args.back()->getLocEnd()); 4209 else 4210 Diag(Args[NumParams]->getLocStart(), 4211 MinArgs == NumParams 4212 ? diag::err_typecheck_call_too_many_args 4213 : diag::err_typecheck_call_too_many_args_at_most) 4214 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4215 << Fn->getSourceRange() 4216 << SourceRange(Args[NumParams]->getLocStart(), 4217 Args.back()->getLocEnd()); 4218 4219 // Emit the location of the prototype. 4220 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4221 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4222 << FDecl; 4223 4224 // This deletes the extra arguments. 4225 Call->setNumArgs(Context, NumParams); 4226 return true; 4227 } 4228 } 4229 SmallVector<Expr *, 8> AllArgs; 4230 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4231 4232 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4233 Proto, 0, Args, AllArgs, CallType); 4234 if (Invalid) 4235 return true; 4236 unsigned TotalNumArgs = AllArgs.size(); 4237 for (unsigned i = 0; i < TotalNumArgs; ++i) 4238 Call->setArg(i, AllArgs[i]); 4239 4240 return false; 4241 } 4242 4243 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4244 const FunctionProtoType *Proto, 4245 unsigned FirstParam, ArrayRef<Expr *> Args, 4246 SmallVectorImpl<Expr *> &AllArgs, 4247 VariadicCallType CallType, bool AllowExplicit, 4248 bool IsListInitialization) { 4249 unsigned NumParams = Proto->getNumParams(); 4250 bool Invalid = false; 4251 unsigned ArgIx = 0; 4252 // Continue to check argument types (even if we have too few/many args). 4253 for (unsigned i = FirstParam; i < NumParams; i++) { 4254 QualType ProtoArgType = Proto->getParamType(i); 4255 4256 Expr *Arg; 4257 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4258 if (ArgIx < Args.size()) { 4259 Arg = Args[ArgIx++]; 4260 4261 if (RequireCompleteType(Arg->getLocStart(), 4262 ProtoArgType, 4263 diag::err_call_incomplete_argument, Arg)) 4264 return true; 4265 4266 // Strip the unbridged-cast placeholder expression off, if applicable. 4267 bool CFAudited = false; 4268 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4269 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4270 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4271 Arg = stripARCUnbridgedCast(Arg); 4272 else if (getLangOpts().ObjCAutoRefCount && 4273 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4274 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4275 CFAudited = true; 4276 4277 InitializedEntity Entity = 4278 Param ? InitializedEntity::InitializeParameter(Context, Param, 4279 ProtoArgType) 4280 : InitializedEntity::InitializeParameter( 4281 Context, ProtoArgType, Proto->isParamConsumed(i)); 4282 4283 // Remember that parameter belongs to a CF audited API. 4284 if (CFAudited) 4285 Entity.setParameterCFAudited(); 4286 4287 ExprResult ArgE = PerformCopyInitialization( 4288 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4289 if (ArgE.isInvalid()) 4290 return true; 4291 4292 Arg = ArgE.getAs<Expr>(); 4293 } else { 4294 assert(Param && "can't use default arguments without a known callee"); 4295 4296 ExprResult ArgExpr = 4297 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4298 if (ArgExpr.isInvalid()) 4299 return true; 4300 4301 Arg = ArgExpr.getAs<Expr>(); 4302 } 4303 4304 // Check for array bounds violations for each argument to the call. This 4305 // check only triggers warnings when the argument isn't a more complex Expr 4306 // with its own checking, such as a BinaryOperator. 4307 CheckArrayAccess(Arg); 4308 4309 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4310 CheckStaticArrayArgument(CallLoc, Param, Arg); 4311 4312 AllArgs.push_back(Arg); 4313 } 4314 4315 // If this is a variadic call, handle args passed through "...". 4316 if (CallType != VariadicDoesNotApply) { 4317 // Assume that extern "C" functions with variadic arguments that 4318 // return __unknown_anytype aren't *really* variadic. 4319 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4320 FDecl->isExternC()) { 4321 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4322 QualType paramType; // ignored 4323 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4324 Invalid |= arg.isInvalid(); 4325 AllArgs.push_back(arg.get()); 4326 } 4327 4328 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4329 } else { 4330 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4331 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4332 FDecl); 4333 Invalid |= Arg.isInvalid(); 4334 AllArgs.push_back(Arg.get()); 4335 } 4336 } 4337 4338 // Check for array bounds violations. 4339 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4340 CheckArrayAccess(Args[i]); 4341 } 4342 return Invalid; 4343 } 4344 4345 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4346 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4347 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4348 TL = DTL.getOriginalLoc(); 4349 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4350 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4351 << ATL.getLocalSourceRange(); 4352 } 4353 4354 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4355 /// array parameter, check that it is non-null, and that if it is formed by 4356 /// array-to-pointer decay, the underlying array is sufficiently large. 4357 /// 4358 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4359 /// array type derivation, then for each call to the function, the value of the 4360 /// corresponding actual argument shall provide access to the first element of 4361 /// an array with at least as many elements as specified by the size expression. 4362 void 4363 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4364 ParmVarDecl *Param, 4365 const Expr *ArgExpr) { 4366 // Static array parameters are not supported in C++. 4367 if (!Param || getLangOpts().CPlusPlus) 4368 return; 4369 4370 QualType OrigTy = Param->getOriginalType(); 4371 4372 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4373 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4374 return; 4375 4376 if (ArgExpr->isNullPointerConstant(Context, 4377 Expr::NPC_NeverValueDependent)) { 4378 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4379 DiagnoseCalleeStaticArrayParam(*this, Param); 4380 return; 4381 } 4382 4383 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4384 if (!CAT) 4385 return; 4386 4387 const ConstantArrayType *ArgCAT = 4388 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4389 if (!ArgCAT) 4390 return; 4391 4392 if (ArgCAT->getSize().ult(CAT->getSize())) { 4393 Diag(CallLoc, diag::warn_static_array_too_small) 4394 << ArgExpr->getSourceRange() 4395 << (unsigned) ArgCAT->getSize().getZExtValue() 4396 << (unsigned) CAT->getSize().getZExtValue(); 4397 DiagnoseCalleeStaticArrayParam(*this, Param); 4398 } 4399 } 4400 4401 /// Given a function expression of unknown-any type, try to rebuild it 4402 /// to have a function type. 4403 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4404 4405 /// Is the given type a placeholder that we need to lower out 4406 /// immediately during argument processing? 4407 static bool isPlaceholderToRemoveAsArg(QualType type) { 4408 // Placeholders are never sugared. 4409 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4410 if (!placeholder) return false; 4411 4412 switch (placeholder->getKind()) { 4413 // Ignore all the non-placeholder types. 4414 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4415 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4416 #include "clang/AST/BuiltinTypes.def" 4417 return false; 4418 4419 // We cannot lower out overload sets; they might validly be resolved 4420 // by the call machinery. 4421 case BuiltinType::Overload: 4422 return false; 4423 4424 // Unbridged casts in ARC can be handled in some call positions and 4425 // should be left in place. 4426 case BuiltinType::ARCUnbridgedCast: 4427 return false; 4428 4429 // Pseudo-objects should be converted as soon as possible. 4430 case BuiltinType::PseudoObject: 4431 return true; 4432 4433 // The debugger mode could theoretically but currently does not try 4434 // to resolve unknown-typed arguments based on known parameter types. 4435 case BuiltinType::UnknownAny: 4436 return true; 4437 4438 // These are always invalid as call arguments and should be reported. 4439 case BuiltinType::BoundMember: 4440 case BuiltinType::BuiltinFn: 4441 return true; 4442 } 4443 llvm_unreachable("bad builtin type kind"); 4444 } 4445 4446 /// Check an argument list for placeholders that we won't try to 4447 /// handle later. 4448 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4449 // Apply this processing to all the arguments at once instead of 4450 // dying at the first failure. 4451 bool hasInvalid = false; 4452 for (size_t i = 0, e = args.size(); i != e; i++) { 4453 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4454 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4455 if (result.isInvalid()) hasInvalid = true; 4456 else args[i] = result.get(); 4457 } 4458 } 4459 return hasInvalid; 4460 } 4461 4462 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4463 /// This provides the location of the left/right parens and a list of comma 4464 /// locations. 4465 ExprResult 4466 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4467 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4468 Expr *ExecConfig, bool IsExecConfig) { 4469 // Since this might be a postfix expression, get rid of ParenListExprs. 4470 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4471 if (Result.isInvalid()) return ExprError(); 4472 Fn = Result.get(); 4473 4474 if (checkArgsForPlaceholders(*this, ArgExprs)) 4475 return ExprError(); 4476 4477 if (getLangOpts().CPlusPlus) { 4478 // If this is a pseudo-destructor expression, build the call immediately. 4479 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4480 if (!ArgExprs.empty()) { 4481 // Pseudo-destructor calls should not have any arguments. 4482 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4483 << FixItHint::CreateRemoval( 4484 SourceRange(ArgExprs[0]->getLocStart(), 4485 ArgExprs.back()->getLocEnd())); 4486 } 4487 4488 return new (Context) 4489 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4490 } 4491 if (Fn->getType() == Context.PseudoObjectTy) { 4492 ExprResult result = CheckPlaceholderExpr(Fn); 4493 if (result.isInvalid()) return ExprError(); 4494 Fn = result.get(); 4495 } 4496 4497 // Determine whether this is a dependent call inside a C++ template, 4498 // in which case we won't do any semantic analysis now. 4499 // FIXME: Will need to cache the results of name lookup (including ADL) in 4500 // Fn. 4501 bool Dependent = false; 4502 if (Fn->isTypeDependent()) 4503 Dependent = true; 4504 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4505 Dependent = true; 4506 4507 if (Dependent) { 4508 if (ExecConfig) { 4509 return new (Context) CUDAKernelCallExpr( 4510 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4511 Context.DependentTy, VK_RValue, RParenLoc); 4512 } else { 4513 return new (Context) CallExpr( 4514 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4515 } 4516 } 4517 4518 // Determine whether this is a call to an object (C++ [over.call.object]). 4519 if (Fn->getType()->isRecordType()) 4520 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4521 RParenLoc); 4522 4523 if (Fn->getType() == Context.UnknownAnyTy) { 4524 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4525 if (result.isInvalid()) return ExprError(); 4526 Fn = result.get(); 4527 } 4528 4529 if (Fn->getType() == Context.BoundMemberTy) { 4530 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4531 } 4532 } 4533 4534 // Check for overloaded calls. This can happen even in C due to extensions. 4535 if (Fn->getType() == Context.OverloadTy) { 4536 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4537 4538 // We aren't supposed to apply this logic for if there's an '&' involved. 4539 if (!find.HasFormOfMemberPointer) { 4540 OverloadExpr *ovl = find.Expression; 4541 if (isa<UnresolvedLookupExpr>(ovl)) { 4542 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4543 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4544 RParenLoc, ExecConfig); 4545 } else { 4546 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4547 RParenLoc); 4548 } 4549 } 4550 } 4551 4552 // If we're directly calling a function, get the appropriate declaration. 4553 if (Fn->getType() == Context.UnknownAnyTy) { 4554 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4555 if (result.isInvalid()) return ExprError(); 4556 Fn = result.get(); 4557 } 4558 4559 Expr *NakedFn = Fn->IgnoreParens(); 4560 4561 NamedDecl *NDecl = nullptr; 4562 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4563 if (UnOp->getOpcode() == UO_AddrOf) 4564 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4565 4566 if (isa<DeclRefExpr>(NakedFn)) 4567 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4568 else if (isa<MemberExpr>(NakedFn)) 4569 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4570 4571 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4572 if (FD->hasAttr<EnableIfAttr>()) { 4573 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4574 Diag(Fn->getLocStart(), 4575 isa<CXXMethodDecl>(FD) ? 4576 diag::err_ovl_no_viable_member_function_in_call : 4577 diag::err_ovl_no_viable_function_in_call) 4578 << FD << FD->getSourceRange(); 4579 Diag(FD->getLocation(), 4580 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4581 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4582 } 4583 } 4584 } 4585 4586 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4587 ExecConfig, IsExecConfig); 4588 } 4589 4590 ExprResult 4591 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4592 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4593 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4594 if (!ConfigDecl) 4595 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4596 << "cudaConfigureCall"); 4597 QualType ConfigQTy = ConfigDecl->getType(); 4598 4599 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4600 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4601 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4602 4603 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr, 4604 /*IsExecConfig=*/true); 4605 } 4606 4607 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4608 /// 4609 /// __builtin_astype( value, dst type ) 4610 /// 4611 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4612 SourceLocation BuiltinLoc, 4613 SourceLocation RParenLoc) { 4614 ExprValueKind VK = VK_RValue; 4615 ExprObjectKind OK = OK_Ordinary; 4616 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4617 QualType SrcTy = E->getType(); 4618 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4619 return ExprError(Diag(BuiltinLoc, 4620 diag::err_invalid_astype_of_different_size) 4621 << DstTy 4622 << SrcTy 4623 << E->getSourceRange()); 4624 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4625 } 4626 4627 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4628 /// provided arguments. 4629 /// 4630 /// __builtin_convertvector( value, dst type ) 4631 /// 4632 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4633 SourceLocation BuiltinLoc, 4634 SourceLocation RParenLoc) { 4635 TypeSourceInfo *TInfo; 4636 GetTypeFromParser(ParsedDestTy, &TInfo); 4637 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4638 } 4639 4640 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4641 /// i.e. an expression not of \p OverloadTy. The expression should 4642 /// unary-convert to an expression of function-pointer or 4643 /// block-pointer type. 4644 /// 4645 /// \param NDecl the declaration being called, if available 4646 ExprResult 4647 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4648 SourceLocation LParenLoc, 4649 ArrayRef<Expr *> Args, 4650 SourceLocation RParenLoc, 4651 Expr *Config, bool IsExecConfig) { 4652 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4653 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4654 4655 // Promote the function operand. 4656 // We special-case function promotion here because we only allow promoting 4657 // builtin functions to function pointers in the callee of a call. 4658 ExprResult Result; 4659 if (BuiltinID && 4660 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4661 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4662 CK_BuiltinFnToFnPtr).get(); 4663 } else { 4664 Result = CallExprUnaryConversions(Fn); 4665 } 4666 if (Result.isInvalid()) 4667 return ExprError(); 4668 Fn = Result.get(); 4669 4670 // Make the call expr early, before semantic checks. This guarantees cleanup 4671 // of arguments and function on error. 4672 CallExpr *TheCall; 4673 if (Config) 4674 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4675 cast<CallExpr>(Config), Args, 4676 Context.BoolTy, VK_RValue, 4677 RParenLoc); 4678 else 4679 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4680 VK_RValue, RParenLoc); 4681 4682 // Bail out early if calling a builtin with custom typechecking. 4683 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4684 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4685 4686 retry: 4687 const FunctionType *FuncT; 4688 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4689 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4690 // have type pointer to function". 4691 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4692 if (!FuncT) 4693 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4694 << Fn->getType() << Fn->getSourceRange()); 4695 } else if (const BlockPointerType *BPT = 4696 Fn->getType()->getAs<BlockPointerType>()) { 4697 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4698 } else { 4699 // Handle calls to expressions of unknown-any type. 4700 if (Fn->getType() == Context.UnknownAnyTy) { 4701 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4702 if (rewrite.isInvalid()) return ExprError(); 4703 Fn = rewrite.get(); 4704 TheCall->setCallee(Fn); 4705 goto retry; 4706 } 4707 4708 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4709 << Fn->getType() << Fn->getSourceRange()); 4710 } 4711 4712 if (getLangOpts().CUDA) { 4713 if (Config) { 4714 // CUDA: Kernel calls must be to global functions 4715 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4716 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4717 << FDecl->getName() << Fn->getSourceRange()); 4718 4719 // CUDA: Kernel function must have 'void' return type 4720 if (!FuncT->getReturnType()->isVoidType()) 4721 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4722 << Fn->getType() << Fn->getSourceRange()); 4723 } else { 4724 // CUDA: Calls to global functions must be configured 4725 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4726 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4727 << FDecl->getName() << Fn->getSourceRange()); 4728 } 4729 } 4730 4731 // Check for a valid return type 4732 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4733 FDecl)) 4734 return ExprError(); 4735 4736 // We know the result type of the call, set it. 4737 TheCall->setType(FuncT->getCallResultType(Context)); 4738 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4739 4740 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4741 if (Proto) { 4742 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4743 IsExecConfig)) 4744 return ExprError(); 4745 } else { 4746 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4747 4748 if (FDecl) { 4749 // Check if we have too few/too many template arguments, based 4750 // on our knowledge of the function definition. 4751 const FunctionDecl *Def = nullptr; 4752 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4753 Proto = Def->getType()->getAs<FunctionProtoType>(); 4754 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4755 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4756 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4757 } 4758 4759 // If the function we're calling isn't a function prototype, but we have 4760 // a function prototype from a prior declaratiom, use that prototype. 4761 if (!FDecl->hasPrototype()) 4762 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4763 } 4764 4765 // Promote the arguments (C99 6.5.2.2p6). 4766 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4767 Expr *Arg = Args[i]; 4768 4769 if (Proto && i < Proto->getNumParams()) { 4770 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4771 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4772 ExprResult ArgE = 4773 PerformCopyInitialization(Entity, SourceLocation(), Arg); 4774 if (ArgE.isInvalid()) 4775 return true; 4776 4777 Arg = ArgE.getAs<Expr>(); 4778 4779 } else { 4780 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4781 4782 if (ArgE.isInvalid()) 4783 return true; 4784 4785 Arg = ArgE.getAs<Expr>(); 4786 } 4787 4788 if (RequireCompleteType(Arg->getLocStart(), 4789 Arg->getType(), 4790 diag::err_call_incomplete_argument, Arg)) 4791 return ExprError(); 4792 4793 TheCall->setArg(i, Arg); 4794 } 4795 } 4796 4797 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4798 if (!Method->isStatic()) 4799 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4800 << Fn->getSourceRange()); 4801 4802 // Check for sentinels 4803 if (NDecl) 4804 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4805 4806 // Do special checking on direct calls to functions. 4807 if (FDecl) { 4808 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4809 return ExprError(); 4810 4811 if (BuiltinID) 4812 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4813 } else if (NDecl) { 4814 if (CheckPointerCall(NDecl, TheCall, Proto)) 4815 return ExprError(); 4816 } else { 4817 if (CheckOtherCall(TheCall, Proto)) 4818 return ExprError(); 4819 } 4820 4821 return MaybeBindToTemporary(TheCall); 4822 } 4823 4824 ExprResult 4825 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4826 SourceLocation RParenLoc, Expr *InitExpr) { 4827 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4828 // FIXME: put back this assert when initializers are worked out. 4829 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4830 4831 TypeSourceInfo *TInfo; 4832 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4833 if (!TInfo) 4834 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4835 4836 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4837 } 4838 4839 ExprResult 4840 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4841 SourceLocation RParenLoc, Expr *LiteralExpr) { 4842 QualType literalType = TInfo->getType(); 4843 4844 if (literalType->isArrayType()) { 4845 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4846 diag::err_illegal_decl_array_incomplete_type, 4847 SourceRange(LParenLoc, 4848 LiteralExpr->getSourceRange().getEnd()))) 4849 return ExprError(); 4850 if (literalType->isVariableArrayType()) 4851 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4852 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4853 } else if (!literalType->isDependentType() && 4854 RequireCompleteType(LParenLoc, literalType, 4855 diag::err_typecheck_decl_incomplete_type, 4856 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4857 return ExprError(); 4858 4859 InitializedEntity Entity 4860 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4861 InitializationKind Kind 4862 = InitializationKind::CreateCStyleCast(LParenLoc, 4863 SourceRange(LParenLoc, RParenLoc), 4864 /*InitList=*/true); 4865 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4866 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4867 &literalType); 4868 if (Result.isInvalid()) 4869 return ExprError(); 4870 LiteralExpr = Result.get(); 4871 4872 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 4873 if (isFileScope && 4874 !LiteralExpr->isTypeDependent() && 4875 !LiteralExpr->isValueDependent() && 4876 !literalType->isDependentType()) { // 6.5.2.5p3 4877 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4878 return ExprError(); 4879 } 4880 4881 // In C, compound literals are l-values for some reason. 4882 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4883 4884 return MaybeBindToTemporary( 4885 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4886 VK, LiteralExpr, isFileScope)); 4887 } 4888 4889 ExprResult 4890 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4891 SourceLocation RBraceLoc) { 4892 // Immediately handle non-overload placeholders. Overloads can be 4893 // resolved contextually, but everything else here can't. 4894 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4895 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4896 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4897 4898 // Ignore failures; dropping the entire initializer list because 4899 // of one failure would be terrible for indexing/etc. 4900 if (result.isInvalid()) continue; 4901 4902 InitArgList[I] = result.get(); 4903 } 4904 } 4905 4906 // Semantic analysis for initializers is done by ActOnDeclarator() and 4907 // CheckInitializer() - it requires knowledge of the object being intialized. 4908 4909 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4910 RBraceLoc); 4911 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4912 return E; 4913 } 4914 4915 /// Do an explicit extend of the given block pointer if we're in ARC. 4916 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4917 assert(E.get()->getType()->isBlockPointerType()); 4918 assert(E.get()->isRValue()); 4919 4920 // Only do this in an r-value context. 4921 if (!S.getLangOpts().ObjCAutoRefCount) return; 4922 4923 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4924 CK_ARCExtendBlockObject, E.get(), 4925 /*base path*/ nullptr, VK_RValue); 4926 S.ExprNeedsCleanups = true; 4927 } 4928 4929 /// Prepare a conversion of the given expression to an ObjC object 4930 /// pointer type. 4931 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4932 QualType type = E.get()->getType(); 4933 if (type->isObjCObjectPointerType()) { 4934 return CK_BitCast; 4935 } else if (type->isBlockPointerType()) { 4936 maybeExtendBlockObject(*this, E); 4937 return CK_BlockPointerToObjCPointerCast; 4938 } else { 4939 assert(type->isPointerType()); 4940 return CK_CPointerToObjCPointerCast; 4941 } 4942 } 4943 4944 /// Prepares for a scalar cast, performing all the necessary stages 4945 /// except the final cast and returning the kind required. 4946 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4947 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4948 // Also, callers should have filtered out the invalid cases with 4949 // pointers. Everything else should be possible. 4950 4951 QualType SrcTy = Src.get()->getType(); 4952 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4953 return CK_NoOp; 4954 4955 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4956 case Type::STK_MemberPointer: 4957 llvm_unreachable("member pointer type in C"); 4958 4959 case Type::STK_CPointer: 4960 case Type::STK_BlockPointer: 4961 case Type::STK_ObjCObjectPointer: 4962 switch (DestTy->getScalarTypeKind()) { 4963 case Type::STK_CPointer: { 4964 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4965 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4966 if (SrcAS != DestAS) 4967 return CK_AddressSpaceConversion; 4968 return CK_BitCast; 4969 } 4970 case Type::STK_BlockPointer: 4971 return (SrcKind == Type::STK_BlockPointer 4972 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4973 case Type::STK_ObjCObjectPointer: 4974 if (SrcKind == Type::STK_ObjCObjectPointer) 4975 return CK_BitCast; 4976 if (SrcKind == Type::STK_CPointer) 4977 return CK_CPointerToObjCPointerCast; 4978 maybeExtendBlockObject(*this, Src); 4979 return CK_BlockPointerToObjCPointerCast; 4980 case Type::STK_Bool: 4981 return CK_PointerToBoolean; 4982 case Type::STK_Integral: 4983 return CK_PointerToIntegral; 4984 case Type::STK_Floating: 4985 case Type::STK_FloatingComplex: 4986 case Type::STK_IntegralComplex: 4987 case Type::STK_MemberPointer: 4988 llvm_unreachable("illegal cast from pointer"); 4989 } 4990 llvm_unreachable("Should have returned before this"); 4991 4992 case Type::STK_Bool: // casting from bool is like casting from an integer 4993 case Type::STK_Integral: 4994 switch (DestTy->getScalarTypeKind()) { 4995 case Type::STK_CPointer: 4996 case Type::STK_ObjCObjectPointer: 4997 case Type::STK_BlockPointer: 4998 if (Src.get()->isNullPointerConstant(Context, 4999 Expr::NPC_ValueDependentIsNull)) 5000 return CK_NullToPointer; 5001 return CK_IntegralToPointer; 5002 case Type::STK_Bool: 5003 return CK_IntegralToBoolean; 5004 case Type::STK_Integral: 5005 return CK_IntegralCast; 5006 case Type::STK_Floating: 5007 return CK_IntegralToFloating; 5008 case Type::STK_IntegralComplex: 5009 Src = ImpCastExprToType(Src.get(), 5010 DestTy->castAs<ComplexType>()->getElementType(), 5011 CK_IntegralCast); 5012 return CK_IntegralRealToComplex; 5013 case Type::STK_FloatingComplex: 5014 Src = ImpCastExprToType(Src.get(), 5015 DestTy->castAs<ComplexType>()->getElementType(), 5016 CK_IntegralToFloating); 5017 return CK_FloatingRealToComplex; 5018 case Type::STK_MemberPointer: 5019 llvm_unreachable("member pointer type in C"); 5020 } 5021 llvm_unreachable("Should have returned before this"); 5022 5023 case Type::STK_Floating: 5024 switch (DestTy->getScalarTypeKind()) { 5025 case Type::STK_Floating: 5026 return CK_FloatingCast; 5027 case Type::STK_Bool: 5028 return CK_FloatingToBoolean; 5029 case Type::STK_Integral: 5030 return CK_FloatingToIntegral; 5031 case Type::STK_FloatingComplex: 5032 Src = ImpCastExprToType(Src.get(), 5033 DestTy->castAs<ComplexType>()->getElementType(), 5034 CK_FloatingCast); 5035 return CK_FloatingRealToComplex; 5036 case Type::STK_IntegralComplex: 5037 Src = ImpCastExprToType(Src.get(), 5038 DestTy->castAs<ComplexType>()->getElementType(), 5039 CK_FloatingToIntegral); 5040 return CK_IntegralRealToComplex; 5041 case Type::STK_CPointer: 5042 case Type::STK_ObjCObjectPointer: 5043 case Type::STK_BlockPointer: 5044 llvm_unreachable("valid float->pointer cast?"); 5045 case Type::STK_MemberPointer: 5046 llvm_unreachable("member pointer type in C"); 5047 } 5048 llvm_unreachable("Should have returned before this"); 5049 5050 case Type::STK_FloatingComplex: 5051 switch (DestTy->getScalarTypeKind()) { 5052 case Type::STK_FloatingComplex: 5053 return CK_FloatingComplexCast; 5054 case Type::STK_IntegralComplex: 5055 return CK_FloatingComplexToIntegralComplex; 5056 case Type::STK_Floating: { 5057 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5058 if (Context.hasSameType(ET, DestTy)) 5059 return CK_FloatingComplexToReal; 5060 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5061 return CK_FloatingCast; 5062 } 5063 case Type::STK_Bool: 5064 return CK_FloatingComplexToBoolean; 5065 case Type::STK_Integral: 5066 Src = ImpCastExprToType(Src.get(), 5067 SrcTy->castAs<ComplexType>()->getElementType(), 5068 CK_FloatingComplexToReal); 5069 return CK_FloatingToIntegral; 5070 case Type::STK_CPointer: 5071 case Type::STK_ObjCObjectPointer: 5072 case Type::STK_BlockPointer: 5073 llvm_unreachable("valid complex float->pointer cast?"); 5074 case Type::STK_MemberPointer: 5075 llvm_unreachable("member pointer type in C"); 5076 } 5077 llvm_unreachable("Should have returned before this"); 5078 5079 case Type::STK_IntegralComplex: 5080 switch (DestTy->getScalarTypeKind()) { 5081 case Type::STK_FloatingComplex: 5082 return CK_IntegralComplexToFloatingComplex; 5083 case Type::STK_IntegralComplex: 5084 return CK_IntegralComplexCast; 5085 case Type::STK_Integral: { 5086 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5087 if (Context.hasSameType(ET, DestTy)) 5088 return CK_IntegralComplexToReal; 5089 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5090 return CK_IntegralCast; 5091 } 5092 case Type::STK_Bool: 5093 return CK_IntegralComplexToBoolean; 5094 case Type::STK_Floating: 5095 Src = ImpCastExprToType(Src.get(), 5096 SrcTy->castAs<ComplexType>()->getElementType(), 5097 CK_IntegralComplexToReal); 5098 return CK_IntegralToFloating; 5099 case Type::STK_CPointer: 5100 case Type::STK_ObjCObjectPointer: 5101 case Type::STK_BlockPointer: 5102 llvm_unreachable("valid complex int->pointer cast?"); 5103 case Type::STK_MemberPointer: 5104 llvm_unreachable("member pointer type in C"); 5105 } 5106 llvm_unreachable("Should have returned before this"); 5107 } 5108 5109 llvm_unreachable("Unhandled scalar cast"); 5110 } 5111 5112 static bool breakDownVectorType(QualType type, uint64_t &len, 5113 QualType &eltType) { 5114 // Vectors are simple. 5115 if (const VectorType *vecType = type->getAs<VectorType>()) { 5116 len = vecType->getNumElements(); 5117 eltType = vecType->getElementType(); 5118 assert(eltType->isScalarType()); 5119 return true; 5120 } 5121 5122 // We allow lax conversion to and from non-vector types, but only if 5123 // they're real types (i.e. non-complex, non-pointer scalar types). 5124 if (!type->isRealType()) return false; 5125 5126 len = 1; 5127 eltType = type; 5128 return true; 5129 } 5130 5131 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) { 5132 uint64_t srcLen, destLen; 5133 QualType srcElt, destElt; 5134 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5135 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5136 5137 // ASTContext::getTypeSize will return the size rounded up to a 5138 // power of 2, so instead of using that, we need to use the raw 5139 // element size multiplied by the element count. 5140 uint64_t srcEltSize = S.Context.getTypeSize(srcElt); 5141 uint64_t destEltSize = S.Context.getTypeSize(destElt); 5142 5143 return (srcLen * srcEltSize == destLen * destEltSize); 5144 } 5145 5146 /// Is this a legal conversion between two known vector types? 5147 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5148 assert(destTy->isVectorType() || srcTy->isVectorType()); 5149 5150 if (!Context.getLangOpts().LaxVectorConversions) 5151 return false; 5152 return VectorTypesMatch(*this, srcTy, destTy); 5153 } 5154 5155 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5156 CastKind &Kind) { 5157 assert(VectorTy->isVectorType() && "Not a vector type!"); 5158 5159 if (Ty->isVectorType() || Ty->isIntegerType()) { 5160 if (!VectorTypesMatch(*this, Ty, VectorTy)) 5161 return Diag(R.getBegin(), 5162 Ty->isVectorType() ? 5163 diag::err_invalid_conversion_between_vectors : 5164 diag::err_invalid_conversion_between_vector_and_integer) 5165 << VectorTy << Ty << R; 5166 } else 5167 return Diag(R.getBegin(), 5168 diag::err_invalid_conversion_between_vector_and_scalar) 5169 << VectorTy << Ty << R; 5170 5171 Kind = CK_BitCast; 5172 return false; 5173 } 5174 5175 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5176 Expr *CastExpr, CastKind &Kind) { 5177 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5178 5179 QualType SrcTy = CastExpr->getType(); 5180 5181 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5182 // an ExtVectorType. 5183 // In OpenCL, casts between vectors of different types are not allowed. 5184 // (See OpenCL 6.2). 5185 if (SrcTy->isVectorType()) { 5186 if (!VectorTypesMatch(*this, SrcTy, DestTy) 5187 || (getLangOpts().OpenCL && 5188 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5189 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5190 << DestTy << SrcTy << R; 5191 return ExprError(); 5192 } 5193 Kind = CK_BitCast; 5194 return CastExpr; 5195 } 5196 5197 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5198 // conversion will take place first from scalar to elt type, and then 5199 // splat from elt type to vector. 5200 if (SrcTy->isPointerType()) 5201 return Diag(R.getBegin(), 5202 diag::err_invalid_conversion_between_vector_and_scalar) 5203 << DestTy << SrcTy << R; 5204 5205 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5206 ExprResult CastExprRes = CastExpr; 5207 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5208 if (CastExprRes.isInvalid()) 5209 return ExprError(); 5210 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5211 5212 Kind = CK_VectorSplat; 5213 return CastExpr; 5214 } 5215 5216 ExprResult 5217 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5218 Declarator &D, ParsedType &Ty, 5219 SourceLocation RParenLoc, Expr *CastExpr) { 5220 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5221 "ActOnCastExpr(): missing type or expr"); 5222 5223 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5224 if (D.isInvalidType()) 5225 return ExprError(); 5226 5227 if (getLangOpts().CPlusPlus) { 5228 // Check that there are no default arguments (C++ only). 5229 CheckExtraCXXDefaultArguments(D); 5230 } 5231 5232 checkUnusedDeclAttributes(D); 5233 5234 QualType castType = castTInfo->getType(); 5235 Ty = CreateParsedType(castType, castTInfo); 5236 5237 bool isVectorLiteral = false; 5238 5239 // Check for an altivec or OpenCL literal, 5240 // i.e. all the elements are integer constants. 5241 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5242 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5243 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5244 && castType->isVectorType() && (PE || PLE)) { 5245 if (PLE && PLE->getNumExprs() == 0) { 5246 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5247 return ExprError(); 5248 } 5249 if (PE || PLE->getNumExprs() == 1) { 5250 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5251 if (!E->getType()->isVectorType()) 5252 isVectorLiteral = true; 5253 } 5254 else 5255 isVectorLiteral = true; 5256 } 5257 5258 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5259 // then handle it as such. 5260 if (isVectorLiteral) 5261 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5262 5263 // If the Expr being casted is a ParenListExpr, handle it specially. 5264 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5265 // sequence of BinOp comma operators. 5266 if (isa<ParenListExpr>(CastExpr)) { 5267 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5268 if (Result.isInvalid()) return ExprError(); 5269 CastExpr = Result.get(); 5270 } 5271 5272 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5273 !getSourceManager().isInSystemMacro(LParenLoc)) 5274 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5275 5276 CheckTollFreeBridgeCast(castType, CastExpr); 5277 5278 CheckObjCBridgeRelatedCast(castType, CastExpr); 5279 5280 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5281 } 5282 5283 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5284 SourceLocation RParenLoc, Expr *E, 5285 TypeSourceInfo *TInfo) { 5286 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5287 "Expected paren or paren list expression"); 5288 5289 Expr **exprs; 5290 unsigned numExprs; 5291 Expr *subExpr; 5292 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5293 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5294 LiteralLParenLoc = PE->getLParenLoc(); 5295 LiteralRParenLoc = PE->getRParenLoc(); 5296 exprs = PE->getExprs(); 5297 numExprs = PE->getNumExprs(); 5298 } else { // isa<ParenExpr> by assertion at function entrance 5299 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5300 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5301 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5302 exprs = &subExpr; 5303 numExprs = 1; 5304 } 5305 5306 QualType Ty = TInfo->getType(); 5307 assert(Ty->isVectorType() && "Expected vector type"); 5308 5309 SmallVector<Expr *, 8> initExprs; 5310 const VectorType *VTy = Ty->getAs<VectorType>(); 5311 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5312 5313 // '(...)' form of vector initialization in AltiVec: the number of 5314 // initializers must be one or must match the size of the vector. 5315 // If a single value is specified in the initializer then it will be 5316 // replicated to all the components of the vector 5317 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5318 // The number of initializers must be one or must match the size of the 5319 // vector. If a single value is specified in the initializer then it will 5320 // be replicated to all the components of the vector 5321 if (numExprs == 1) { 5322 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5323 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5324 if (Literal.isInvalid()) 5325 return ExprError(); 5326 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5327 PrepareScalarCast(Literal, ElemTy)); 5328 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5329 } 5330 else if (numExprs < numElems) { 5331 Diag(E->getExprLoc(), 5332 diag::err_incorrect_number_of_vector_initializers); 5333 return ExprError(); 5334 } 5335 else 5336 initExprs.append(exprs, exprs + numExprs); 5337 } 5338 else { 5339 // For OpenCL, when the number of initializers is a single value, 5340 // it will be replicated to all components of the vector. 5341 if (getLangOpts().OpenCL && 5342 VTy->getVectorKind() == VectorType::GenericVector && 5343 numExprs == 1) { 5344 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5345 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5346 if (Literal.isInvalid()) 5347 return ExprError(); 5348 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5349 PrepareScalarCast(Literal, ElemTy)); 5350 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5351 } 5352 5353 initExprs.append(exprs, exprs + numExprs); 5354 } 5355 // FIXME: This means that pretty-printing the final AST will produce curly 5356 // braces instead of the original commas. 5357 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5358 initExprs, LiteralRParenLoc); 5359 initE->setType(Ty); 5360 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5361 } 5362 5363 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5364 /// the ParenListExpr into a sequence of comma binary operators. 5365 ExprResult 5366 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5367 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5368 if (!E) 5369 return OrigExpr; 5370 5371 ExprResult Result(E->getExpr(0)); 5372 5373 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5374 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5375 E->getExpr(i)); 5376 5377 if (Result.isInvalid()) return ExprError(); 5378 5379 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5380 } 5381 5382 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5383 SourceLocation R, 5384 MultiExprArg Val) { 5385 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5386 return expr; 5387 } 5388 5389 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5390 /// constant and the other is not a pointer. Returns true if a diagnostic is 5391 /// emitted. 5392 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5393 SourceLocation QuestionLoc) { 5394 Expr *NullExpr = LHSExpr; 5395 Expr *NonPointerExpr = RHSExpr; 5396 Expr::NullPointerConstantKind NullKind = 5397 NullExpr->isNullPointerConstant(Context, 5398 Expr::NPC_ValueDependentIsNotNull); 5399 5400 if (NullKind == Expr::NPCK_NotNull) { 5401 NullExpr = RHSExpr; 5402 NonPointerExpr = LHSExpr; 5403 NullKind = 5404 NullExpr->isNullPointerConstant(Context, 5405 Expr::NPC_ValueDependentIsNotNull); 5406 } 5407 5408 if (NullKind == Expr::NPCK_NotNull) 5409 return false; 5410 5411 if (NullKind == Expr::NPCK_ZeroExpression) 5412 return false; 5413 5414 if (NullKind == Expr::NPCK_ZeroLiteral) { 5415 // In this case, check to make sure that we got here from a "NULL" 5416 // string in the source code. 5417 NullExpr = NullExpr->IgnoreParenImpCasts(); 5418 SourceLocation loc = NullExpr->getExprLoc(); 5419 if (!findMacroSpelling(loc, "NULL")) 5420 return false; 5421 } 5422 5423 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5424 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5425 << NonPointerExpr->getType() << DiagType 5426 << NonPointerExpr->getSourceRange(); 5427 return true; 5428 } 5429 5430 /// \brief Return false if the condition expression is valid, true otherwise. 5431 static bool checkCondition(Sema &S, Expr *Cond) { 5432 QualType CondTy = Cond->getType(); 5433 5434 // C99 6.5.15p2 5435 if (CondTy->isScalarType()) return false; 5436 5437 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5438 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5439 return false; 5440 5441 // Emit the proper error message. 5442 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5443 diag::err_typecheck_cond_expect_scalar : 5444 diag::err_typecheck_cond_expect_scalar_or_vector) 5445 << CondTy; 5446 return true; 5447 } 5448 5449 /// \brief Return false if the two expressions can be converted to a vector, 5450 /// true otherwise 5451 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5452 ExprResult &RHS, 5453 QualType CondTy) { 5454 // Both operands should be of scalar type. 5455 if (!LHS.get()->getType()->isScalarType()) { 5456 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5457 << CondTy; 5458 return true; 5459 } 5460 if (!RHS.get()->getType()->isScalarType()) { 5461 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5462 << CondTy; 5463 return true; 5464 } 5465 5466 // Implicity convert these scalars to the type of the condition. 5467 LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast); 5468 RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast); 5469 return false; 5470 } 5471 5472 /// \brief Handle when one or both operands are void type. 5473 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5474 ExprResult &RHS) { 5475 Expr *LHSExpr = LHS.get(); 5476 Expr *RHSExpr = RHS.get(); 5477 5478 if (!LHSExpr->getType()->isVoidType()) 5479 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5480 << RHSExpr->getSourceRange(); 5481 if (!RHSExpr->getType()->isVoidType()) 5482 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5483 << LHSExpr->getSourceRange(); 5484 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5485 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5486 return S.Context.VoidTy; 5487 } 5488 5489 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5490 /// true otherwise. 5491 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5492 QualType PointerTy) { 5493 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5494 !NullExpr.get()->isNullPointerConstant(S.Context, 5495 Expr::NPC_ValueDependentIsNull)) 5496 return true; 5497 5498 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5499 return false; 5500 } 5501 5502 /// \brief Checks compatibility between two pointers and return the resulting 5503 /// type. 5504 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5505 ExprResult &RHS, 5506 SourceLocation Loc) { 5507 QualType LHSTy = LHS.get()->getType(); 5508 QualType RHSTy = RHS.get()->getType(); 5509 5510 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5511 // Two identical pointers types are always compatible. 5512 return LHSTy; 5513 } 5514 5515 QualType lhptee, rhptee; 5516 5517 // Get the pointee types. 5518 bool IsBlockPointer = false; 5519 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5520 lhptee = LHSBTy->getPointeeType(); 5521 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5522 IsBlockPointer = true; 5523 } else { 5524 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5525 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5526 } 5527 5528 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5529 // differently qualified versions of compatible types, the result type is 5530 // a pointer to an appropriately qualified version of the composite 5531 // type. 5532 5533 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5534 // clause doesn't make sense for our extensions. E.g. address space 2 should 5535 // be incompatible with address space 3: they may live on different devices or 5536 // anything. 5537 Qualifiers lhQual = lhptee.getQualifiers(); 5538 Qualifiers rhQual = rhptee.getQualifiers(); 5539 5540 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5541 lhQual.removeCVRQualifiers(); 5542 rhQual.removeCVRQualifiers(); 5543 5544 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5545 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5546 5547 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5548 5549 if (CompositeTy.isNull()) { 5550 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5551 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5552 << RHS.get()->getSourceRange(); 5553 // In this situation, we assume void* type. No especially good 5554 // reason, but this is what gcc does, and we do have to pick 5555 // to get a consistent AST. 5556 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5557 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5558 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5559 return incompatTy; 5560 } 5561 5562 // The pointer types are compatible. 5563 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5564 if (IsBlockPointer) 5565 ResultTy = S.Context.getBlockPointerType(ResultTy); 5566 else 5567 ResultTy = S.Context.getPointerType(ResultTy); 5568 5569 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5570 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5571 return ResultTy; 5572 } 5573 5574 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or 5575 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally 5576 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else). 5577 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) { 5578 if (QT->isObjCIdType()) 5579 return true; 5580 5581 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 5582 if (!OPT) 5583 return false; 5584 5585 if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl()) 5586 if (ID->getIdentifier() != &C.Idents.get("NSObject")) 5587 return false; 5588 5589 ObjCProtocolDecl* PNSCopying = 5590 S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation()); 5591 ObjCProtocolDecl* PNSObject = 5592 S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation()); 5593 5594 for (auto *Proto : OPT->quals()) { 5595 if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) || 5596 (PNSObject && declaresSameEntity(Proto, PNSObject))) 5597 ; 5598 else 5599 return false; 5600 } 5601 return true; 5602 } 5603 5604 /// \brief Return the resulting type when the operands are both block pointers. 5605 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5606 ExprResult &LHS, 5607 ExprResult &RHS, 5608 SourceLocation Loc) { 5609 QualType LHSTy = LHS.get()->getType(); 5610 QualType RHSTy = RHS.get()->getType(); 5611 5612 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5613 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5614 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5615 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5616 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5617 return destType; 5618 } 5619 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5620 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5621 << RHS.get()->getSourceRange(); 5622 return QualType(); 5623 } 5624 5625 // We have 2 block pointer types. 5626 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5627 } 5628 5629 /// \brief Return the resulting type when the operands are both pointers. 5630 static QualType 5631 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5632 ExprResult &RHS, 5633 SourceLocation Loc) { 5634 // get the pointer types 5635 QualType LHSTy = LHS.get()->getType(); 5636 QualType RHSTy = RHS.get()->getType(); 5637 5638 // get the "pointed to" types 5639 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5640 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5641 5642 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5643 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5644 // Figure out necessary qualifiers (C99 6.5.15p6) 5645 QualType destPointee 5646 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5647 QualType destType = S.Context.getPointerType(destPointee); 5648 // Add qualifiers if necessary. 5649 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5650 // Promote to void*. 5651 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5652 return destType; 5653 } 5654 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5655 QualType destPointee 5656 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5657 QualType destType = S.Context.getPointerType(destPointee); 5658 // Add qualifiers if necessary. 5659 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 5660 // Promote to void*. 5661 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5662 return destType; 5663 } 5664 5665 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5666 } 5667 5668 /// \brief Return false if the first expression is not an integer and the second 5669 /// expression is not a pointer, true otherwise. 5670 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5671 Expr* PointerExpr, SourceLocation Loc, 5672 bool IsIntFirstExpr) { 5673 if (!PointerExpr->getType()->isPointerType() || 5674 !Int.get()->getType()->isIntegerType()) 5675 return false; 5676 5677 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5678 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5679 5680 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5681 << Expr1->getType() << Expr2->getType() 5682 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5683 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 5684 CK_IntegralToPointer); 5685 return true; 5686 } 5687 5688 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5689 /// In that case, LHS = cond. 5690 /// C99 6.5.15 5691 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5692 ExprResult &RHS, ExprValueKind &VK, 5693 ExprObjectKind &OK, 5694 SourceLocation QuestionLoc) { 5695 5696 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5697 if (!LHSResult.isUsable()) return QualType(); 5698 LHS = LHSResult; 5699 5700 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5701 if (!RHSResult.isUsable()) return QualType(); 5702 RHS = RHSResult; 5703 5704 // C++ is sufficiently different to merit its own checker. 5705 if (getLangOpts().CPlusPlus) 5706 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5707 5708 VK = VK_RValue; 5709 OK = OK_Ordinary; 5710 5711 // First, check the condition. 5712 Cond = UsualUnaryConversions(Cond.get()); 5713 if (Cond.isInvalid()) 5714 return QualType(); 5715 if (checkCondition(*this