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/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/AnalysisBasedWarnings.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/DelayedDiagnostic.h" 36 #include "clang/Sema/Designator.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/Lookup.h" 39 #include "clang/Sema/ParsedTemplate.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaFixItUtils.h" 43 #include "clang/Sema/Template.h" 44 using namespace clang; 45 using namespace sema; 46 47 /// \brief Determine whether the use of this declaration is valid, without 48 /// emitting diagnostics. 49 bool Sema::CanUseDecl(NamedDecl *D) { 50 // See if this is an auto-typed variable whose initializer we are parsing. 51 if (ParsingInitForAutoVars.count(D)) 52 return false; 53 54 // See if this is a deleted function. 55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 56 if (FD->isDeleted()) 57 return false; 58 59 // If the function has a deduced return type, and we can't deduce it, 60 // then we can't use it either. 61 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 62 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false)) 63 return false; 64 } 65 66 // See if this function is unavailable. 67 if (D->getAvailability() == AR_Unavailable && 68 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 69 return false; 70 71 return true; 72 } 73 74 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 75 // Warn if this is used but marked unused. 76 if (D->hasAttr<UnusedAttr>()) { 77 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 78 if (!DC->hasAttr<UnusedAttr>()) 79 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 80 } 81 } 82 83 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 84 NamedDecl *D, SourceLocation Loc, 85 const ObjCInterfaceDecl *UnknownObjCClass) { 86 // See if this declaration is unavailable or deprecated. 87 std::string Message; 88 AvailabilityResult Result = D->getAvailability(&Message); 89 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 90 if (Result == AR_Available) { 91 const DeclContext *DC = ECD->getDeclContext(); 92 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 93 Result = TheEnumDecl->getAvailability(&Message); 94 } 95 96 const ObjCPropertyDecl *ObjCPDecl = 0; 97 if (Result == AR_Deprecated || Result == AR_Unavailable) { 98 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 99 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 100 AvailabilityResult PDeclResult = PD->getAvailability(0); 101 if (PDeclResult == Result) 102 ObjCPDecl = PD; 103 } 104 } 105 } 106 107 switch (Result) { 108 case AR_Available: 109 case AR_NotYetIntroduced: 110 break; 111 112 case AR_Deprecated: 113 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 114 break; 115 116 case AR_Unavailable: 117 if (S.getCurContextAvailability() != AR_Unavailable) { 118 if (Message.empty()) { 119 if (!UnknownObjCClass) { 120 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 121 if (ObjCPDecl) 122 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 123 << ObjCPDecl->getDeclName() << 1; 124 } 125 else 126 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 127 << D->getDeclName(); 128 } 129 else 130 S.Diag(Loc, diag::err_unavailable_message) 131 << D->getDeclName() << Message; 132 S.Diag(D->getLocation(), diag::note_unavailable_here) 133 << isa<FunctionDecl>(D) << false; 134 if (ObjCPDecl) 135 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 136 << ObjCPDecl->getDeclName() << 1; 137 } 138 break; 139 } 140 return Result; 141 } 142 143 /// \brief Emit a note explaining that this function is deleted. 144 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 145 assert(Decl->isDeleted()); 146 147 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 148 149 if (Method && Method->isDeleted() && Method->isDefaulted()) { 150 // If the method was explicitly defaulted, point at that declaration. 151 if (!Method->isImplicit()) 152 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 153 154 // Try to diagnose why this special member function was implicitly 155 // deleted. This might fail, if that reason no longer applies. 156 CXXSpecialMember CSM = getSpecialMember(Method); 157 if (CSM != CXXInvalid) 158 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 159 160 return; 161 } 162 163 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 164 if (CXXConstructorDecl *BaseCD = 165 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 166 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 167 if (BaseCD->isDeleted()) { 168 NoteDeletedFunction(BaseCD); 169 } else { 170 // FIXME: An explanation of why exactly it can't be inherited 171 // would be nice. 172 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 173 } 174 return; 175 } 176 } 177 178 Diag(Decl->getLocation(), diag::note_unavailable_here) 179 << 1 << true; 180 } 181 182 /// \brief Determine whether a FunctionDecl was ever declared with an 183 /// explicit storage class. 184 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 185 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 186 E = D->redecls_end(); 187 I != E; ++I) { 188 if (I->getStorageClass() != SC_None) 189 return true; 190 } 191 return false; 192 } 193 194 /// \brief Check whether we're in an extern inline function and referring to a 195 /// variable or function with internal linkage (C11 6.7.4p3). 196 /// 197 /// This is only a warning because we used to silently accept this code, but 198 /// in many cases it will not behave correctly. This is not enabled in C++ mode 199 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 200 /// and so while there may still be user mistakes, most of the time we can't 201 /// prove that there are errors. 202 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 203 const NamedDecl *D, 204 SourceLocation Loc) { 205 // This is disabled under C++; there are too many ways for this to fire in 206 // contexts where the warning is a false positive, or where it is technically 207 // correct but benign. 208 if (S.getLangOpts().CPlusPlus) 209 return; 210 211 // Check if this is an inlined function or method. 212 FunctionDecl *Current = S.getCurFunctionDecl(); 213 if (!Current) 214 return; 215 if (!Current->isInlined()) 216 return; 217 if (!Current->isExternallyVisible()) 218 return; 219 220 // Check if the decl has internal linkage. 221 if (D->getFormalLinkage() != InternalLinkage) 222 return; 223 224 // Downgrade from ExtWarn to Extension if 225 // (1) the supposedly external inline function is in the main file, 226 // and probably won't be included anywhere else. 227 // (2) the thing we're referencing is a pure function. 228 // (3) the thing we're referencing is another inline function. 229 // This last can give us false negatives, but it's better than warning on 230 // wrappers for simple C library functions. 231 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 232 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 233 if (!DowngradeWarning && UsedFn) 234 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 235 236 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 237 : diag::warn_internal_in_extern_inline) 238 << /*IsVar=*/!UsedFn << D; 239 240 S.MaybeSuggestAddingStaticToDecl(Current); 241 242 S.Diag(D->getCanonicalDecl()->getLocation(), 243 diag::note_internal_decl_declared_here) 244 << D; 245 } 246 247 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 248 const FunctionDecl *First = Cur->getFirstDeclaration(); 249 250 // Suggest "static" on the function, if possible. 251 if (!hasAnyExplicitStorageClass(First)) { 252 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 253 Diag(DeclBegin, diag::note_convert_inline_to_static) 254 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 255 } 256 } 257 258 /// \brief Determine whether the use of this declaration is valid, and 259 /// emit any corresponding diagnostics. 260 /// 261 /// This routine diagnoses various problems with referencing 262 /// declarations that can occur when using a declaration. For example, 263 /// it might warn if a deprecated or unavailable declaration is being 264 /// used, or produce an error (and return true) if a C++0x deleted 265 /// function is being used. 266 /// 267 /// \returns true if there was an error (this declaration cannot be 268 /// referenced), false otherwise. 269 /// 270 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 271 const ObjCInterfaceDecl *UnknownObjCClass) { 272 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 273 // If there were any diagnostics suppressed by template argument deduction, 274 // emit them now. 275 SuppressedDiagnosticsMap::iterator 276 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 277 if (Pos != SuppressedDiagnostics.end()) { 278 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 279 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 280 Diag(Suppressed[I].first, Suppressed[I].second); 281 282 // Clear out the list of suppressed diagnostics, so that we don't emit 283 // them again for this specialization. However, we don't obsolete this 284 // entry from the table, because we want to avoid ever emitting these 285 // diagnostics again. 286 Suppressed.clear(); 287 } 288 } 289 290 // See if this is an auto-typed variable whose initializer we are parsing. 291 if (ParsingInitForAutoVars.count(D)) { 292 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 293 << D->getDeclName(); 294 return true; 295 } 296 297 // See if this is a deleted function. 298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 299 if (FD->isDeleted()) { 300 Diag(Loc, diag::err_deleted_function_use); 301 NoteDeletedFunction(FD); 302 return true; 303 } 304 305 // If the function has a deduced return type, and we can't deduce it, 306 // then we can't use it either. 307 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 308 DeduceReturnType(FD, Loc)) 309 return true; 310 } 311 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 312 313 DiagnoseUnusedOfDecl(*this, D, Loc); 314 315 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 316 317 return false; 318 } 319 320 /// \brief Retrieve the message suffix that should be added to a 321 /// diagnostic complaining about the given function being deleted or 322 /// unavailable. 323 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 324 std::string Message; 325 if (FD->getAvailability(&Message)) 326 return ": " + Message; 327 328 return std::string(); 329 } 330 331 /// DiagnoseSentinelCalls - This routine checks whether a call or 332 /// message-send is to a declaration with the sentinel attribute, and 333 /// if so, it checks that the requirements of the sentinel are 334 /// satisfied. 335 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 336 ArrayRef<Expr *> Args) { 337 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 338 if (!attr) 339 return; 340 341 // The number of formal parameters of the declaration. 342 unsigned numFormalParams; 343 344 // The kind of declaration. This is also an index into a %select in 345 // the diagnostic. 346 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 347 348 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 349 numFormalParams = MD->param_size(); 350 calleeType = CT_Method; 351 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 352 numFormalParams = FD->param_size(); 353 calleeType = CT_Function; 354 } else if (isa<VarDecl>(D)) { 355 QualType type = cast<ValueDecl>(D)->getType(); 356 const FunctionType *fn = 0; 357 if (const PointerType *ptr = type->getAs<PointerType>()) { 358 fn = ptr->getPointeeType()->getAs<FunctionType>(); 359 if (!fn) return; 360 calleeType = CT_Function; 361 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 362 fn = ptr->getPointeeType()->castAs<FunctionType>(); 363 calleeType = CT_Block; 364 } else { 365 return; 366 } 367 368 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 369 numFormalParams = proto->getNumArgs(); 370 } else { 371 numFormalParams = 0; 372 } 373 } else { 374 return; 375 } 376 377 // "nullPos" is the number of formal parameters at the end which 378 // effectively count as part of the variadic arguments. This is 379 // useful if you would prefer to not have *any* formal parameters, 380 // but the language forces you to have at least one. 381 unsigned nullPos = attr->getNullPos(); 382 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 383 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 384 385 // The number of arguments which should follow the sentinel. 386 unsigned numArgsAfterSentinel = attr->getSentinel(); 387 388 // If there aren't enough arguments for all the formal parameters, 389 // the sentinel, and the args after the sentinel, complain. 390 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 391 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 392 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 393 return; 394 } 395 396 // Otherwise, find the sentinel expression. 397 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 398 if (!sentinelExpr) return; 399 if (sentinelExpr->isValueDependent()) return; 400 if (Context.isSentinelNullExpr(sentinelExpr)) return; 401 402 // Pick a reasonable string to insert. Optimistically use 'nil' or 403 // 'NULL' if those are actually defined in the context. Only use 404 // 'nil' for ObjC methods, where it's much more likely that the 405 // variadic arguments form a list of object pointers. 406 SourceLocation MissingNilLoc 407 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 408 std::string NullValue; 409 if (calleeType == CT_Method && 410 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 411 NullValue = "nil"; 412 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 413 NullValue = "NULL"; 414 else 415 NullValue = "(void*) 0"; 416 417 if (MissingNilLoc.isInvalid()) 418 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 419 else 420 Diag(MissingNilLoc, diag::warn_missing_sentinel) 421 << int(calleeType) 422 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 423 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 424 } 425 426 SourceRange Sema::getExprRange(Expr *E) const { 427 return E ? E->getSourceRange() : SourceRange(); 428 } 429 430 //===----------------------------------------------------------------------===// 431 // Standard Promotions and Conversions 432 //===----------------------------------------------------------------------===// 433 434 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 435 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 436 // Handle any placeholder expressions which made it here. 437 if (E->getType()->isPlaceholderType()) { 438 ExprResult result = CheckPlaceholderExpr(E); 439 if (result.isInvalid()) return ExprError(); 440 E = result.take(); 441 } 442 443 QualType Ty = E->getType(); 444 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 445 446 if (Ty->isFunctionType()) 447 E = ImpCastExprToType(E, Context.getPointerType(Ty), 448 CK_FunctionToPointerDecay).take(); 449 else if (Ty->isArrayType()) { 450 // In C90 mode, arrays only promote to pointers if the array expression is 451 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 452 // type 'array of type' is converted to an expression that has type 'pointer 453 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 454 // that has type 'array of type' ...". The relevant change is "an lvalue" 455 // (C90) to "an expression" (C99). 456 // 457 // C++ 4.2p1: 458 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 459 // T" can be converted to an rvalue of type "pointer to T". 460 // 461 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 462 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 463 CK_ArrayToPointerDecay).take(); 464 } 465 return Owned(E); 466 } 467 468 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 469 // Check to see if we are dereferencing a null pointer. If so, 470 // and if not volatile-qualified, this is undefined behavior that the 471 // optimizer will delete, so warn about it. People sometimes try to use this 472 // to get a deterministic trap and are surprised by clang's behavior. This 473 // only handles the pattern "*null", which is a very syntactic check. 474 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 475 if (UO->getOpcode() == UO_Deref && 476 UO->getSubExpr()->IgnoreParenCasts()-> 477 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 478 !UO->getType().isVolatileQualified()) { 479 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 480 S.PDiag(diag::warn_indirection_through_null) 481 << UO->getSubExpr()->getSourceRange()); 482 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 483 S.PDiag(diag::note_indirection_through_null)); 484 } 485 } 486 487 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 488 SourceLocation AssignLoc, 489 const Expr* RHS) { 490 const ObjCIvarDecl *IV = OIRE->getDecl(); 491 if (!IV) 492 return; 493 494 DeclarationName MemberName = IV->getDeclName(); 495 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 496 if (!Member || !Member->isStr("isa")) 497 return; 498 499 const Expr *Base = OIRE->getBase(); 500 QualType BaseType = Base->getType(); 501 if (OIRE->isArrow()) 502 BaseType = BaseType->getPointeeType(); 503 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 504 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 505 ObjCInterfaceDecl *ClassDeclared = 0; 506 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 507 if (!ClassDeclared->getSuperClass() 508 && (*ClassDeclared->ivar_begin()) == IV) { 509 if (RHS) { 510 NamedDecl *ObjectSetClass = 511 S.LookupSingleName(S.TUScope, 512 &S.Context.Idents.get("object_setClass"), 513 SourceLocation(), S.LookupOrdinaryName); 514 if (ObjectSetClass) { 515 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 516 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 517 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 518 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 519 AssignLoc), ",") << 520 FixItHint::CreateInsertion(RHSLocEnd, ")"); 521 } 522 else 523 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 524 } else { 525 NamedDecl *ObjectGetClass = 526 S.LookupSingleName(S.TUScope, 527 &S.Context.Idents.get("object_getClass"), 528 SourceLocation(), S.LookupOrdinaryName); 529 if (ObjectGetClass) 530 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 531 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 532 FixItHint::CreateReplacement( 533 SourceRange(OIRE->getOpLoc(), 534 OIRE->getLocEnd()), ")"); 535 else 536 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 537 } 538 S.Diag(IV->getLocation(), diag::note_ivar_decl); 539 } 540 } 541 } 542 543 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 544 // Handle any placeholder expressions which made it here. 545 if (E->getType()->isPlaceholderType()) { 546 ExprResult result = CheckPlaceholderExpr(E); 547 if (result.isInvalid()) return ExprError(); 548 E = result.take(); 549 } 550 551 // C++ [conv.lval]p1: 552 // A glvalue of a non-function, non-array type T can be 553 // converted to a prvalue. 554 if (!E->isGLValue()) return Owned(E); 555 556 QualType T = E->getType(); 557 assert(!T.isNull() && "r-value conversion on typeless expression?"); 558 559 // We don't want to throw lvalue-to-rvalue casts on top of 560 // expressions of certain types in C++. 561 if (getLangOpts().CPlusPlus && 562 (E->getType() == Context.OverloadTy || 563 T->isDependentType() || 564 T->isRecordType())) 565 return Owned(E); 566 567 // The C standard is actually really unclear on this point, and 568 // DR106 tells us what the result should be but not why. It's 569 // generally best to say that void types just doesn't undergo 570 // lvalue-to-rvalue at all. Note that expressions of unqualified 571 // 'void' type are never l-values, but qualified void can be. 572 if (T->isVoidType()) 573 return Owned(E); 574 575 // OpenCL usually rejects direct accesses to values of 'half' type. 576 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 577 T->isHalfType()) { 578 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 579 << 0 << T; 580 return ExprError(); 581 } 582 583 CheckForNullPointerDereference(*this, E); 584 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 585 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 586 &Context.Idents.get("object_getClass"), 587 SourceLocation(), LookupOrdinaryName); 588 if (ObjectGetClass) 589 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 590 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 591 FixItHint::CreateReplacement( 592 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 593 else 594 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 595 } 596 else if (const ObjCIvarRefExpr *OIRE = 597 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 598 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 599 600 // C++ [conv.lval]p1: 601 // [...] If T is a non-class type, the type of the prvalue is the 602 // cv-unqualified version of T. Otherwise, the type of the 603 // rvalue is T. 604 // 605 // C99 6.3.2.1p2: 606 // If the lvalue has qualified type, the value has the unqualified 607 // version of the type of the lvalue; otherwise, the value has the 608 // type of the lvalue. 609 if (T.hasQualifiers()) 610 T = T.getUnqualifiedType(); 611 612 UpdateMarkingForLValueToRValue(E); 613 614 // Loading a __weak object implicitly retains the value, so we need a cleanup to 615 // balance that. 616 if (getLangOpts().ObjCAutoRefCount && 617 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 618 ExprNeedsCleanups = true; 619 620 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 621 E, 0, VK_RValue)); 622 623 // C11 6.3.2.1p2: 624 // ... if the lvalue has atomic type, the value has the non-atomic version 625 // of the type of the lvalue ... 626 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 627 T = Atomic->getValueType().getUnqualifiedType(); 628 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 629 Res.get(), 0, VK_RValue)); 630 } 631 632 return Res; 633 } 634 635 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 636 ExprResult Res = DefaultFunctionArrayConversion(E); 637 if (Res.isInvalid()) 638 return ExprError(); 639 Res = DefaultLvalueConversion(Res.take()); 640 if (Res.isInvalid()) 641 return ExprError(); 642 return Res; 643 } 644 645 646 /// UsualUnaryConversions - Performs various conversions that are common to most 647 /// operators (C99 6.3). The conversions of array and function types are 648 /// sometimes suppressed. For example, the array->pointer conversion doesn't 649 /// apply if the array is an argument to the sizeof or address (&) operators. 650 /// In these instances, this routine should *not* be called. 651 ExprResult Sema::UsualUnaryConversions(Expr *E) { 652 // First, convert to an r-value. 653 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 654 if (Res.isInvalid()) 655 return ExprError(); 656 E = Res.take(); 657 658 QualType Ty = E->getType(); 659 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 660 661 // Half FP have to be promoted to float unless it is natively supported 662 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 663 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 664 665 // Try to perform integral promotions if the object has a theoretically 666 // promotable type. 667 if (Ty->isIntegralOrUnscopedEnumerationType()) { 668 // C99 6.3.1.1p2: 669 // 670 // The following may be used in an expression wherever an int or 671 // unsigned int may be used: 672 // - an object or expression with an integer type whose integer 673 // conversion rank is less than or equal to the rank of int 674 // and unsigned int. 675 // - A bit-field of type _Bool, int, signed int, or unsigned int. 676 // 677 // If an int can represent all values of the original type, the 678 // value is converted to an int; otherwise, it is converted to an 679 // unsigned int. These are called the integer promotions. All 680 // other types are unchanged by the integer promotions. 681 682 QualType PTy = Context.isPromotableBitField(E); 683 if (!PTy.isNull()) { 684 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 685 return Owned(E); 686 } 687 if (Ty->isPromotableIntegerType()) { 688 QualType PT = Context.getPromotedIntegerType(Ty); 689 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 690 return Owned(E); 691 } 692 } 693 return Owned(E); 694 } 695 696 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 697 /// do not have a prototype. Arguments that have type float or __fp16 698 /// are promoted to double. All other argument types are converted by 699 /// UsualUnaryConversions(). 700 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 701 QualType Ty = E->getType(); 702 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 703 704 ExprResult Res = UsualUnaryConversions(E); 705 if (Res.isInvalid()) 706 return ExprError(); 707 E = Res.take(); 708 709 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 710 // double. 711 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 712 if (BTy && (BTy->getKind() == BuiltinType::Half || 713 BTy->getKind() == BuiltinType::Float)) 714 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 715 716 // C++ performs lvalue-to-rvalue conversion as a default argument 717 // promotion, even on class types, but note: 718 // C++11 [conv.lval]p2: 719 // When an lvalue-to-rvalue conversion occurs in an unevaluated 720 // operand or a subexpression thereof the value contained in the 721 // referenced object is not accessed. Otherwise, if the glvalue 722 // has a class type, the conversion copy-initializes a temporary 723 // of type T from the glvalue and the result of the conversion 724 // is a prvalue for the temporary. 725 // FIXME: add some way to gate this entire thing for correctness in 726 // potentially potentially evaluated contexts. 727 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 728 ExprResult Temp = PerformCopyInitialization( 729 InitializedEntity::InitializeTemporary(E->getType()), 730 E->getExprLoc(), 731 Owned(E)); 732 if (Temp.isInvalid()) 733 return ExprError(); 734 E = Temp.get(); 735 } 736 737 return Owned(E); 738 } 739 740 /// Determine the degree of POD-ness for an expression. 741 /// Incomplete types are considered POD, since this check can be performed 742 /// when we're in an unevaluated context. 743 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 744 if (Ty->isIncompleteType()) { 745 // C++11 [expr.call]p7: 746 // After these conversions, if the argument does not have arithmetic, 747 // enumeration, pointer, pointer to member, or class type, the program 748 // is ill-formed. 749 // 750 // Since we've already performed array-to-pointer and function-to-pointer 751 // decay, the only such type in C++ is cv void. This also handles 752 // initializer lists as variadic arguments. 753 if (Ty->isVoidType()) 754 return VAK_Invalid; 755 756 if (Ty->isObjCObjectType()) 757 return VAK_Invalid; 758 return VAK_Valid; 759 } 760 761 if (Ty.isCXX98PODType(Context)) 762 return VAK_Valid; 763 764 // C++11 [expr.call]p7: 765 // Passing a potentially-evaluated argument of class type (Clause 9) 766 // having a non-trivial copy constructor, a non-trivial move constructor, 767 // or a non-trivial destructor, with no corresponding parameter, 768 // is conditionally-supported with implementation-defined semantics. 769 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 770 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 771 if (!Record->hasNonTrivialCopyConstructor() && 772 !Record->hasNonTrivialMoveConstructor() && 773 !Record->hasNonTrivialDestructor()) 774 return VAK_ValidInCXX11; 775 776 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 777 return VAK_Valid; 778 779 if (Ty->isObjCObjectType()) 780 return VAK_Invalid; 781 782 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 783 // permitted to reject them. We should consider doing so. 784 return VAK_Undefined; 785 } 786 787 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 788 // Don't allow one to pass an Objective-C interface to a vararg. 789 const QualType &Ty = E->getType(); 790 VarArgKind VAK = isValidVarArgType(Ty); 791 792 // Complain about passing non-POD types through varargs. 793 switch (VAK) { 794 case VAK_Valid: 795 break; 796 797 case VAK_ValidInCXX11: 798 DiagRuntimeBehavior( 799 E->getLocStart(), 0, 800 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 801 << E->getType() << CT); 802 break; 803 804 case VAK_Undefined: 805 DiagRuntimeBehavior( 806 E->getLocStart(), 0, 807 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 808 << getLangOpts().CPlusPlus11 << Ty << CT); 809 break; 810 811 case VAK_Invalid: 812 if (Ty->isObjCObjectType()) 813 DiagRuntimeBehavior( 814 E->getLocStart(), 0, 815 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 816 << Ty << CT); 817 else 818 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 819 << isa<InitListExpr>(E) << Ty << CT; 820 break; 821 } 822 } 823 824 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 825 /// will create a trap if the resulting type is not a POD type. 826 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 827 FunctionDecl *FDecl) { 828 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 829 // Strip the unbridged-cast placeholder expression off, if applicable. 830 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 831 (CT == VariadicMethod || 832 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 833 E = stripARCUnbridgedCast(E); 834 835 // Otherwise, do normal placeholder checking. 836 } else { 837 ExprResult ExprRes = CheckPlaceholderExpr(E); 838 if (ExprRes.isInvalid()) 839 return ExprError(); 840 E = ExprRes.take(); 841 } 842 } 843 844 ExprResult ExprRes = DefaultArgumentPromotion(E); 845 if (ExprRes.isInvalid()) 846 return ExprError(); 847 E = ExprRes.take(); 848 849 // Diagnostics regarding non-POD argument types are 850 // emitted along with format string checking in Sema::CheckFunctionCall(). 851 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 852 // Turn this into a trap. 853 CXXScopeSpec SS; 854 SourceLocation TemplateKWLoc; 855 UnqualifiedId Name; 856 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 857 E->getLocStart()); 858 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 859 Name, true, false); 860 if (TrapFn.isInvalid()) 861 return ExprError(); 862 863 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 864 E->getLocStart(), None, 865 E->getLocEnd()); 866 if (Call.isInvalid()) 867 return ExprError(); 868 869 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 870 Call.get(), E); 871 if (Comma.isInvalid()) 872 return ExprError(); 873 return Comma.get(); 874 } 875 876 if (!getLangOpts().CPlusPlus && 877 RequireCompleteType(E->getExprLoc(), E->getType(), 878 diag::err_call_incomplete_argument)) 879 return ExprError(); 880 881 return Owned(E); 882 } 883 884 /// \brief Converts an integer to complex float type. Helper function of 885 /// UsualArithmeticConversions() 886 /// 887 /// \return false if the integer expression is an integer type and is 888 /// successfully converted to the complex type. 889 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 890 ExprResult &ComplexExpr, 891 QualType IntTy, 892 QualType ComplexTy, 893 bool SkipCast) { 894 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 895 if (SkipCast) return false; 896 if (IntTy->isIntegerType()) { 897 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 898 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 899 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 900 CK_FloatingRealToComplex); 901 } else { 902 assert(IntTy->isComplexIntegerType()); 903 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 904 CK_IntegralComplexToFloatingComplex); 905 } 906 return false; 907 } 908 909 /// \brief Takes two complex float types and converts them to the same type. 910 /// Helper function of UsualArithmeticConversions() 911 static QualType 912 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 913 ExprResult &RHS, QualType LHSType, 914 QualType RHSType, 915 bool IsCompAssign) { 916 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 917 918 if (order < 0) { 919 // _Complex float -> _Complex double 920 if (!IsCompAssign) 921 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 922 return RHSType; 923 } 924 if (order > 0) 925 // _Complex float -> _Complex double 926 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 927 return LHSType; 928 } 929 930 /// \brief Converts otherExpr to complex float and promotes complexExpr if 931 /// necessary. Helper function of UsualArithmeticConversions() 932 static QualType handleOtherComplexFloatConversion(Sema &S, 933 ExprResult &ComplexExpr, 934 ExprResult &OtherExpr, 935 QualType ComplexTy, 936 QualType OtherTy, 937 bool ConvertComplexExpr, 938 bool ConvertOtherExpr) { 939 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 940 941 // If just the complexExpr is complex, the otherExpr needs to be converted, 942 // and the complexExpr might need to be promoted. 943 if (order > 0) { // complexExpr is wider 944 // float -> _Complex double 945 if (ConvertOtherExpr) { 946 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 947 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 948 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 949 CK_FloatingRealToComplex); 950 } 951 return ComplexTy; 952 } 953 954 // otherTy is at least as wide. Find its corresponding complex type. 955 QualType result = (order == 0 ? ComplexTy : 956 S.Context.getComplexType(OtherTy)); 957 958 // double -> _Complex double 959 if (ConvertOtherExpr) 960 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 961 CK_FloatingRealToComplex); 962 963 // _Complex float -> _Complex double 964 if (ConvertComplexExpr && order < 0) 965 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 966 CK_FloatingComplexCast); 967 968 return result; 969 } 970 971 /// \brief Handle arithmetic conversion with complex types. Helper function of 972 /// UsualArithmeticConversions() 973 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 974 ExprResult &RHS, QualType LHSType, 975 QualType RHSType, 976 bool IsCompAssign) { 977 // if we have an integer operand, the result is the complex type. 978 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 979 /*skipCast*/false)) 980 return LHSType; 981 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 982 /*skipCast*/IsCompAssign)) 983 return RHSType; 984 985 // This handles complex/complex, complex/float, or float/complex. 986 // When both operands are complex, the shorter operand is converted to the 987 // type of the longer, and that is the type of the result. This corresponds 988 // to what is done when combining two real floating-point operands. 989 // The fun begins when size promotion occur across type domains. 990 // From H&S 6.3.4: When one operand is complex and the other is a real 991 // floating-point type, the less precise type is converted, within it's 992 // real or complex domain, to the precision of the other type. For example, 993 // when combining a "long double" with a "double _Complex", the 994 // "double _Complex" is promoted to "long double _Complex". 995 996 bool LHSComplexFloat = LHSType->isComplexType(); 997 bool RHSComplexFloat = RHSType->isComplexType(); 998 999 // If both are complex, just cast to the more precise type. 1000 if (LHSComplexFloat && RHSComplexFloat) 1001 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1002 LHSType, RHSType, 1003 IsCompAssign); 1004 1005 // If only one operand is complex, promote it if necessary and convert the 1006 // other operand to complex. 1007 if (LHSComplexFloat) 1008 return handleOtherComplexFloatConversion( 1009 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1010 /*convertOtherExpr*/ true); 1011 1012 assert(RHSComplexFloat); 1013 return handleOtherComplexFloatConversion( 1014 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1015 /*convertOtherExpr*/ !IsCompAssign); 1016 } 1017 1018 /// \brief Hande arithmetic conversion from integer to float. Helper function 1019 /// of UsualArithmeticConversions() 1020 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1021 ExprResult &IntExpr, 1022 QualType FloatTy, QualType IntTy, 1023 bool ConvertFloat, bool ConvertInt) { 1024 if (IntTy->isIntegerType()) { 1025 if (ConvertInt) 1026 // Convert intExpr to the lhs floating point type. 1027 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1028 CK_IntegralToFloating); 1029 return FloatTy; 1030 } 1031 1032 // Convert both sides to the appropriate complex float. 1033 assert(IntTy->isComplexIntegerType()); 1034 QualType result = S.Context.getComplexType(FloatTy); 1035 1036 // _Complex int -> _Complex float 1037 if (ConvertInt) 1038 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1039 CK_IntegralComplexToFloatingComplex); 1040 1041 // float -> _Complex float 1042 if (ConvertFloat) 1043 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1044 CK_FloatingRealToComplex); 1045 1046 return result; 1047 } 1048 1049 /// \brief Handle arithmethic conversion with floating point types. Helper 1050 /// function of UsualArithmeticConversions() 1051 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1052 ExprResult &RHS, QualType LHSType, 1053 QualType RHSType, bool IsCompAssign) { 1054 bool LHSFloat = LHSType->isRealFloatingType(); 1055 bool RHSFloat = RHSType->isRealFloatingType(); 1056 1057 // If we have two real floating types, convert the smaller operand 1058 // to the bigger result. 1059 if (LHSFloat && RHSFloat) { 1060 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1061 if (order > 0) { 1062 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1063 return LHSType; 1064 } 1065 1066 assert(order < 0 && "illegal float comparison"); 1067 if (!IsCompAssign) 1068 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1069 return RHSType; 1070 } 1071 1072 if (LHSFloat) 1073 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1074 /*convertFloat=*/!IsCompAssign, 1075 /*convertInt=*/ true); 1076 assert(RHSFloat); 1077 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1078 /*convertInt=*/ true, 1079 /*convertFloat=*/!IsCompAssign); 1080 } 1081 1082 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1083 1084 namespace { 1085 /// These helper callbacks are placed in an anonymous namespace to 1086 /// permit their use as function template parameters. 1087 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1088 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1089 } 1090 1091 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1092 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1093 CK_IntegralComplexCast); 1094 } 1095 } 1096 1097 /// \brief Handle integer arithmetic conversions. Helper function of 1098 /// UsualArithmeticConversions() 1099 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1100 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1101 ExprResult &RHS, QualType LHSType, 1102 QualType RHSType, bool IsCompAssign) { 1103 // The rules for this case are in C99 6.3.1.8 1104 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1105 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1106 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1107 if (LHSSigned == RHSSigned) { 1108 // Same signedness; use the higher-ranked type 1109 if (order >= 0) { 1110 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1111 return LHSType; 1112 } else if (!IsCompAssign) 1113 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1114 return RHSType; 1115 } else if (order != (LHSSigned ? 1 : -1)) { 1116 // The unsigned type has greater than or equal rank to the 1117 // signed type, so use the unsigned type 1118 if (RHSSigned) { 1119 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1120 return LHSType; 1121 } else if (!IsCompAssign) 1122 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1123 return RHSType; 1124 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1125 // The two types are different widths; if we are here, that 1126 // means the signed type is larger than the unsigned type, so 1127 // use the signed type. 1128 if (LHSSigned) { 1129 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1130 return LHSType; 1131 } else if (!IsCompAssign) 1132 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1133 return RHSType; 1134 } else { 1135 // The signed type is higher-ranked than the unsigned type, 1136 // but isn't actually any bigger (like unsigned int and long 1137 // on most 32-bit systems). Use the unsigned type corresponding 1138 // to the signed type. 1139 QualType result = 1140 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1141 RHS = (*doRHSCast)(S, RHS.take(), result); 1142 if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.take(), result); 1144 return result; 1145 } 1146 } 1147 1148 /// \brief Handle conversions with GCC complex int extension. Helper function 1149 /// of UsualArithmeticConversions() 1150 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1151 ExprResult &RHS, QualType LHSType, 1152 QualType RHSType, 1153 bool IsCompAssign) { 1154 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1155 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1156 1157 if (LHSComplexInt && RHSComplexInt) { 1158 QualType LHSEltType = LHSComplexInt->getElementType(); 1159 QualType RHSEltType = RHSComplexInt->getElementType(); 1160 QualType ScalarType = 1161 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1162 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1163 1164 return S.Context.getComplexType(ScalarType); 1165 } 1166 1167 if (LHSComplexInt) { 1168 QualType LHSEltType = LHSComplexInt->getElementType(); 1169 QualType ScalarType = 1170 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1171 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1172 QualType ComplexType = S.Context.getComplexType(ScalarType); 1173 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1174 CK_IntegralRealToComplex); 1175 1176 return ComplexType; 1177 } 1178 1179 assert(RHSComplexInt); 1180 1181 QualType RHSEltType = RHSComplexInt->getElementType(); 1182 QualType ScalarType = 1183 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1184 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1185 QualType ComplexType = S.Context.getComplexType(ScalarType); 1186 1187 if (!IsCompAssign) 1188 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1189 CK_IntegralRealToComplex); 1190 return ComplexType; 1191 } 1192 1193 /// UsualArithmeticConversions - Performs various conversions that are common to 1194 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1195 /// routine returns the first non-arithmetic type found. The client is 1196 /// responsible for emitting appropriate error diagnostics. 1197 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1198 bool IsCompAssign) { 1199 if (!IsCompAssign) { 1200 LHS = UsualUnaryConversions(LHS.take()); 1201 if (LHS.isInvalid()) 1202 return QualType(); 1203 } 1204 1205 RHS = UsualUnaryConversions(RHS.take()); 1206 if (RHS.isInvalid()) 1207 return QualType(); 1208 1209 // For conversion purposes, we ignore any qualifiers. 1210 // For example, "const float" and "float" are equivalent. 1211 QualType LHSType = 1212 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1213 QualType RHSType = 1214 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1215 1216 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1217 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1218 LHSType = AtomicLHS->getValueType(); 1219 1220 // If both types are identical, no conversion is needed. 1221 if (LHSType == RHSType) 1222 return LHSType; 1223 1224 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1225 // The caller can deal with this (e.g. pointer + int). 1226 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1227 return QualType(); 1228 1229 // Apply unary and bitfield promotions to the LHS's type. 1230 QualType LHSUnpromotedType = LHSType; 1231 if (LHSType->isPromotableIntegerType()) 1232 LHSType = Context.getPromotedIntegerType(LHSType); 1233 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1234 if (!LHSBitfieldPromoteTy.isNull()) 1235 LHSType = LHSBitfieldPromoteTy; 1236 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1237 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1238 1239 // If both types are identical, no conversion is needed. 1240 if (LHSType == RHSType) 1241 return LHSType; 1242 1243 // At this point, we have two different arithmetic types. 1244 1245 // Handle complex types first (C99 6.3.1.8p1). 1246 if (LHSType->isComplexType() || RHSType->isComplexType()) 1247 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1248 IsCompAssign); 1249 1250 // Now handle "real" floating types (i.e. float, double, long double). 1251 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1252 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1253 IsCompAssign); 1254 1255 // Handle GCC complex int extension. 1256 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1257 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1258 IsCompAssign); 1259 1260 // Finally, we have two differing integer types. 1261 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1262 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1263 } 1264 1265 1266 //===----------------------------------------------------------------------===// 1267 // Semantic Analysis for various Expression Types 1268 //===----------------------------------------------------------------------===// 1269 1270 1271 ExprResult 1272 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1273 SourceLocation DefaultLoc, 1274 SourceLocation RParenLoc, 1275 Expr *ControllingExpr, 1276 ArrayRef<ParsedType> ArgTypes, 1277 ArrayRef<Expr *> ArgExprs) { 1278 unsigned NumAssocs = ArgTypes.size(); 1279 assert(NumAssocs == ArgExprs.size()); 1280 1281 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1282 for (unsigned i = 0; i < NumAssocs; ++i) { 1283 if (ArgTypes[i]) 1284 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1285 else 1286 Types[i] = 0; 1287 } 1288 1289 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1290 ControllingExpr, 1291 llvm::makeArrayRef(Types, NumAssocs), 1292 ArgExprs); 1293 delete [] Types; 1294 return ER; 1295 } 1296 1297 ExprResult 1298 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1299 SourceLocation DefaultLoc, 1300 SourceLocation RParenLoc, 1301 Expr *ControllingExpr, 1302 ArrayRef<TypeSourceInfo *> Types, 1303 ArrayRef<Expr *> Exprs) { 1304 unsigned NumAssocs = Types.size(); 1305 assert(NumAssocs == Exprs.size()); 1306 if (ControllingExpr->getType()->isPlaceholderType()) { 1307 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1308 if (result.isInvalid()) return ExprError(); 1309 ControllingExpr = result.take(); 1310 } 1311 1312 bool TypeErrorFound = false, 1313 IsResultDependent = ControllingExpr->isTypeDependent(), 1314 ContainsUnexpandedParameterPack 1315 = ControllingExpr->containsUnexpandedParameterPack(); 1316 1317 for (unsigned i = 0; i < NumAssocs; ++i) { 1318 if (Exprs[i]->containsUnexpandedParameterPack()) 1319 ContainsUnexpandedParameterPack = true; 1320 1321 if (Types[i]) { 1322 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1323 ContainsUnexpandedParameterPack = true; 1324 1325 if (Types[i]->getType()->isDependentType()) { 1326 IsResultDependent = true; 1327 } else { 1328 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1329 // complete object type other than a variably modified type." 1330 unsigned D = 0; 1331 if (Types[i]->getType()->isIncompleteType()) 1332 D = diag::err_assoc_type_incomplete; 1333 else if (!Types[i]->getType()->isObjectType()) 1334 D = diag::err_assoc_type_nonobject; 1335 else if (Types[i]->getType()->isVariablyModifiedType()) 1336 D = diag::err_assoc_type_variably_modified; 1337 1338 if (D != 0) { 1339 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1340 << Types[i]->getTypeLoc().getSourceRange() 1341 << Types[i]->getType(); 1342 TypeErrorFound = true; 1343 } 1344 1345 // C11 6.5.1.1p2 "No two generic associations in the same generic 1346 // selection shall specify compatible types." 1347 for (unsigned j = i+1; j < NumAssocs; ++j) 1348 if (Types[j] && !Types[j]->getType()->isDependentType() && 1349 Context.typesAreCompatible(Types[i]->getType(), 1350 Types[j]->getType())) { 1351 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1352 diag::err_assoc_compatible_types) 1353 << Types[j]->getTypeLoc().getSourceRange() 1354 << Types[j]->getType() 1355 << Types[i]->getType(); 1356 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1357 diag::note_compat_assoc) 1358 << Types[i]->getTypeLoc().getSourceRange() 1359 << Types[i]->getType(); 1360 TypeErrorFound = true; 1361 } 1362 } 1363 } 1364 } 1365 if (TypeErrorFound) 1366 return ExprError(); 1367 1368 // If we determined that the generic selection is result-dependent, don't 1369 // try to compute the result expression. 1370 if (IsResultDependent) 1371 return Owned(new (Context) GenericSelectionExpr( 1372 Context, KeyLoc, ControllingExpr, 1373 Types, Exprs, 1374 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1375 1376 SmallVector<unsigned, 1> CompatIndices; 1377 unsigned DefaultIndex = -1U; 1378 for (unsigned i = 0; i < NumAssocs; ++i) { 1379 if (!Types[i]) 1380 DefaultIndex = i; 1381 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1382 Types[i]->getType())) 1383 CompatIndices.push_back(i); 1384 } 1385 1386 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1387 // type compatible with at most one of the types named in its generic 1388 // association list." 1389 if (CompatIndices.size() > 1) { 1390 // We strip parens here because the controlling expression is typically 1391 // parenthesized in macro definitions. 1392 ControllingExpr = ControllingExpr->IgnoreParens(); 1393 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1394 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1395 << (unsigned) CompatIndices.size(); 1396 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1397 E = CompatIndices.end(); I != E; ++I) { 1398 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1399 diag::note_compat_assoc) 1400 << Types[*I]->getTypeLoc().getSourceRange() 1401 << Types[*I]->getType(); 1402 } 1403 return ExprError(); 1404 } 1405 1406 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1407 // its controlling expression shall have type compatible with exactly one of 1408 // the types named in its generic association list." 1409 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1410 // We strip parens here because the controlling expression is typically 1411 // parenthesized in macro definitions. 1412 ControllingExpr = ControllingExpr->IgnoreParens(); 1413 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1414 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1415 return ExprError(); 1416 } 1417 1418 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1419 // type name that is compatible with the type of the controlling expression, 1420 // then the result expression of the generic selection is the expression 1421 // in that generic association. Otherwise, the result expression of the 1422 // generic selection is the expression in the default generic association." 1423 unsigned ResultIndex = 1424 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1425 1426 return Owned(new (Context) GenericSelectionExpr( 1427 Context, KeyLoc, ControllingExpr, 1428 Types, Exprs, 1429 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1430 ResultIndex)); 1431 } 1432 1433 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1434 /// location of the token and the offset of the ud-suffix within it. 1435 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1436 unsigned Offset) { 1437 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1438 S.getLangOpts()); 1439 } 1440 1441 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1442 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1443 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1444 IdentifierInfo *UDSuffix, 1445 SourceLocation UDSuffixLoc, 1446 ArrayRef<Expr*> Args, 1447 SourceLocation LitEndLoc) { 1448 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1449 1450 QualType ArgTy[2]; 1451 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1452 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1453 if (ArgTy[ArgIdx]->isArrayType()) 1454 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1455 } 1456 1457 DeclarationName OpName = 1458 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1459 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1460 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1461 1462 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1463 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1464 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1465 return ExprError(); 1466 1467 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1468 } 1469 1470 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1471 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1472 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1473 /// multiple tokens. However, the common case is that StringToks points to one 1474 /// string. 1475 /// 1476 ExprResult 1477 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1478 Scope *UDLScope) { 1479 assert(NumStringToks && "Must have at least one string!"); 1480 1481 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1482 if (Literal.hadError) 1483 return ExprError(); 1484 1485 SmallVector<SourceLocation, 4> StringTokLocs; 1486 for (unsigned i = 0; i != NumStringToks; ++i) 1487 StringTokLocs.push_back(StringToks[i].getLocation()); 1488 1489 QualType StrTy = Context.CharTy; 1490 if (Literal.isWide()) 1491 StrTy = Context.getWideCharType(); 1492 else if (Literal.isUTF16()) 1493 StrTy = Context.Char16Ty; 1494 else if (Literal.isUTF32()) 1495 StrTy = Context.Char32Ty; 1496 else if (Literal.isPascal()) 1497 StrTy = Context.UnsignedCharTy; 1498 1499 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1500 if (Literal.isWide()) 1501 Kind = StringLiteral::Wide; 1502 else if (Literal.isUTF8()) 1503 Kind = StringLiteral::UTF8; 1504 else if (Literal.isUTF16()) 1505 Kind = StringLiteral::UTF16; 1506 else if (Literal.isUTF32()) 1507 Kind = StringLiteral::UTF32; 1508 1509 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1510 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1511 StrTy.addConst(); 1512 1513 // Get an array type for the string, according to C99 6.4.5. This includes 1514 // the nul terminator character as well as the string length for pascal 1515 // strings. 1516 StrTy = Context.getConstantArrayType(StrTy, 1517 llvm::APInt(32, Literal.GetNumStringChars()+1), 1518 ArrayType::Normal, 0); 1519 1520 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1521 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1522 Kind, Literal.Pascal, StrTy, 1523 &StringTokLocs[0], 1524 StringTokLocs.size()); 1525 if (Literal.getUDSuffix().empty()) 1526 return Owned(Lit); 1527 1528 // We're building a user-defined literal. 1529 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1530 SourceLocation UDSuffixLoc = 1531 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1532 Literal.getUDSuffixOffset()); 1533 1534 // Make sure we're allowed user-defined literals here. 1535 if (!UDLScope) 1536 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1537 1538 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1539 // operator "" X (str, len) 1540 QualType SizeType = Context.getSizeType(); 1541 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1542 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1543 StringTokLocs[0]); 1544 Expr *Args[] = { Lit, LenArg }; 1545 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1546 Args, StringTokLocs.back()); 1547 } 1548 1549 ExprResult 1550 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1551 SourceLocation Loc, 1552 const CXXScopeSpec *SS) { 1553 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1554 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1555 } 1556 1557 /// BuildDeclRefExpr - Build an expression that references a 1558 /// declaration that does not require a closure capture. 1559 ExprResult 1560 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1561 const DeclarationNameInfo &NameInfo, 1562 const CXXScopeSpec *SS, NamedDecl *FoundD, 1563 const TemplateArgumentListInfo *TemplateArgs) { 1564 if (getLangOpts().CUDA) 1565 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1566 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1567 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1568 CalleeTarget = IdentifyCUDATarget(Callee); 1569 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1570 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1571 << CalleeTarget << D->getIdentifier() << CallerTarget; 1572 Diag(D->getLocation(), diag::note_previous_decl) 1573 << D->getIdentifier(); 1574 return ExprError(); 1575 } 1576 } 1577 1578 bool refersToEnclosingScope = 1579 (CurContext != D->getDeclContext() && 1580 D->getDeclContext()->isFunctionOrMethod()); 1581 1582 DeclRefExpr *E; 1583 if (isa<VarTemplateSpecializationDecl>(D)) { 1584 VarTemplateSpecializationDecl *VarSpec = 1585 cast<VarTemplateSpecializationDecl>(D); 1586 1587 E = DeclRefExpr::Create( 1588 Context, 1589 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1590 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1591 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1592 } else { 1593 assert(!TemplateArgs && "No template arguments for non-variable" 1594 " template specialization referrences"); 1595 E = DeclRefExpr::Create( 1596 Context, 1597 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1598 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1599 } 1600 1601 MarkDeclRefReferenced(E); 1602 1603 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1604 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1605 DiagnosticsEngine::Level Level = 1606 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1607 E->getLocStart()); 1608 if (Level != DiagnosticsEngine::Ignored) 1609 recordUseOfEvaluatedWeak(E); 1610 } 1611 1612 // Just in case we're building an illegal pointer-to-member. 1613 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1614 if (FD && FD->isBitField()) 1615 E->setObjectKind(OK_BitField); 1616 1617 return Owned(E); 1618 } 1619 1620 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1621 /// possibly a list of template arguments. 1622 /// 1623 /// If this produces template arguments, it is permitted to call 1624 /// DecomposeTemplateName. 1625 /// 1626 /// This actually loses a lot of source location information for 1627 /// non-standard name kinds; we should consider preserving that in 1628 /// some way. 1629 void 1630 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1631 TemplateArgumentListInfo &Buffer, 1632 DeclarationNameInfo &NameInfo, 1633 const TemplateArgumentListInfo *&TemplateArgs) { 1634 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1635 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1636 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1637 1638 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1639 Id.TemplateId->NumArgs); 1640 translateTemplateArguments(TemplateArgsPtr, Buffer); 1641 1642 TemplateName TName = Id.TemplateId->Template.get(); 1643 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1644 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1645 TemplateArgs = &Buffer; 1646 } else { 1647 NameInfo = GetNameFromUnqualifiedId(Id); 1648 TemplateArgs = 0; 1649 } 1650 } 1651 1652 /// Diagnose an empty lookup. 1653 /// 1654 /// \return false if new lookup candidates were found 1655 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1656 CorrectionCandidateCallback &CCC, 1657 TemplateArgumentListInfo *ExplicitTemplateArgs, 1658 ArrayRef<Expr *> Args) { 1659 DeclarationName Name = R.getLookupName(); 1660 1661 unsigned diagnostic = diag::err_undeclared_var_use; 1662 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1663 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1664 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1665 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1666 diagnostic = diag::err_undeclared_use; 1667 diagnostic_suggest = diag::err_undeclared_use_suggest; 1668 } 1669 1670 // If the original lookup was an unqualified lookup, fake an 1671 // unqualified lookup. This is useful when (for example) the 1672 // original lookup would not have found something because it was a 1673 // dependent name. 1674 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1675 ? CurContext : 0; 1676 while (DC) { 1677 if (isa<CXXRecordDecl>(DC)) { 1678 LookupQualifiedName(R, DC); 1679 1680 if (!R.empty()) { 1681 // Don't give errors about ambiguities in this lookup. 1682 R.suppressDiagnostics(); 1683 1684 // During a default argument instantiation the CurContext points 1685 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1686 // function parameter list, hence add an explicit check. 1687 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1688 ActiveTemplateInstantiations.back().Kind == 1689 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1690 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1691 bool isInstance = CurMethod && 1692 CurMethod->isInstance() && 1693 DC == CurMethod->getParent() && !isDefaultArgument; 1694 1695 1696 // Give a code modification hint to insert 'this->'. 1697 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1698 // Actually quite difficult! 1699 if (getLangOpts().MicrosoftMode) 1700 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1701 if (isInstance) { 1702 Diag(R.getNameLoc(), diagnostic) << Name 1703 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1704 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1705 CallsUndergoingInstantiation.back()->getCallee()); 1706 1707 CXXMethodDecl *DepMethod; 1708 if (CurMethod->isDependentContext()) 1709 DepMethod = CurMethod; 1710 else if (CurMethod->getTemplatedKind() == 1711 FunctionDecl::TK_FunctionTemplateSpecialization) 1712 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1713 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1714 else 1715 DepMethod = cast<CXXMethodDecl>( 1716 CurMethod->getInstantiatedFromMemberFunction()); 1717 assert(DepMethod && "No template pattern found"); 1718 1719 QualType DepThisType = DepMethod->getThisType(Context); 1720 CheckCXXThisCapture(R.getNameLoc()); 1721 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1722 R.getNameLoc(), DepThisType, false); 1723 TemplateArgumentListInfo TList; 1724 if (ULE->hasExplicitTemplateArgs()) 1725 ULE->copyTemplateArgumentsInto(TList); 1726 1727 CXXScopeSpec SS; 1728 SS.Adopt(ULE->getQualifierLoc()); 1729 CXXDependentScopeMemberExpr *DepExpr = 1730 CXXDependentScopeMemberExpr::Create( 1731 Context, DepThis, DepThisType, true, SourceLocation(), 1732 SS.getWithLocInContext(Context), 1733 ULE->getTemplateKeywordLoc(), 0, 1734 R.getLookupNameInfo(), 1735 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1736 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1737 } else { 1738 Diag(R.getNameLoc(), diagnostic) << Name; 1739 } 1740 1741 // Do we really want to note all of these? 1742 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1743 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1744 1745 // Return true if we are inside a default argument instantiation 1746 // and the found name refers to an instance member function, otherwise 1747 // the function calling DiagnoseEmptyLookup will try to create an 1748 // implicit member call and this is wrong for default argument. 1749 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1750 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1751 return true; 1752 } 1753 1754 // Tell the callee to try to recover. 1755 return false; 1756 } 1757 1758 R.clear(); 1759 } 1760 1761 // In Microsoft mode, if we are performing lookup from within a friend 1762 // function definition declared at class scope then we must set 1763 // DC to the lexical parent to be able to search into the parent 1764 // class. 1765 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1766 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1767 DC->getLexicalParent()->isRecord()) 1768 DC = DC->getLexicalParent(); 1769 else 1770 DC = DC->getParent(); 1771 } 1772 1773 // We didn't find anything, so try to correct for a typo. 1774 TypoCorrection Corrected; 1775 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1776 S, &SS, CCC))) { 1777 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1778 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1779 bool droppedSpecifier = 1780 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1781 R.setLookupName(Corrected.getCorrection()); 1782 1783 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1784 if (Corrected.isOverloaded()) { 1785 OverloadCandidateSet OCS(R.getNameLoc()); 1786 OverloadCandidateSet::iterator Best; 1787 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1788 CDEnd = Corrected.end(); 1789 CD != CDEnd; ++CD) { 1790 if (FunctionTemplateDecl *FTD = 1791 dyn_cast<FunctionTemplateDecl>(*CD)) 1792 AddTemplateOverloadCandidate( 1793 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1794 Args, OCS); 1795 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1796 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1797 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1798 Args, OCS); 1799 } 1800 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1801 case OR_Success: 1802 ND = Best->Function; 1803 break; 1804 default: 1805 break; 1806 } 1807 } 1808 R.addDecl(ND); 1809 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1810 if (SS.isEmpty()) 1811 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1812 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1813 else 1814 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1815 << Name << computeDeclContext(SS, false) << droppedSpecifier 1816 << CorrectedQuotedStr << SS.getRange() 1817 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1818 CorrectedStr); 1819 1820 unsigned diag = isa<ImplicitParamDecl>(ND) 1821 ? diag::note_implicit_param_decl 1822 : diag::note_previous_decl; 1823 1824 Diag(ND->getLocation(), diag) 1825 << CorrectedQuotedStr; 1826 1827 // Tell the callee to try to recover. 1828 return false; 1829 } 1830 1831 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1832 // FIXME: If we ended up with a typo for a type name or 1833 // Objective-C class name, we're in trouble because the parser 1834 // is in the wrong place to recover. Suggest the typo 1835 // correction, but don't make it a fix-it since we're not going 1836 // to recover well anyway. 1837 if (SS.isEmpty()) 1838 Diag(R.getNameLoc(), diagnostic_suggest) 1839 << Name << CorrectedQuotedStr; 1840 else 1841 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1842 << Name << computeDeclContext(SS, false) << droppedSpecifier 1843 << CorrectedQuotedStr << SS.getRange(); 1844 1845 // Don't try to recover; it won't work. 1846 return true; 1847 } 1848 } else { 1849 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1850 // because we aren't able to recover. 1851 if (SS.isEmpty()) 1852 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1853 else 1854 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1855 << Name << computeDeclContext(SS, false) << droppedSpecifier 1856 << CorrectedQuotedStr << SS.getRange(); 1857 return true; 1858 } 1859 } 1860 R.clear(); 1861 1862 // Emit a special diagnostic for failed member lookups. 1863 // FIXME: computing the declaration context might fail here (?) 1864 if (!SS.isEmpty()) { 1865 Diag(R.getNameLoc(), diag::err_no_member) 1866 << Name << computeDeclContext(SS, false) 1867 << SS.getRange(); 1868 return true; 1869 } 1870 1871 // Give up, we can't recover. 1872 Diag(R.getNameLoc(), diagnostic) << Name; 1873 return true; 1874 } 1875 1876 ExprResult Sema::ActOnIdExpression(Scope *S, 1877 CXXScopeSpec &SS, 1878 SourceLocation TemplateKWLoc, 1879 UnqualifiedId &Id, 1880 bool HasTrailingLParen, 1881 bool IsAddressOfOperand, 1882 CorrectionCandidateCallback *CCC, 1883 bool IsInlineAsmIdentifier) { 1884 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1885 "cannot be direct & operand and have a trailing lparen"); 1886 if (SS.isInvalid()) 1887 return ExprError(); 1888 1889 TemplateArgumentListInfo TemplateArgsBuffer; 1890 1891 // Decompose the UnqualifiedId into the following data. 1892 DeclarationNameInfo NameInfo; 1893 const TemplateArgumentListInfo *TemplateArgs; 1894 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1895 1896 DeclarationName Name = NameInfo.getName(); 1897 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1898 SourceLocation NameLoc = NameInfo.getLoc(); 1899 1900 // C++ [temp.dep.expr]p3: 1901 // An id-expression is type-dependent if it contains: 1902 // -- an identifier that was declared with a dependent type, 1903 // (note: handled after lookup) 1904 // -- a template-id that is dependent, 1905 // (note: handled in BuildTemplateIdExpr) 1906 // -- a conversion-function-id that specifies a dependent type, 1907 // -- a nested-name-specifier that contains a class-name that 1908 // names a dependent type. 1909 // Determine whether this is a member of an unknown specialization; 1910 // we need to handle these differently. 1911 bool DependentID = false; 1912 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1913 Name.getCXXNameType()->isDependentType()) { 1914 DependentID = true; 1915 } else if (SS.isSet()) { 1916 if (DeclContext *DC = computeDeclContext(SS, false)) { 1917 if (RequireCompleteDeclContext(SS, DC)) 1918 return ExprError(); 1919 } else { 1920 DependentID = true; 1921 } 1922 } 1923 1924 if (DependentID) 1925 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1926 IsAddressOfOperand, TemplateArgs); 1927 1928 // Perform the required lookup. 1929 LookupResult R(*this, NameInfo, 1930 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1931 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1932 if (TemplateArgs) { 1933 // Lookup the template name again to correctly establish the context in 1934 // which it was found. This is really unfortunate as we already did the 1935 // lookup to determine that it was a template name in the first place. If 1936 // this becomes a performance hit, we can work harder to preserve those 1937 // results until we get here but it's likely not worth it. 1938 bool MemberOfUnknownSpecialization; 1939 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1940 MemberOfUnknownSpecialization); 1941 1942 if (MemberOfUnknownSpecialization || 1943 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1944 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1945 IsAddressOfOperand, TemplateArgs); 1946 } else { 1947 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1948 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1949 1950 // If the result might be in a dependent base class, this is a dependent 1951 // id-expression. 1952 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1953 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1954 IsAddressOfOperand, TemplateArgs); 1955 1956 // If this reference is in an Objective-C method, then we need to do 1957 // some special Objective-C lookup, too. 1958 if (IvarLookupFollowUp) { 1959 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1960 if (E.isInvalid()) 1961 return ExprError(); 1962 1963 if (Expr *Ex = E.takeAs<Expr>()) 1964 return Owned(Ex); 1965 } 1966 } 1967 1968 if (R.isAmbiguous()) 1969 return ExprError(); 1970 1971 // Determine whether this name might be a candidate for 1972 // argument-dependent lookup. 1973 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1974 1975 if (R.empty() && !ADL) { 1976 1977 // Otherwise, this could be an implicitly declared function reference (legal 1978 // in C90, extension in C99, forbidden in C++). 1979 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1980 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1981 if (D) R.addDecl(D); 1982 } 1983 1984 // If this name wasn't predeclared and if this is not a function 1985 // call, diagnose the problem. 1986 if (R.empty()) { 1987 // In Microsoft mode, if we are inside a template class member function 1988 // whose parent class has dependent base classes, and we can't resolve 1989 // an identifier, then assume the identifier is type dependent. The 1990 // goal is to postpone name lookup to instantiation time to be able to 1991 // search into the type dependent base classes. 1992 if (getLangOpts().MicrosoftMode) { 1993 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 1994 if (MD && MD->getParent()->hasAnyDependentBases()) 1995 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1996 IsAddressOfOperand, TemplateArgs); 1997 } 1998 1999 // Don't diagnose an empty lookup for inline assmebly. 2000 if (IsInlineAsmIdentifier) 2001 return ExprError(); 2002 2003 CorrectionCandidateCallback DefaultValidator; 2004 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2005 return ExprError(); 2006 2007 assert(!R.empty() && 2008 "DiagnoseEmptyLookup returned false but added no results"); 2009 2010 // If we found an Objective-C instance variable, let 2011 // LookupInObjCMethod build the appropriate expression to 2012 // reference the ivar. 2013 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2014 R.clear(); 2015 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2016 // In a hopelessly buggy code, Objective-C instance variable 2017 // lookup fails and no expression will be built to reference it. 2018 if (!E.isInvalid() && !E.get()) 2019 return ExprError(); 2020 return E; 2021 } 2022 } 2023 } 2024 2025 // This is guaranteed from this point on. 2026 assert(!R.empty() || ADL); 2027 2028 // Check whether this might be a C++ implicit instance member access. 2029 // C++ [class.mfct.non-static]p3: 2030 // When an id-expression that is not part of a class member access 2031 // syntax and not used to form a pointer to member is used in the 2032 // body of a non-static member function of class X, if name lookup 2033 // resolves the name in the id-expression to a non-static non-type 2034 // member of some class C, the id-expression is transformed into a 2035 // class member access expression using (*this) as the 2036 // postfix-expression to the left of the . operator. 2037 // 2038 // But we don't actually need to do this for '&' operands if R 2039 // resolved to a function or overloaded function set, because the 2040 // expression is ill-formed if it actually works out to be a 2041 // non-static member function: 2042 // 2043 // C++ [expr.ref]p4: 2044 // Otherwise, if E1.E2 refers to a non-static member function. . . 2045 // [t]he expression can be used only as the left-hand operand of a 2046 // member function call. 2047 // 2048 // There are other safeguards against such uses, but it's important 2049 // to get this right here so that we don't end up making a 2050 // spuriously dependent expression if we're inside a dependent 2051 // instance method. 2052 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2053 bool MightBeImplicitMember; 2054 if (!IsAddressOfOperand) 2055 MightBeImplicitMember = true; 2056 else if (!SS.isEmpty()) 2057 MightBeImplicitMember = false; 2058 else if (R.isOverloadedResult()) 2059 MightBeImplicitMember = false; 2060 else if (R.isUnresolvableResult()) 2061 MightBeImplicitMember = true; 2062 else 2063 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2064 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2065 isa<MSPropertyDecl>(R.getFoundDecl()); 2066 2067 if (MightBeImplicitMember) 2068 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2069 R, TemplateArgs); 2070 } 2071 2072 if (TemplateArgs || TemplateKWLoc.isValid()) { 2073 2074 // In C++1y, if this is a variable template id, then check it 2075 // in BuildTemplateIdExpr(). 2076 // The single lookup result must be a variable template declaration. 2077 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2078 Id.TemplateId->Kind == TNK_Var_template) { 2079 assert(R.getAsSingle<VarTemplateDecl>() && 2080 "There should only be one declaration found."); 2081 } 2082 2083 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2084 } 2085 2086 return BuildDeclarationNameExpr(SS, R, ADL); 2087 } 2088 2089 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2090 /// declaration name, generally during template instantiation. 2091 /// There's a large number of things which don't need to be done along 2092 /// this path. 2093 ExprResult 2094 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2095 const DeclarationNameInfo &NameInfo, 2096 bool IsAddressOfOperand) { 2097 DeclContext *DC = computeDeclContext(SS, false); 2098 if (!DC) 2099 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2100 NameInfo, /*TemplateArgs=*/0); 2101 2102 if (RequireCompleteDeclContext(SS, DC)) 2103 return ExprError(); 2104 2105 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2106 LookupQualifiedName(R, DC); 2107 2108 if (R.isAmbiguous()) 2109 return ExprError(); 2110 2111 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2112 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2113 NameInfo, /*TemplateArgs=*/0); 2114 2115 if (R.empty()) { 2116 Diag(NameInfo.getLoc(), diag::err_no_member) 2117 << NameInfo.getName() << DC << SS.getRange(); 2118 return ExprError(); 2119 } 2120 2121 // Defend against this resolving to an implicit member access. We usually 2122 // won't get here if this might be a legitimate a class member (we end up in 2123 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2124 // a pointer-to-member or in an unevaluated context in C++11. 2125 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2126 return BuildPossibleImplicitMemberExpr(SS, 2127 /*TemplateKWLoc=*/SourceLocation(), 2128 R, /*TemplateArgs=*/0); 2129 2130 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2131 } 2132 2133 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2134 /// detected that we're currently inside an ObjC method. Perform some 2135 /// additional lookup. 2136 /// 2137 /// Ideally, most of this would be done by lookup, but there's 2138 /// actually quite a lot of extra work involved. 2139 /// 2140 /// Returns a null sentinel to indicate trivial success. 2141 ExprResult 2142 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2143 IdentifierInfo *II, bool AllowBuiltinCreation) { 2144 SourceLocation Loc = Lookup.getNameLoc(); 2145 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2146 2147 // Check for error condition which is already reported. 2148 if (!CurMethod) 2149 return ExprError(); 2150 2151 // There are two cases to handle here. 1) scoped lookup could have failed, 2152 // in which case we should look for an ivar. 2) scoped lookup could have 2153 // found a decl, but that decl is outside the current instance method (i.e. 2154 // a global variable). In these two cases, we do a lookup for an ivar with 2155 // this name, if the lookup sucedes, we replace it our current decl. 2156 2157 // If we're in a class method, we don't normally want to look for 2158 // ivars. But if we don't find anything else, and there's an 2159 // ivar, that's an error. 2160 bool IsClassMethod = CurMethod->isClassMethod(); 2161 2162 bool LookForIvars; 2163 if (Lookup.empty()) 2164 LookForIvars = true; 2165 else if (IsClassMethod) 2166 LookForIvars = false; 2167 else 2168 LookForIvars = (Lookup.isSingleResult() && 2169 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2170 ObjCInterfaceDecl *IFace = 0; 2171 if (LookForIvars) { 2172 IFace = CurMethod->getClassInterface(); 2173 ObjCInterfaceDecl *ClassDeclared; 2174 ObjCIvarDecl *IV = 0; 2175 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2176 // Diagnose using an ivar in a class method. 2177 if (IsClassMethod) 2178 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2179 << IV->getDeclName()); 2180 2181 // If we're referencing an invalid decl, just return this as a silent 2182 // error node. The error diagnostic was already emitted on the decl. 2183 if (IV->isInvalidDecl()) 2184 return ExprError(); 2185 2186 // Check if referencing a field with __attribute__((deprecated)). 2187 if (DiagnoseUseOfDecl(IV, Loc)) 2188 return ExprError(); 2189 2190 // Diagnose the use of an ivar outside of the declaring class. 2191 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2192 !declaresSameEntity(ClassDeclared, IFace) && 2193 !getLangOpts().DebuggerSupport) 2194 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2195 2196 // FIXME: This should use a new expr for a direct reference, don't 2197 // turn this into Self->ivar, just return a BareIVarExpr or something. 2198 IdentifierInfo &II = Context.Idents.get("self"); 2199 UnqualifiedId SelfName; 2200 SelfName.setIdentifier(&II, SourceLocation()); 2201 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2202 CXXScopeSpec SelfScopeSpec; 2203 SourceLocation TemplateKWLoc; 2204 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2205 SelfName, false, false); 2206 if (SelfExpr.isInvalid()) 2207 return ExprError(); 2208 2209 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2210 if (SelfExpr.isInvalid()) 2211 return ExprError(); 2212 2213 MarkAnyDeclReferenced(Loc, IV, true); 2214 2215 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2216 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2217 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2218 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2219 2220 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2221 Loc, IV->getLocation(), 2222 SelfExpr.take(), 2223 true, true); 2224 2225 if (getLangOpts().ObjCAutoRefCount) { 2226 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2227 DiagnosticsEngine::Level Level = 2228 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2229 if (Level != DiagnosticsEngine::Ignored) 2230 recordUseOfEvaluatedWeak(Result); 2231 } 2232 if (CurContext->isClosure()) 2233 Diag(Loc, diag::warn_implicitly_retains_self) 2234 << FixItHint::CreateInsertion(Loc, "self->"); 2235 } 2236 2237 return Owned(Result); 2238 } 2239 } else if (CurMethod->isInstanceMethod()) { 2240 // We should warn if a local variable hides an ivar. 2241 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2242 ObjCInterfaceDecl *ClassDeclared; 2243 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2244 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2245 declaresSameEntity(IFace, ClassDeclared)) 2246 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2247 } 2248 } 2249 } else if (Lookup.isSingleResult() && 2250 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2251 // If accessing a stand-alone ivar in a class method, this is an error. 2252 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2253 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2254 << IV->getDeclName()); 2255 } 2256 2257 if (Lookup.empty() && II && AllowBuiltinCreation) { 2258 // FIXME. Consolidate this with similar code in LookupName. 2259 if (unsigned BuiltinID = II->getBuiltinID()) { 2260 if (!(getLangOpts().CPlusPlus && 2261 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2262 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2263 S, Lookup.isForRedeclaration(), 2264 Lookup.getNameLoc()); 2265 if (D) Lookup.addDecl(D); 2266 } 2267 } 2268 } 2269 // Sentinel value saying that we didn't do anything special. 2270 return Owned((Expr*) 0); 2271 } 2272 2273 /// \brief Cast a base object to a member's actual type. 2274 /// 2275 /// Logically this happens in three phases: 2276 /// 2277 /// * First we cast from the base type to the naming class. 2278 /// The naming class is the class into which we were looking 2279 /// when we found the member; it's the qualifier type if a 2280 /// qualifier was provided, and otherwise it's the base type. 2281 /// 2282 /// * Next we cast from the naming class to the declaring class. 2283 /// If the member we found was brought into a class's scope by 2284 /// a using declaration, this is that class; otherwise it's 2285 /// the class declaring the member. 2286 /// 2287 /// * Finally we cast from the declaring class to the "true" 2288 /// declaring class of the member. This conversion does not 2289 /// obey access control. 2290 ExprResult 2291 Sema::PerformObjectMemberConversion(Expr *From, 2292 NestedNameSpecifier *Qualifier, 2293 NamedDecl *FoundDecl, 2294 NamedDecl *Member) { 2295 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2296 if (!RD) 2297 return Owned(From); 2298 2299 QualType DestRecordType; 2300 QualType DestType; 2301 QualType FromRecordType; 2302 QualType FromType = From->getType(); 2303 bool PointerConversions = false; 2304 if (isa<FieldDecl>(Member)) { 2305 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2306 2307 if (FromType->getAs<PointerType>()) { 2308 DestType = Context.getPointerType(DestRecordType); 2309 FromRecordType = FromType->getPointeeType(); 2310 PointerConversions = true; 2311 } else { 2312 DestType = DestRecordType; 2313 FromRecordType = FromType; 2314 } 2315 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2316 if (Method->isStatic()) 2317 return Owned(From); 2318 2319 DestType = Method->getThisType(Context); 2320 DestRecordType = DestType->getPointeeType(); 2321 2322 if (FromType->getAs<PointerType>()) { 2323 FromRecordType = FromType->getPointeeType(); 2324 PointerConversions = true; 2325 } else { 2326 FromRecordType = FromType; 2327 DestType = DestRecordType; 2328 } 2329 } else { 2330 // No conversion necessary. 2331 return Owned(From); 2332 } 2333 2334 if (DestType->isDependentType() || FromType->isDependentType()) 2335 return Owned(From); 2336 2337 // If the unqualified types are the same, no conversion is necessary. 2338 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2339 return Owned(From); 2340 2341 SourceRange FromRange = From->getSourceRange(); 2342 SourceLocation FromLoc = FromRange.getBegin(); 2343 2344 ExprValueKind VK = From->getValueKind(); 2345 2346 // C++ [class.member.lookup]p8: 2347 // [...] Ambiguities can often be resolved by qualifying a name with its 2348 // class name. 2349 // 2350 // If the member was a qualified name and the qualified referred to a 2351 // specific base subobject type, we'll cast to that intermediate type 2352 // first and then to the object in which the member is declared. That allows 2353 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2354 // 2355 // class Base { public: int x; }; 2356 // class Derived1 : public Base { }; 2357 // class Derived2 : public Base { }; 2358 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2359 // 2360 // void VeryDerived::f() { 2361 // x = 17; // error: ambiguous base subobjects 2362 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2363 // } 2364 if (Qualifier && Qualifier->getAsType()) { 2365 QualType QType = QualType(Qualifier->getAsType(), 0); 2366 assert(QType->isRecordType() && "lookup done with non-record type"); 2367 2368 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2369 2370 // In C++98, the qualifier type doesn't actually have to be a base 2371 // type of the object type, in which case we just ignore it. 2372 // Otherwise build the appropriate casts. 2373 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2374 CXXCastPath BasePath; 2375 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2376 FromLoc, FromRange, &BasePath)) 2377 return ExprError(); 2378 2379 if (PointerConversions) 2380 QType = Context.getPointerType(QType); 2381 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2382 VK, &BasePath).take(); 2383 2384 FromType = QType; 2385 FromRecordType = QRecordType; 2386 2387 // If the qualifier type was the same as the destination type, 2388 // we're done. 2389 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2390 return Owned(From); 2391 } 2392 } 2393 2394 bool IgnoreAccess = false; 2395 2396 // If we actually found the member through a using declaration, cast 2397 // down to the using declaration's type. 2398 // 2399 // Pointer equality is fine here because only one declaration of a 2400 // class ever has member declarations. 2401 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2402 assert(isa<UsingShadowDecl>(FoundDecl)); 2403 QualType URecordType = Context.getTypeDeclType( 2404 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2405 2406 // We only need to do this if the naming-class to declaring-class 2407 // conversion is non-trivial. 2408 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2409 assert(IsDerivedFrom(FromRecordType, URecordType)); 2410 CXXCastPath BasePath; 2411 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2412 FromLoc, FromRange, &BasePath)) 2413 return ExprError(); 2414 2415 QualType UType = URecordType; 2416 if (PointerConversions) 2417 UType = Context.getPointerType(UType); 2418 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2419 VK, &BasePath).take(); 2420 FromType = UType; 2421 FromRecordType = URecordType; 2422 } 2423 2424 // We don't do access control for the conversion from the 2425 // declaring class to the true declaring class. 2426 IgnoreAccess = true; 2427 } 2428 2429 CXXCastPath BasePath; 2430 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2431 FromLoc, FromRange, &BasePath, 2432 IgnoreAccess)) 2433 return ExprError(); 2434 2435 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2436 VK, &BasePath); 2437 } 2438 2439 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2440 const LookupResult &R, 2441 bool HasTrailingLParen) { 2442 // Only when used directly as the postfix-expression of a call. 2443 if (!HasTrailingLParen) 2444 return false; 2445 2446 // Never if a scope specifier was provided. 2447 if (SS.isSet()) 2448 return false; 2449 2450 // Only in C++ or ObjC++. 2451 if (!getLangOpts().CPlusPlus) 2452 return false; 2453 2454 // Turn off ADL when we find certain kinds of declarations during 2455 // normal lookup: 2456 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2457 NamedDecl *D = *I; 2458 2459 // C++0x [basic.lookup.argdep]p3: 2460 // -- a declaration of a class member 2461 // Since using decls preserve this property, we check this on the 2462 // original decl. 2463 if (D->isCXXClassMember()) 2464 return false; 2465 2466 // C++0x [basic.lookup.argdep]p3: 2467 // -- a block-scope function declaration that is not a 2468 // using-declaration 2469 // NOTE: we also trigger this for function templates (in fact, we 2470 // don't check the decl type at all, since all other decl types 2471 // turn off ADL anyway). 2472 if (isa<UsingShadowDecl>(D)) 2473 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2474 else if (D->getDeclContext()->isFunctionOrMethod()) 2475 return false; 2476 2477 // C++0x [basic.lookup.argdep]p3: 2478 // -- a declaration that is neither a function or a function 2479 // template 2480 // And also for builtin functions. 2481 if (isa<FunctionDecl>(D)) { 2482 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2483 2484 // But also builtin functions. 2485 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2486 return false; 2487 } else if (!isa<FunctionTemplateDecl>(D)) 2488 return false; 2489 } 2490 2491 return true; 2492 } 2493 2494 2495 /// Diagnoses obvious problems with the use of the given declaration 2496 /// as an expression. This is only actually called for lookups that 2497 /// were not overloaded, and it doesn't promise that the declaration 2498 /// will in fact be used. 2499 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2500 if (isa<TypedefNameDecl>(D)) { 2501 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2502 return true; 2503 } 2504 2505 if (isa<ObjCInterfaceDecl>(D)) { 2506 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2507 return true; 2508 } 2509 2510 if (isa<NamespaceDecl>(D)) { 2511 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2512 return true; 2513 } 2514 2515 return false; 2516 } 2517 2518 ExprResult 2519 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2520 LookupResult &R, 2521 bool NeedsADL) { 2522 // If this is a single, fully-resolved result and we don't need ADL, 2523 // just build an ordinary singleton decl ref. 2524 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2525 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2526 R.getRepresentativeDecl()); 2527 2528 // We only need to check the declaration if there's exactly one 2529 // result, because in the overloaded case the results can only be 2530 // functions and function templates. 2531 if (R.isSingleResult() && 2532 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2533 return ExprError(); 2534 2535 // Otherwise, just build an unresolved lookup expression. Suppress 2536 // any lookup-related diagnostics; we'll hash these out later, when 2537 // we've picked a target. 2538 R.suppressDiagnostics(); 2539 2540 UnresolvedLookupExpr *ULE 2541 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2542 SS.getWithLocInContext(Context), 2543 R.getLookupNameInfo(), 2544 NeedsADL, R.isOverloadedResult(), 2545 R.begin(), R.end()); 2546 2547 return Owned(ULE); 2548 } 2549 2550 /// \brief Complete semantic analysis for a reference to the given declaration. 2551 ExprResult Sema::BuildDeclarationNameExpr( 2552 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2553 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2554 assert(D && "Cannot refer to a NULL declaration"); 2555 assert(!isa<FunctionTemplateDecl>(D) && 2556 "Cannot refer unambiguously to a function template"); 2557 2558 SourceLocation Loc = NameInfo.getLoc(); 2559 if (CheckDeclInExpr(*this, Loc, D)) 2560 return ExprError(); 2561 2562 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2563 // Specifically diagnose references to class templates that are missing 2564 // a template argument list. 2565 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2566 << Template << SS.getRange(); 2567 Diag(Template->getLocation(), diag::note_template_decl_here); 2568 return ExprError(); 2569 } 2570 2571 // Make sure that we're referring to a value. 2572 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2573 if (!VD) { 2574 Diag(Loc, diag::err_ref_non_value) 2575 << D << SS.getRange(); 2576 Diag(D->getLocation(), diag::note_declared_at); 2577 return ExprError(); 2578 } 2579 2580 // Check whether this declaration can be used. Note that we suppress 2581 // this check when we're going to perform argument-dependent lookup 2582 // on this function name, because this might not be the function 2583 // that overload resolution actually selects. 2584 if (DiagnoseUseOfDecl(VD, Loc)) 2585 return ExprError(); 2586 2587 // Only create DeclRefExpr's for valid Decl's. 2588 if (VD->isInvalidDecl()) 2589 return ExprError(); 2590 2591 // Handle members of anonymous structs and unions. If we got here, 2592 // and the reference is to a class member indirect field, then this 2593 // must be the subject of a pointer-to-member expression. 2594 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2595 if (!indirectField->isCXXClassMember()) 2596 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2597 indirectField); 2598 2599 { 2600 QualType type = VD->getType(); 2601 ExprValueKind valueKind = VK_RValue; 2602 2603 switch (D->getKind()) { 2604 // Ignore all the non-ValueDecl kinds. 2605 #define ABSTRACT_DECL(kind) 2606 #define VALUE(type, base) 2607 #define DECL(type, base) \ 2608 case Decl::type: 2609 #include "clang/AST/DeclNodes.inc" 2610 llvm_unreachable("invalid value decl kind"); 2611 2612 // These shouldn't make it here. 2613 case Decl::ObjCAtDefsField: 2614 case Decl::ObjCIvar: 2615 llvm_unreachable("forming non-member reference to ivar?"); 2616 2617 // Enum constants are always r-values and never references. 2618 // Unresolved using declarations are dependent. 2619 case Decl::EnumConstant: 2620 case Decl::UnresolvedUsingValue: 2621 valueKind = VK_RValue; 2622 break; 2623 2624 // Fields and indirect fields that got here must be for 2625 // pointer-to-member expressions; we just call them l-values for 2626 // internal consistency, because this subexpression doesn't really 2627 // exist in the high-level semantics. 2628 case Decl::Field: 2629 case Decl::IndirectField: 2630 assert(getLangOpts().CPlusPlus && 2631 "building reference to field in C?"); 2632 2633 // These can't have reference type in well-formed programs, but 2634 // for internal consistency we do this anyway. 2635 type = type.getNonReferenceType(); 2636 valueKind = VK_LValue; 2637 break; 2638 2639 // Non-type template parameters are either l-values or r-values 2640 // depending on the type. 2641 case Decl::NonTypeTemplateParm: { 2642 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2643 type = reftype->getPointeeType(); 2644 valueKind = VK_LValue; // even if the parameter is an r-value reference 2645 break; 2646 } 2647 2648 // For non-references, we need to strip qualifiers just in case 2649 // the template parameter was declared as 'const int' or whatever. 2650 valueKind = VK_RValue; 2651 type = type.getUnqualifiedType(); 2652 break; 2653 } 2654 2655 case Decl::Var: 2656 case Decl::VarTemplateSpecialization: 2657 case Decl::VarTemplatePartialSpecialization: 2658 // In C, "extern void blah;" is valid and is an r-value. 2659 if (!getLangOpts().CPlusPlus && 2660 !type.hasQualifiers() && 2661 type->isVoidType()) { 2662 valueKind = VK_RValue; 2663 break; 2664 } 2665 // fallthrough 2666 2667 case Decl::ImplicitParam: 2668 case Decl::ParmVar: { 2669 // These are always l-values. 2670 valueKind = VK_LValue; 2671 type = type.getNonReferenceType(); 2672 2673 // FIXME: Does the addition of const really only apply in 2674 // potentially-evaluated contexts? Since the variable isn't actually 2675 // captured in an unevaluated context, it seems that the answer is no. 2676 if (!isUnevaluatedContext()) { 2677 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2678 if (!CapturedType.isNull()) 2679 type = CapturedType; 2680 } 2681 2682 break; 2683 } 2684 2685 case Decl::Function: { 2686 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2687 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2688 type = Context.BuiltinFnTy; 2689 valueKind = VK_RValue; 2690 break; 2691 } 2692 } 2693 2694 const FunctionType *fty = type->castAs<FunctionType>(); 2695 2696 // If we're referring to a function with an __unknown_anytype 2697 // result type, make the entire expression __unknown_anytype. 2698 if (fty->getResultType() == Context.UnknownAnyTy) { 2699 type = Context.UnknownAnyTy; 2700 valueKind = VK_RValue; 2701 break; 2702 } 2703 2704 // Functions are l-values in C++. 2705 if (getLangOpts().CPlusPlus) { 2706 valueKind = VK_LValue; 2707 break; 2708 } 2709 2710 // C99 DR 316 says that, if a function type comes from a 2711 // function definition (without a prototype), that type is only 2712 // used for checking compatibility. Therefore, when referencing 2713 // the function, we pretend that we don't have the full function 2714 // type. 2715 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2716 isa<FunctionProtoType>(fty)) 2717 type = Context.getFunctionNoProtoType(fty->getResultType(), 2718 fty->getExtInfo()); 2719 2720 // Functions are r-values in C. 2721 valueKind = VK_RValue; 2722 break; 2723 } 2724 2725 case Decl::MSProperty: 2726 valueKind = VK_LValue; 2727 break; 2728 2729 case Decl::CXXMethod: 2730 // If we're referring to a method with an __unknown_anytype 2731 // result type, make the entire expression __unknown_anytype. 2732 // This should only be possible with a type written directly. 2733 if (const FunctionProtoType *proto 2734 = dyn_cast<FunctionProtoType>(VD->getType())) 2735 if (proto->getResultType() == Context.UnknownAnyTy) { 2736 type = Context.UnknownAnyTy; 2737 valueKind = VK_RValue; 2738 break; 2739 } 2740 2741 // C++ methods are l-values if static, r-values if non-static. 2742 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2743 valueKind = VK_LValue; 2744 break; 2745 } 2746 // fallthrough 2747 2748 case Decl::CXXConversion: 2749 case Decl::CXXDestructor: 2750 case Decl::CXXConstructor: 2751 valueKind = VK_RValue; 2752 break; 2753 } 2754 2755 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2756 TemplateArgs); 2757 } 2758 } 2759 2760 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2761 PredefinedExpr::IdentType IT; 2762 2763 switch (Kind) { 2764 default: llvm_unreachable("Unknown simple primary expr!"); 2765 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2766 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2767 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2768 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2769 } 2770 2771 // Pre-defined identifiers are of type char[x], where x is the length of the 2772 // string. 2773 2774 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2775 // Blocks and lambdas can occur at global scope. Don't emit a warning. 2776 if (!currentDecl) { 2777 if (const BlockScopeInfo *BSI = getCurBlock()) 2778 currentDecl = BSI->TheDecl; 2779 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2780 currentDecl = LSI->CallOperator; 2781 } 2782 2783 if (!currentDecl) { 2784 Diag(Loc, diag::ext_predef_outside_function); 2785 currentDecl = Context.getTranslationUnitDecl(); 2786 } 2787 2788 QualType ResTy; 2789 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2790 ResTy = Context.DependentTy; 2791 } else { 2792 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2793 2794 llvm::APInt LengthI(32, Length + 1); 2795 if (IT == PredefinedExpr::LFunction) 2796 ResTy = Context.WideCharTy.withConst(); 2797 else 2798 ResTy = Context.CharTy.withConst(); 2799 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2800 } 2801 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2802 } 2803 2804 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2805 SmallString<16> CharBuffer; 2806 bool Invalid = false; 2807 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2808 if (Invalid) 2809 return ExprError(); 2810 2811 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2812 PP, Tok.getKind()); 2813 if (Literal.hadError()) 2814 return ExprError(); 2815 2816 QualType Ty; 2817 if (Literal.isWide()) 2818 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2819 else if (Literal.isUTF16()) 2820 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2821 else if (Literal.isUTF32()) 2822 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2823 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2824 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2825 else 2826 Ty = Context.CharTy; // 'x' -> char in C++ 2827 2828 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2829 if (Literal.isWide()) 2830 Kind = CharacterLiteral::Wide; 2831 else if (Literal.isUTF16()) 2832 Kind = CharacterLiteral::UTF16; 2833 else if (Literal.isUTF32()) 2834 Kind = CharacterLiteral::UTF32; 2835 2836 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2837 Tok.getLocation()); 2838 2839 if (Literal.getUDSuffix().empty()) 2840 return Owned(Lit); 2841 2842 // We're building a user-defined literal. 2843 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2844 SourceLocation UDSuffixLoc = 2845 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2846 2847 // Make sure we're allowed user-defined literals here. 2848 if (!UDLScope) 2849 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2850 2851 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2852 // operator "" X (ch) 2853 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2854 Lit, Tok.getLocation()); 2855 } 2856 2857 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2858 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2859 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2860 Context.IntTy, Loc)); 2861 } 2862 2863 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2864 QualType Ty, SourceLocation Loc) { 2865 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2866 2867 using llvm::APFloat; 2868 APFloat Val(Format); 2869 2870 APFloat::opStatus result = Literal.GetFloatValue(Val); 2871 2872 // Overflow is always an error, but underflow is only an error if 2873 // we underflowed to zero (APFloat reports denormals as underflow). 2874 if ((result & APFloat::opOverflow) || 2875 ((result & APFloat::opUnderflow) && Val.isZero())) { 2876 unsigned diagnostic; 2877 SmallString<20> buffer; 2878 if (result & APFloat::opOverflow) { 2879 diagnostic = diag::warn_float_overflow; 2880 APFloat::getLargest(Format).toString(buffer); 2881 } else { 2882 diagnostic = diag::warn_float_underflow; 2883 APFloat::getSmallest(Format).toString(buffer); 2884 } 2885 2886 S.Diag(Loc, diagnostic) 2887 << Ty 2888 << StringRef(buffer.data(), buffer.size()); 2889 } 2890 2891 bool isExact = (result == APFloat::opOK); 2892 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2893 } 2894 2895 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2896 // Fast path for a single digit (which is quite common). A single digit 2897 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2898 if (Tok.getLength() == 1) { 2899 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2900 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2901 } 2902 2903 SmallString<128> SpellingBuffer; 2904 // NumericLiteralParser wants to overread by one character. Add padding to 2905 // the buffer in case the token is copied to the buffer. If getSpelling() 2906 // returns a StringRef to the memory buffer, it should have a null char at 2907 // the EOF, so it is also safe. 2908 SpellingBuffer.resize(Tok.getLength() + 1); 2909 2910 // Get the spelling of the token, which eliminates trigraphs, etc. 2911 bool Invalid = false; 2912 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2913 if (Invalid) 2914 return ExprError(); 2915 2916 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2917 if (Literal.hadError) 2918 return ExprError(); 2919 2920 if (Literal.hasUDSuffix()) { 2921 // We're building a user-defined literal. 2922 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2923 SourceLocation UDSuffixLoc = 2924 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2925 2926 // Make sure we're allowed user-defined literals here. 2927 if (!UDLScope) 2928 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2929 2930 QualType CookedTy; 2931 if (Literal.isFloatingLiteral()) { 2932 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2933 // long double, the literal is treated as a call of the form 2934 // operator "" X (f L) 2935 CookedTy = Context.LongDoubleTy; 2936 } else { 2937 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2938 // unsigned long long, the literal is treated as a call of the form 2939 // operator "" X (n ULL) 2940 CookedTy = Context.UnsignedLongLongTy; 2941 } 2942 2943 DeclarationName OpName = 2944 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2945 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2946 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2947 2948 // Perform literal operator lookup to determine if we're building a raw 2949 // literal or a cooked one. 2950 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2951 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 2952 /*AllowRawAndTemplate*/true)) { 2953 case LOLR_Error: 2954 return ExprError(); 2955 2956 case LOLR_Cooked: { 2957 Expr *Lit; 2958 if (Literal.isFloatingLiteral()) { 2959 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2960 } else { 2961 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2962 if (Literal.GetIntegerValue(ResultVal)) 2963 Diag(Tok.getLocation(), diag::err_integer_too_large); 2964 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2965 Tok.getLocation()); 2966 } 2967 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, 2968 Tok.getLocation()); 2969 } 2970 2971 case LOLR_Raw: { 2972 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2973 // literal is treated as a call of the form 2974 // operator "" X ("n") 2975 SourceLocation TokLoc = Tok.getLocation(); 2976 unsigned Length = Literal.getUDSuffixOffset(); 2977 QualType StrTy = Context.getConstantArrayType( 2978 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 2979 ArrayType::Normal, 0); 2980 Expr *Lit = StringLiteral::Create( 2981 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2982 /*Pascal*/false, StrTy, &TokLoc, 1); 2983 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 2984 } 2985 2986 case LOLR_Template: 2987 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2988 // template), L is treated as a call fo the form 2989 // operator "" X <'c1', 'c2', ... 'ck'>() 2990 // where n is the source character sequence c1 c2 ... ck. 2991 TemplateArgumentListInfo ExplicitArgs; 2992 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2993 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2994 llvm::APSInt Value(CharBits, CharIsUnsigned); 2995 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2996 Value = TokSpelling[I]; 2997 TemplateArgument Arg(Context, Value, Context.CharTy); 2998 TemplateArgumentLocInfo ArgInfo; 2999 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3000 } 3001 return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(), 3002 &ExplicitArgs); 3003 } 3004 3005 llvm_unreachable("unexpected literal operator lookup result"); 3006 } 3007 3008 Expr *Res; 3009 3010 if (Literal.isFloatingLiteral()) { 3011 QualType Ty; 3012 if (Literal.isFloat) 3013 Ty = Context.FloatTy; 3014 else if (!Literal.isLong) 3015 Ty = Context.DoubleTy; 3016 else 3017 Ty = Context.LongDoubleTy; 3018 3019 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3020 3021 if (Ty == Context.DoubleTy) { 3022 if (getLangOpts().SinglePrecisionConstants) { 3023 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3024 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3025 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3026 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3027 } 3028 } 3029 } else if (!Literal.isIntegerLiteral()) { 3030 return ExprError(); 3031 } else { 3032 QualType Ty; 3033 3034 // 'long long' is a C99 or C++11 feature. 3035 if (!getLangOpts().C99 && Literal.isLongLong) { 3036 if (getLangOpts().CPlusPlus) 3037 Diag(Tok.getLocation(), 3038 getLangOpts().CPlusPlus11 ? 3039 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3040 else 3041 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3042 } 3043 3044 // Get the value in the widest-possible width. 3045 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3046 // The microsoft literal suffix extensions support 128-bit literals, which 3047 // may be wider than [u]intmax_t. 3048 // FIXME: Actually, they don't. We seem to have accidentally invented the 3049 // i128 suffix. 3050 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3051 PP.getTargetInfo().hasInt128Type()) 3052 MaxWidth = 128; 3053 llvm::APInt ResultVal(MaxWidth, 0); 3054 3055 if (Literal.GetIntegerValue(ResultVal)) { 3056 // If this value didn't fit into uintmax_t, error and force to ull. 3057 Diag(Tok.getLocation(), diag::err_integer_too_large); 3058 Ty = Context.UnsignedLongLongTy; 3059 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3060 "long long is not intmax_t?"); 3061 } else { 3062 // If this value fits into a ULL, try to figure out what else it fits into 3063 // according to the rules of C99 6.4.4.1p5. 3064 3065 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3066 // be an unsigned int. 3067 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3068 3069 // Check from smallest to largest, picking the smallest type we can. 3070 unsigned Width = 0; 3071 if (!Literal.isLong && !Literal.isLongLong) { 3072 // Are int/unsigned possibilities? 3073 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3074 3075 // Does it fit in a unsigned int? 3076 if (ResultVal.isIntN(IntSize)) { 3077 // Does it fit in a signed int? 3078 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3079 Ty = Context.IntTy; 3080 else if (AllowUnsigned) 3081 Ty = Context.UnsignedIntTy; 3082 Width = IntSize; 3083 } 3084 } 3085 3086 // Are long/unsigned long possibilities? 3087 if (Ty.isNull() && !Literal.isLongLong) { 3088 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3089 3090 // Does it fit in a unsigned long? 3091 if (ResultVal.isIntN(LongSize)) { 3092 // Does it fit in a signed long? 3093 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3094 Ty = Context.LongTy; 3095 else if (AllowUnsigned) 3096 Ty = Context.UnsignedLongTy; 3097 Width = LongSize; 3098 } 3099 } 3100 3101 // Check long long if needed. 3102 if (Ty.isNull()) { 3103 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3104 3105 // Does it fit in a unsigned long long? 3106 if (ResultVal.isIntN(LongLongSize)) { 3107 // Does it fit in a signed long long? 3108 // To be compatible with MSVC, hex integer literals ending with the 3109 // LL or i64 suffix are always signed in Microsoft mode. 3110 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3111 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3112 Ty = Context.LongLongTy; 3113 else if (AllowUnsigned) 3114 Ty = Context.UnsignedLongLongTy; 3115 Width = LongLongSize; 3116 } 3117 } 3118 3119 // If it doesn't fit in unsigned long long, and we're using Microsoft 3120 // extensions, then its a 128-bit integer literal. 3121 if (Ty.isNull() && Literal.isMicrosoftInteger && 3122 PP.getTargetInfo().hasInt128Type()) { 3123 if (Literal.isUnsigned) 3124 Ty = Context.UnsignedInt128Ty; 3125 else 3126 Ty = Context.Int128Ty; 3127 Width = 128; 3128 } 3129 3130 // If we still couldn't decide a type, we probably have something that 3131 // does not fit in a signed long long, but has no U suffix. 3132 if (Ty.isNull()) { 3133 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3134 Ty = Context.UnsignedLongLongTy; 3135 Width = Context.getTargetInfo().getLongLongWidth(); 3136 } 3137 3138 if (ResultVal.getBitWidth() != Width) 3139 ResultVal = ResultVal.trunc(Width); 3140 } 3141 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3142 } 3143 3144 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3145 if (Literal.isImaginary) 3146 Res = new (Context) ImaginaryLiteral(Res, 3147 Context.getComplexType(Res->getType())); 3148 3149 return Owned(Res); 3150 } 3151 3152 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3153 assert((E != 0) && "ActOnParenExpr() missing expr"); 3154 return Owned(new (Context) ParenExpr(L, R, E)); 3155 } 3156 3157 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3158 SourceLocation Loc, 3159 SourceRange ArgRange) { 3160 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3161 // scalar or vector data type argument..." 3162 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3163 // type (C99 6.2.5p18) or void. 3164 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3165 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3166 << T << ArgRange; 3167 return true; 3168 } 3169 3170 assert((T->isVoidType() || !T->isIncompleteType()) && 3171 "Scalar types should always be complete"); 3172 return false; 3173 } 3174 3175 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3176 SourceLocation Loc, 3177 SourceRange ArgRange, 3178 UnaryExprOrTypeTrait TraitKind) { 3179 // Invalid types must be hard errors for SFINAE in C++. 3180 if (S.LangOpts.CPlusPlus) 3181 return true; 3182 3183 // C99 6.5.3.4p1: 3184 if (T->isFunctionType() && 3185 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3186 // sizeof(function)/alignof(function) is allowed as an extension. 3187 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3188 << TraitKind << ArgRange; 3189 return false; 3190 } 3191 3192 // Allow sizeof(void)/alignof(void) as an extension. 3193 if (T->isVoidType()) { 3194 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3195 return false; 3196 } 3197 3198 return true; 3199 } 3200 3201 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3202 SourceLocation Loc, 3203 SourceRange ArgRange, 3204 UnaryExprOrTypeTrait TraitKind) { 3205 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3206 // runtime doesn't allow it. 3207 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3208 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3209 << T << (TraitKind == UETT_SizeOf) 3210 << ArgRange; 3211 return true; 3212 } 3213 3214 return false; 3215 } 3216 3217 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3218 /// pointer type is equal to T) and emit a warning if it is. 3219 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3220 Expr *E) { 3221 // Don't warn if the operation changed the type. 3222 if (T != E->getType()) 3223 return; 3224 3225 // Now look for array decays. 3226 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3227 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3228 return; 3229 3230 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3231 << ICE->getType() 3232 << ICE->getSubExpr()->getType(); 3233 } 3234 3235 /// \brief Check the constrains on expression operands to unary type expression 3236 /// and type traits. 3237 /// 3238 /// Completes any types necessary and validates the constraints on the operand 3239 /// expression. The logic mostly mirrors the type-based overload, but may modify 3240 /// the expression as it completes the type for that expression through template 3241 /// instantiation, etc. 3242 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3243 UnaryExprOrTypeTrait ExprKind) { 3244 QualType ExprTy = E->getType(); 3245 assert(!ExprTy->isReferenceType()); 3246 3247 if (ExprKind == UETT_VecStep) 3248 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3249 E->getSourceRange()); 3250 3251 // Whitelist some types as extensions 3252 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3253 E->getSourceRange(), ExprKind)) 3254 return false; 3255 3256 if (RequireCompleteExprType(E, 3257 diag::err_sizeof_alignof_incomplete_type, 3258 ExprKind, E->getSourceRange())) 3259 return true; 3260 3261 // Completing the expression's type may have changed it. 3262 ExprTy = E->getType(); 3263 assert(!ExprTy->isReferenceType()); 3264 3265 if (ExprTy->isFunctionType()) { 3266 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3267 << ExprKind << E->getSourceRange(); 3268 return true; 3269 } 3270 3271 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3272 E->getSourceRange(), ExprKind)) 3273 return true; 3274 3275 if (ExprKind == UETT_SizeOf) { 3276 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3277 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3278 QualType OType = PVD->getOriginalType(); 3279 QualType Type = PVD->getType(); 3280 if (Type->isPointerType() && OType->isArrayType()) { 3281 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3282 << Type << OType; 3283 Diag(PVD->getLocation(), diag::note_declared_at); 3284 } 3285 } 3286 } 3287 3288 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3289 // decays into a pointer and returns an unintended result. This is most 3290 // likely a typo for "sizeof(array) op x". 3291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3292 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3293 BO->getLHS()); 3294 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3295 BO->getRHS()); 3296 } 3297 } 3298 3299 return false; 3300 } 3301 3302 /// \brief Check the constraints on operands to unary expression and type 3303 /// traits. 3304 /// 3305 /// This will complete any types necessary, and validate the various constraints 3306 /// on those operands. 3307 /// 3308 /// The UsualUnaryConversions() function is *not* called by this routine. 3309 /// C99 6.3.2.1p[2-4] all state: 3310 /// Except when it is the operand of the sizeof operator ... 3311 /// 3312 /// C++ [expr.sizeof]p4 3313 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3314 /// standard conversions are not applied to the operand of sizeof. 3315 /// 3316 /// This policy is followed for all of the unary trait expressions. 3317 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3318 SourceLocation OpLoc, 3319 SourceRange ExprRange, 3320 UnaryExprOrTypeTrait ExprKind) { 3321 if (ExprType->isDependentType()) 3322 return false; 3323 3324 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3325 // the result is the size of the referenced type." 3326 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3327 // result shall be the alignment of the referenced type." 3328 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3329 ExprType = Ref->getPointeeType(); 3330 3331 if (ExprKind == UETT_VecStep) 3332 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3333 3334 // Whitelist some types as extensions 3335 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3336 ExprKind)) 3337 return false; 3338 3339 if (RequireCompleteType(OpLoc, ExprType, 3340 diag::err_sizeof_alignof_incomplete_type, 3341 ExprKind, ExprRange)) 3342 return true; 3343 3344 if (ExprType->isFunctionType()) { 3345 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3346 << ExprKind << ExprRange; 3347 return true; 3348 } 3349 3350 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3351 ExprKind)) 3352 return true; 3353 3354 return false; 3355 } 3356 3357 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3358 E = E->IgnoreParens(); 3359 3360 // Cannot know anything else if the expression is dependent. 3361 if (E->isTypeDependent()) 3362 return false; 3363 3364 if (E->getObjectKind() == OK_BitField) { 3365 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3366 << 1 << E->getSourceRange(); 3367 return true; 3368 } 3369 3370 ValueDecl *D = 0; 3371 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3372 D = DRE->getDecl(); 3373 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3374 D = ME->getMemberDecl(); 3375 } 3376 3377 // If it's a field, require the containing struct to have a 3378 // complete definition so that we can compute the layout. 3379 // 3380 // This requires a very particular set of circumstances. For a 3381 // field to be contained within an incomplete type, we must in the 3382 // process of parsing that type. To have an expression refer to a 3383 // field, it must be an id-expression or a member-expression, but 3384 // the latter are always ill-formed when the base type is 3385 // incomplete, including only being partially complete. An 3386 // id-expression can never refer to a field in C because fields 3387 // are not in the ordinary namespace. In C++, an id-expression 3388 // can implicitly be a member access, but only if there's an 3389 // implicit 'this' value, and all such contexts are subject to 3390 // delayed parsing --- except for trailing return types in C++11. 3391 // And if an id-expression referring to a field occurs in a 3392 // context that lacks a 'this' value, it's ill-formed --- except, 3393 // agian, in C++11, where such references are allowed in an 3394 // unevaluated context. So C++11 introduces some new complexity. 3395 // 3396 // For the record, since __alignof__ on expressions is a GCC 3397 // extension, GCC seems to permit this but always gives the 3398 // nonsensical answer 0. 3399 // 3400 // We don't really need the layout here --- we could instead just 3401 // directly check for all the appropriate alignment-lowing 3402 // attributes --- but that would require duplicating a lot of 3403 // logic that just isn't worth duplicating for such a marginal 3404 // use-case. 3405 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3406 // Fast path this check, since we at least know the record has a 3407 // definition if we can find a member of it. 3408 if (!FD->getParent()->isCompleteDefinition()) { 3409 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3410 << E->getSourceRange(); 3411 return true; 3412 } 3413 3414 // Otherwise, if it's a field, and the field doesn't have 3415 // reference type, then it must have a complete type (or be a 3416 // flexible array member, which we explicitly want to 3417 // white-list anyway), which makes the following checks trivial. 3418 if (!FD->getType()->isReferenceType()) 3419 return false; 3420 } 3421 3422 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3423 } 3424 3425 bool Sema::CheckVecStepExpr(Expr *E) { 3426 E = E->IgnoreParens(); 3427 3428 // Cannot know anything else if the expression is dependent. 3429 if (E->isTypeDependent()) 3430 return false; 3431 3432 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3433 } 3434 3435 /// \brief Build a sizeof or alignof expression given a type operand. 3436 ExprResult 3437 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3438 SourceLocation OpLoc, 3439 UnaryExprOrTypeTrait ExprKind, 3440 SourceRange R) { 3441 if (!TInfo) 3442 return ExprError(); 3443 3444 QualType T = TInfo->getType(); 3445 3446 if (!T->isDependentType() && 3447 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3448 return ExprError(); 3449 3450 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3451 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3452 Context.getSizeType(), 3453 OpLoc, R.getEnd())); 3454 } 3455 3456 /// \brief Build a sizeof or alignof expression given an expression 3457 /// operand. 3458 ExprResult 3459 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3460 UnaryExprOrTypeTrait ExprKind) { 3461 ExprResult PE = CheckPlaceholderExpr(E); 3462 if (PE.isInvalid()) 3463 return ExprError(); 3464 3465 E = PE.get(); 3466 3467 // Verify that the operand is valid. 3468 bool isInvalid = false; 3469 if (E->isTypeDependent()) { 3470 // Delay type-checking for type-dependent expressions. 3471 } else if (ExprKind == UETT_AlignOf) { 3472 isInvalid = CheckAlignOfExpr(*this, E); 3473 } else if (ExprKind == UETT_VecStep) { 3474 isInvalid = CheckVecStepExpr(E); 3475 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3476 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3477 isInvalid = true; 3478 } else { 3479 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3480 } 3481 3482 if (isInvalid) 3483 return ExprError(); 3484 3485 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3486 PE = TransformToPotentiallyEvaluated(E); 3487 if (PE.isInvalid()) return ExprError(); 3488 E = PE.take(); 3489 } 3490 3491 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3492 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3493 ExprKind, E, Context.getSizeType(), OpLoc, 3494 E->getSourceRange().getEnd())); 3495 } 3496 3497 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3498 /// expr and the same for @c alignof and @c __alignof 3499 /// Note that the ArgRange is invalid if isType is false. 3500 ExprResult 3501 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3502 UnaryExprOrTypeTrait ExprKind, bool IsType, 3503 void *TyOrEx, const SourceRange &ArgRange) { 3504 // If error parsing type, ignore. 3505 if (TyOrEx == 0) return ExprError(); 3506 3507 if (IsType) { 3508 TypeSourceInfo *TInfo; 3509 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3510 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3511 } 3512 3513 Expr *ArgEx = (Expr *)TyOrEx; 3514 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3515 return Result; 3516 } 3517 3518 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3519 bool IsReal) { 3520 if (V.get()->isTypeDependent()) 3521 return S.Context.DependentTy; 3522 3523 // _Real and _Imag are only l-values for normal l-values. 3524 if (V.get()->getObjectKind() != OK_Ordinary) { 3525 V = S.DefaultLvalueConversion(V.take()); 3526 if (V.isInvalid()) 3527 return QualType(); 3528 } 3529 3530 // These operators return the element type of a complex type. 3531 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3532 return CT->getElementType(); 3533 3534 // Otherwise they pass through real integer and floating point types here. 3535 if (V.get()->getType()->isArithmeticType()) 3536 return V.get()->getType(); 3537 3538 // Test for placeholders. 3539 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3540 if (PR.isInvalid()) return QualType(); 3541 if (PR.get() != V.get()) { 3542 V = PR; 3543 return CheckRealImagOperand(S, V, Loc, IsReal); 3544 } 3545 3546 // Reject anything else. 3547 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3548 << (IsReal ? "__real" : "__imag"); 3549 return QualType(); 3550 } 3551 3552 3553 3554 ExprResult 3555 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3556 tok::TokenKind Kind, Expr *Input) { 3557 UnaryOperatorKind Opc; 3558 switch (Kind) { 3559 default: llvm_unreachable("Unknown unary op!"); 3560 case tok::plusplus: Opc = UO_PostInc; break; 3561 case tok::minusminus: Opc = UO_PostDec; break; 3562 } 3563 3564 // Since this might is a postfix expression, get rid of ParenListExprs. 3565 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3566 if (Result.isInvalid()) return ExprError(); 3567 Input = Result.take(); 3568 3569 return BuildUnaryOp(S, OpLoc, Opc, Input); 3570 } 3571 3572 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3573 /// 3574 /// \return true on error 3575 static bool checkArithmeticOnObjCPointer(Sema &S, 3576 SourceLocation opLoc, 3577 Expr *op) { 3578 assert(op->getType()->isObjCObjectPointerType()); 3579 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3580 return false; 3581 3582 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3583 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3584 << op->getSourceRange(); 3585 return true; 3586 } 3587 3588 ExprResult 3589 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3590 Expr *idx, SourceLocation rbLoc) { 3591 // Since this might be a postfix expression, get rid of ParenListExprs. 3592 if (isa<ParenListExpr>(base)) { 3593 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3594 if (result.isInvalid()) return ExprError(); 3595 base = result.take(); 3596 } 3597 3598 // Handle any non-overload placeholder types in the base and index 3599 // expressions. We can't handle overloads here because the other 3600 // operand might be an overloadable type, in which case the overload 3601 // resolution for the operator overload should get the first crack 3602 // at the overload. 3603 if (base->getType()->isNonOverloadPlaceholderType()) { 3604 ExprResult result = CheckPlaceholderExpr(base); 3605 if (result.isInvalid()) return ExprError(); 3606 base = result.take(); 3607 } 3608 if (idx->getType()->isNonOverloadPlaceholderType()) { 3609 ExprResult result = CheckPlaceholderExpr(idx); 3610 if (result.isInvalid()) return ExprError(); 3611 idx = result.take(); 3612 } 3613 3614 // Build an unanalyzed expression if either operand is type-dependent. 3615 if (getLangOpts().CPlusPlus && 3616 (base->isTypeDependent() || idx->isTypeDependent())) { 3617 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3618 Context.DependentTy, 3619 VK_LValue, OK_Ordinary, 3620 rbLoc)); 3621 } 3622 3623 // Use C++ overloaded-operator rules if either operand has record 3624 // type. The spec says to do this if either type is *overloadable*, 3625 // but enum types can't declare subscript operators or conversion 3626 // operators, so there's nothing interesting for overload resolution 3627 // to do if there aren't any record types involved. 3628 // 3629 // ObjC pointers have their own subscripting logic that is not tied 3630 // to overload resolution and so should not take this path. 3631 if (getLangOpts().CPlusPlus && 3632 (base->getType()->isRecordType() || 3633 (!base->getType()->isObjCObjectPointerType() && 3634 idx->getType()->isRecordType()))) { 3635 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3636 } 3637 3638 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3639 } 3640 3641 ExprResult 3642 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3643 Expr *Idx, SourceLocation RLoc) { 3644 Expr *LHSExp = Base; 3645 Expr *RHSExp = Idx; 3646 3647 // Perform default conversions. 3648 if (!LHSExp->getType()->getAs<VectorType>()) { 3649 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3650 if (Result.isInvalid()) 3651 return ExprError(); 3652 LHSExp = Result.take(); 3653 } 3654 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3655 if (Result.isInvalid()) 3656 return ExprError(); 3657 RHSExp = Result.take(); 3658 3659 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3660 ExprValueKind VK = VK_LValue; 3661 ExprObjectKind OK = OK_Ordinary; 3662 3663 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3664 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3665 // in the subscript position. As a result, we need to derive the array base 3666 // and index from the expression types. 3667 Expr *BaseExpr, *IndexExpr; 3668 QualType ResultType; 3669 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3670 BaseExpr = LHSExp; 3671 IndexExpr = RHSExp; 3672 ResultType = Context.DependentTy; 3673 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3674 BaseExpr = LHSExp; 3675 IndexExpr = RHSExp; 3676 ResultType = PTy->getPointeeType(); 3677 } else if (const ObjCObjectPointerType *PTy = 3678 LHSTy->getAs<ObjCObjectPointerType>()) { 3679 BaseExpr = LHSExp; 3680 IndexExpr = RHSExp; 3681 3682 // Use custom logic if this should be the pseudo-object subscript 3683 // expression. 3684 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3685 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3686 3687 ResultType = PTy->getPointeeType(); 3688 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3689 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3690 << ResultType << BaseExpr->getSourceRange(); 3691 return ExprError(); 3692 } 3693 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3694 // Handle the uncommon case of "123[Ptr]". 3695 BaseExpr = RHSExp; 3696 IndexExpr = LHSExp; 3697 ResultType = PTy->getPointeeType(); 3698 } else if (const ObjCObjectPointerType *PTy = 3699 RHSTy->getAs<ObjCObjectPointerType>()) { 3700 // Handle the uncommon case of "123[Ptr]". 3701 BaseExpr = RHSExp; 3702 IndexExpr = LHSExp; 3703 ResultType = PTy->getPointeeType(); 3704 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3705 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3706 << ResultType << BaseExpr->getSourceRange(); 3707 return ExprError(); 3708 } 3709 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3710 BaseExpr = LHSExp; // vectors: V[123] 3711 IndexExpr = RHSExp; 3712 VK = LHSExp->getValueKind(); 3713 if (VK != VK_RValue) 3714 OK = OK_VectorComponent; 3715 3716 // FIXME: need to deal with const... 3717 ResultType = VTy->getElementType(); 3718 } else if (LHSTy->isArrayType()) { 3719 // If we see an array that wasn't promoted by 3720 // DefaultFunctionArrayLvalueConversion, it must be an array that 3721 // wasn't promoted because of the C90 rule that doesn't 3722 // allow promoting non-lvalue arrays. Warn, then 3723 // force the promotion here. 3724 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3725 LHSExp->getSourceRange(); 3726 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3727 CK_ArrayToPointerDecay).take(); 3728 LHSTy = LHSExp->getType(); 3729 3730 BaseExpr = LHSExp; 3731 IndexExpr = RHSExp; 3732 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3733 } else if (RHSTy->isArrayType()) { 3734 // Same as previous, except for 123[f().a] case 3735 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3736 RHSExp->getSourceRange(); 3737 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3738 CK_ArrayToPointerDecay).take(); 3739 RHSTy = RHSExp->getType(); 3740 3741 BaseExpr = RHSExp; 3742 IndexExpr = LHSExp; 3743 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3744 } else { 3745 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3746 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3747 } 3748 // C99 6.5.2.1p1 3749 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3750 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3751 << IndexExpr->getSourceRange()); 3752 3753 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3754 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3755 && !IndexExpr->isTypeDependent()) 3756 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3757 3758 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3759 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3760 // type. Note that Functions are not objects, and that (in C99 parlance) 3761 // incomplete types are not object types. 3762 if (ResultType->isFunctionType()) { 3763 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3764 << ResultType << BaseExpr->getSourceRange(); 3765 return ExprError(); 3766 } 3767 3768 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3769 // GNU extension: subscripting on pointer to void 3770 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3771 << BaseExpr->getSourceRange(); 3772 3773 // C forbids expressions of unqualified void type from being l-values. 3774 // See IsCForbiddenLValueType. 3775 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3776 } else if (!ResultType->isDependentType() && 3777 RequireCompleteType(LLoc, ResultType, 3778 diag::err_subscript_incomplete_type, BaseExpr)) 3779 return ExprError(); 3780 3781 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3782 !ResultType.isCForbiddenLValueType()); 3783 3784 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3785 ResultType, VK, OK, RLoc)); 3786 } 3787 3788 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3789 FunctionDecl *FD, 3790 ParmVarDecl *Param) { 3791 if (Param->hasUnparsedDefaultArg()) { 3792 Diag(CallLoc, 3793 diag::err_use_of_default_argument_to_function_declared_later) << 3794 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3795 Diag(UnparsedDefaultArgLocs[Param], 3796 diag::note_default_argument_declared_here); 3797 return ExprError(); 3798 } 3799 3800 if (Param->hasUninstantiatedDefaultArg()) { 3801 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3802 3803 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3804 Param); 3805 3806 // Instantiate the expression. 3807 MultiLevelTemplateArgumentList MutiLevelArgList 3808 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3809 3810 InstantiatingTemplate Inst(*this, CallLoc, Param, 3811 MutiLevelArgList.getInnermost()); 3812 if (Inst) 3813 return ExprError(); 3814 3815 ExprResult Result; 3816 { 3817 // C++ [dcl.fct.default]p5: 3818 // The names in the [default argument] expression are bound, and 3819 // the semantic constraints are checked, at the point where the 3820 // default argument expression appears. 3821 ContextRAII SavedContext(*this, FD); 3822 LocalInstantiationScope Local(*this); 3823 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3824 } 3825 if (Result.isInvalid()) 3826 return ExprError(); 3827 3828 // Check the expression as an initializer for the parameter. 3829 InitializedEntity Entity 3830 = InitializedEntity::InitializeParameter(Context, Param); 3831 InitializationKind Kind 3832 = InitializationKind::CreateCopy(Param->getLocation(), 3833 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3834 Expr *ResultE = Result.takeAs<Expr>(); 3835 3836 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3837 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3838 if (Result.isInvalid()) 3839 return ExprError(); 3840 3841 Expr *Arg = Result.takeAs<Expr>(); 3842 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3843 // Build the default argument expression. 3844 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3845 } 3846 3847 // If the default expression creates temporaries, we need to 3848 // push them to the current stack of expression temporaries so they'll 3849 // be properly destroyed. 3850 // FIXME: We should really be rebuilding the default argument with new 3851 // bound temporaries; see the comment in PR5810. 3852 // We don't need to do that with block decls, though, because 3853 // blocks in default argument expression can never capture anything. 3854 if (isa<ExprWithCleanups>(Param->getInit())) { 3855 // Set the "needs cleanups" bit regardless of whether there are 3856 // any explicit objects. 3857 ExprNeedsCleanups = true; 3858 3859 // Append all the objects to the cleanup list. Right now, this 3860 // should always be a no-op, because blocks in default argument 3861 // expressions should never be able to capture anything. 3862 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3863 "default argument expression has capturing blocks?"); 3864 } 3865 3866 // We already type-checked the argument, so we know it works. 3867 // Just mark all of the declarations in this potentially-evaluated expression 3868 // as being "referenced". 3869 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3870 /*SkipLocalVariables=*/true); 3871 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3872 } 3873 3874 3875 Sema::VariadicCallType 3876 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3877 Expr *Fn) { 3878 if (Proto && Proto->isVariadic()) { 3879 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3880 return VariadicConstructor; 3881 else if (Fn && Fn->getType()->isBlockPointerType()) 3882 return VariadicBlock; 3883 else if (FDecl) { 3884 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3885 if (Method->isInstance()) 3886 return VariadicMethod; 3887 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3888 return VariadicMethod; 3889 return VariadicFunction; 3890 } 3891 return VariadicDoesNotApply; 3892 } 3893 3894 namespace { 3895 class FunctionCallCCC : public FunctionCallFilterCCC { 3896 public: 3897 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3898 unsigned NumArgs, bool HasExplicitTemplateArgs) 3899 : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs), 3900 FunctionName(FuncName) {} 3901 3902 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 3903 if (!candidate.getCorrectionSpecifier() || 3904 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3905 return false; 3906 } 3907 3908 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3909 } 3910 3911 private: 3912 const IdentifierInfo *const FunctionName; 3913 }; 3914 } 3915 3916 static TypoCorrection TryTypoCorrectionForCall(Sema &S, 3917 DeclarationNameInfo FuncName, 3918 ArrayRef<Expr *> Args) { 3919 FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(), 3920 Args.size(), false); 3921 if (TypoCorrection Corrected = 3922 S.CorrectTypo(FuncName, Sema::LookupOrdinaryName, 3923 S.getScopeForContext(S.CurContext), NULL, CCC)) { 3924 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 3925 if (Corrected.isOverloaded()) { 3926 OverloadCandidateSet OCS(FuncName.getLoc()); 3927 OverloadCandidateSet::iterator Best; 3928 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 3929 CDEnd = Corrected.end(); 3930 CD != CDEnd; ++CD) { 3931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 3932 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 3933 OCS); 3934 } 3935 switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) { 3936 case OR_Success: 3937 ND = Best->Function; 3938 Corrected.setCorrectionDecl(ND); 3939 break; 3940 default: 3941 break; 3942 } 3943 } 3944 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 3945 return Corrected; 3946 } 3947 } 3948 } 3949 return TypoCorrection(); 3950 } 3951 3952 /// ConvertArgumentsForCall - Converts the arguments specified in 3953 /// Args/NumArgs to the parameter types of the function FDecl with 3954 /// function prototype Proto. Call is the call expression itself, and 3955 /// Fn is the function expression. For a C++ member function, this 3956 /// routine does not attempt to convert the object argument. Returns 3957 /// true if the call is ill-formed. 3958 bool 3959 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3960 FunctionDecl *FDecl, 3961 const FunctionProtoType *Proto, 3962 ArrayRef<Expr *> Args, 3963 SourceLocation RParenLoc, 3964 bool IsExecConfig) { 3965 // Bail out early if calling a builtin with custom typechecking. 3966 // We don't need to do this in the 3967 if (FDecl) 3968 if (unsigned ID = FDecl->getBuiltinID()) 3969 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3970 return false; 3971 3972 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3973 // assignment, to the types of the corresponding parameter, ... 3974 unsigned NumArgsInProto = Proto->getNumArgs(); 3975 bool Invalid = false; 3976 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3977 unsigned FnKind = Fn->getType()->isBlockPointerType() 3978 ? 1 /* block */ 3979 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3980 : 0 /* function */); 3981 3982 // If too few arguments are available (and we don't have default 3983 // arguments for the remaining parameters), don't make the call. 3984 if (Args.size() < NumArgsInProto) { 3985 if (Args.size() < MinArgs) { 3986 TypoCorrection TC; 3987 if (FDecl && (TC = TryTypoCorrectionForCall( 3988 *this, DeclarationNameInfo(FDecl->getDeclName(), 3989 Fn->getLocStart()), 3990 Args))) { 3991 std::string CorrectedStr(TC.getAsString(getLangOpts())); 3992 std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts())); 3993 unsigned diag_id = 3994 MinArgs == NumArgsInProto && !Proto->isVariadic() 3995 ? diag::err_typecheck_call_too_few_args_suggest 3996 : diag::err_typecheck_call_too_few_args_at_least_suggest; 3997 Diag(RParenLoc, diag_id) 3998 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 3999 << Fn->getSourceRange() << CorrectedQuotedStr 4000 << FixItHint::CreateReplacement(TC.getCorrectionRange(), 4001 CorrectedStr); 4002 Diag(TC.getCorrectionDecl()->getLocStart(), 4003 diag::note_previous_decl) << CorrectedQuotedStr; 4004 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4005 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4006 ? diag::err_typecheck_call_too_few_args_one 4007 : diag::err_typecheck_call_too_few_args_at_least_one) 4008 << FnKind 4009 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4010 else 4011 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 4012 ? diag::err_typecheck_call_too_few_args 4013 : diag::err_typecheck_call_too_few_args_at_least) 4014 << FnKind 4015 << MinArgs << static_cast<unsigned>(Args.size()) 4016 << Fn->getSourceRange(); 4017 4018 // Emit the location of the prototype. 4019 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4020 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4021 << FDecl; 4022 4023 return true; 4024 } 4025 Call->setNumArgs(Context, NumArgsInProto); 4026 } 4027 4028 // If too many are passed and not variadic, error on the extras and drop 4029 // them. 4030 if (Args.size() > NumArgsInProto) { 4031 if (!Proto->isVariadic()) { 4032 TypoCorrection TC; 4033 if (FDecl && (TC = TryTypoCorrectionForCall( 4034 *this, DeclarationNameInfo(FDecl->getDeclName(), 4035 Fn->getLocStart()), 4036 Args))) { 4037 std::string CorrectedStr(TC.getAsString(getLangOpts())); 4038 std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts())); 4039 unsigned diag_id = 4040 MinArgs == NumArgsInProto && !Proto->isVariadic() 4041 ? diag::err_typecheck_call_too_many_args_suggest 4042 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4043 Diag(Args[NumArgsInProto]->getLocStart(), diag_id) 4044 << FnKind << NumArgsInProto << static_cast<unsigned>(Args.size()) 4045 << Fn->getSourceRange() << CorrectedQuotedStr 4046 << FixItHint::CreateReplacement(TC.getCorrectionRange(), 4047 CorrectedStr); 4048 Diag(TC.getCorrectionDecl()->getLocStart(), 4049 diag::note_previous_decl) << CorrectedQuotedStr; 4050 } else if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4051 Diag(Args[NumArgsInProto]->getLocStart(), 4052 MinArgs == NumArgsInProto 4053 ? diag::err_typecheck_call_too_many_args_one 4054 : diag::err_typecheck_call_too_many_args_at_most_one) 4055 << FnKind 4056 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size()) 4057 << Fn->getSourceRange() 4058 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4059 Args.back()->getLocEnd()); 4060 else 4061 Diag(Args[NumArgsInProto]->getLocStart(), 4062 MinArgs == NumArgsInProto 4063 ? diag::err_typecheck_call_too_many_args 4064 : diag::err_typecheck_call_too_many_args_at_most) 4065 << FnKind 4066 << NumArgsInProto << static_cast<unsigned>(Args.size()) 4067 << Fn->getSourceRange() 4068 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4069 Args.back()->getLocEnd()); 4070 4071 // Emit the location of the prototype. 4072 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4073 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4074 << FDecl; 4075 4076 // This deletes the extra arguments. 4077 Call->setNumArgs(Context, NumArgsInProto); 4078 return true; 4079 } 4080 } 4081 SmallVector<Expr *, 8> AllArgs; 4082 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4083 4084 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4085 Proto, 0, Args, AllArgs, CallType); 4086 if (Invalid) 4087 return true; 4088 unsigned TotalNumArgs = AllArgs.size(); 4089 for (unsigned i = 0; i < TotalNumArgs; ++i) 4090 Call->setArg(i, AllArgs[i]); 4091 4092 return false; 4093 } 4094 4095 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 4096 FunctionDecl *FDecl, 4097 const FunctionProtoType *Proto, 4098 unsigned FirstProtoArg, 4099 ArrayRef<Expr *> Args, 4100 SmallVectorImpl<Expr *> &AllArgs, 4101 VariadicCallType CallType, 4102 bool AllowExplicit, 4103 bool IsListInitialization) { 4104 unsigned NumArgsInProto = Proto->getNumArgs(); 4105 unsigned NumArgsToCheck = Args.size(); 4106 bool Invalid = false; 4107 if (Args.size() != NumArgsInProto) 4108 // Use default arguments for missing arguments 4109 NumArgsToCheck = NumArgsInProto; 4110 unsigned ArgIx = 0; 4111 // Continue to check argument types (even if we have too few/many args). 4112 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 4113 QualType ProtoArgType = Proto->getArgType(i); 4114 4115 Expr *Arg; 4116 ParmVarDecl *Param; 4117 if (ArgIx < Args.size()) { 4118 Arg = Args[ArgIx++]; 4119 4120 if (RequireCompleteType(Arg->getLocStart(), 4121 ProtoArgType, 4122 diag::err_call_incomplete_argument, Arg)) 4123 return true; 4124 4125 // Pass the argument 4126 Param = 0; 4127 if (FDecl && i < FDecl->getNumParams()) 4128 Param = FDecl->getParamDecl(i); 4129 4130 // Strip the unbridged-cast placeholder expression off, if applicable. 4131 bool CFAudited = false; 4132 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4133 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4134 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4135 Arg = stripARCUnbridgedCast(Arg); 4136 else if (getLangOpts().ObjCAutoRefCount && 4137 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4138 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4139 CFAudited = true; 4140 4141 InitializedEntity Entity = Param ? 4142 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 4143 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 4144 Proto->isArgConsumed(i)); 4145 4146 // Remember that parameter belongs to a CF audited API. 4147 if (CFAudited) 4148 Entity.setParameterCFAudited(); 4149 4150 ExprResult ArgE = PerformCopyInitialization(Entity, 4151 SourceLocation(), 4152 Owned(Arg), 4153 IsListInitialization, 4154 AllowExplicit); 4155 if (ArgE.isInvalid()) 4156 return true; 4157 4158 Arg = ArgE.takeAs<Expr>(); 4159 } else { 4160 assert(FDecl && "can't use default arguments without a known callee"); 4161 Param = FDecl->getParamDecl(i); 4162 4163 ExprResult ArgExpr = 4164 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4165 if (ArgExpr.isInvalid()) 4166 return true; 4167 4168 Arg = ArgExpr.takeAs<Expr>(); 4169 } 4170 4171 // Check for array bounds violations for each argument to the call. This 4172 // check only triggers warnings when the argument isn't a more complex Expr 4173 // with its own checking, such as a BinaryOperator. 4174 CheckArrayAccess(Arg); 4175 4176 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4177 CheckStaticArrayArgument(CallLoc, Param, Arg); 4178 4179 AllArgs.push_back(Arg); 4180 } 4181 4182 // If this is a variadic call, handle args passed through "...". 4183 if (CallType != VariadicDoesNotApply) { 4184 // Assume that extern "C" functions with variadic arguments that 4185 // return __unknown_anytype aren't *really* variadic. 4186 if (Proto->getResultType() == Context.UnknownAnyTy && 4187 FDecl && FDecl->isExternC()) { 4188 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4189 QualType paramType; // ignored 4190 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4191 Invalid |= arg.isInvalid(); 4192 AllArgs.push_back(arg.take()); 4193 } 4194 4195 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4196 } else { 4197 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4198 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4199 FDecl); 4200 Invalid |= Arg.isInvalid(); 4201 AllArgs.push_back(Arg.take()); 4202 } 4203 } 4204 4205 // Check for array bounds violations. 4206 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4207 CheckArrayAccess(Args[i]); 4208 } 4209 return Invalid; 4210 } 4211 4212 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4213 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4214 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4215 TL = DTL.getOriginalLoc(); 4216 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4217 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4218 << ATL.getLocalSourceRange(); 4219 } 4220 4221 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4222 /// array parameter, check that it is non-null, and that if it is formed by 4223 /// array-to-pointer decay, the underlying array is sufficiently large. 4224 /// 4225 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4226 /// array type derivation, then for each call to the function, the value of the 4227 /// corresponding actual argument shall provide access to the first element of 4228 /// an array with at least as many elements as specified by the size expression. 4229 void 4230 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4231 ParmVarDecl *Param, 4232 const Expr *ArgExpr) { 4233 // Static array parameters are not supported in C++. 4234 if (!Param || getLangOpts().CPlusPlus) 4235 return; 4236 4237 QualType OrigTy = Param->getOriginalType(); 4238 4239 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4240 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4241 return; 4242 4243 if (ArgExpr->isNullPointerConstant(Context, 4244 Expr::NPC_NeverValueDependent)) { 4245 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4246 DiagnoseCalleeStaticArrayParam(*this, Param); 4247 return; 4248 } 4249 4250 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4251 if (!CAT) 4252 return; 4253 4254 const ConstantArrayType *ArgCAT = 4255 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4256 if (!ArgCAT) 4257 return; 4258 4259 if (ArgCAT->getSize().ult(CAT->getSize())) { 4260 Diag(CallLoc, diag::warn_static_array_too_small) 4261 << ArgExpr->getSourceRange() 4262 << (unsigned) ArgCAT->getSize().getZExtValue() 4263 << (unsigned) CAT->getSize().getZExtValue(); 4264 DiagnoseCalleeStaticArrayParam(*this, Param); 4265 } 4266 } 4267 4268 /// Given a function expression of unknown-any type, try to rebuild it 4269 /// to have a function type. 4270 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4271 4272 /// Is the given type a placeholder that we need to lower out 4273 /// immediately during argument processing? 4274 static bool isPlaceholderToRemoveAsArg(QualType type) { 4275 // Placeholders are never sugared. 4276 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4277 if (!placeholder) return false; 4278 4279 switch (placeholder->getKind()) { 4280 // Ignore all the non-placeholder types. 4281 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4282 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4283 #include "clang/AST/BuiltinTypes.def" 4284 return false; 4285 4286 // We cannot lower out overload sets; they might validly be resolved 4287 // by the call machinery. 4288 case BuiltinType::Overload: 4289 return false; 4290 4291 // Unbridged casts in ARC can be handled in some call positions and 4292 // should be left in place. 4293 case BuiltinType::ARCUnbridgedCast: 4294 return false; 4295 4296 // Pseudo-objects should be converted as soon as possible. 4297 case BuiltinType::PseudoObject: 4298 return true; 4299 4300 // The debugger mode could theoretically but currently does not try 4301 // to resolve unknown-typed arguments based on known parameter types. 4302 case BuiltinType::UnknownAny: 4303 return true; 4304 4305 // These are always invalid as call arguments and should be reported. 4306 case BuiltinType::BoundMember: 4307 case BuiltinType::BuiltinFn: 4308 return true; 4309 } 4310 llvm_unreachable("bad builtin type kind"); 4311 } 4312 4313 /// Check an argument list for placeholders that we won't try to 4314 /// handle later. 4315 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4316 // Apply this processing to all the arguments at once instead of 4317 // dying at the first failure. 4318 bool hasInvalid = false; 4319 for (size_t i = 0, e = args.size(); i != e; i++) { 4320 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4321 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4322 if (result.isInvalid()) hasInvalid = true; 4323 else args[i] = result.take(); 4324 } 4325 } 4326 return hasInvalid; 4327 } 4328 4329 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4330 /// This provides the location of the left/right parens and a list of comma 4331 /// locations. 4332 ExprResult 4333 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4334 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4335 Expr *ExecConfig, bool IsExecConfig) { 4336 // Since this might be a postfix expression, get rid of ParenListExprs. 4337 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4338 if (Result.isInvalid()) return ExprError(); 4339 Fn = Result.take(); 4340 4341 if (checkArgsForPlaceholders(*this, ArgExprs)) 4342 return ExprError(); 4343 4344 if (getLangOpts().CPlusPlus) { 4345 // If this is a pseudo-destructor expression, build the call immediately. 4346 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4347 if (!ArgExprs.empty()) { 4348 // Pseudo-destructor calls should not have any arguments. 4349 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4350 << FixItHint::CreateRemoval( 4351 SourceRange(ArgExprs[0]->getLocStart(), 4352 ArgExprs.back()->getLocEnd())); 4353 } 4354 4355 return Owned(new (Context) CallExpr(Context, Fn, None, 4356 Context.VoidTy, VK_RValue, 4357 RParenLoc)); 4358 } 4359 if (Fn->getType() == Context.PseudoObjectTy) { 4360 ExprResult result = CheckPlaceholderExpr(Fn); 4361 if (result.isInvalid()) return ExprError(); 4362 Fn = result.take(); 4363 } 4364 4365 // Determine whether this is a dependent call inside a C++ template, 4366 // in which case we won't do any semantic analysis now. 4367 // FIXME: Will need to cache the results of name lookup (including ADL) in 4368 // Fn. 4369 bool Dependent = false; 4370 if (Fn->isTypeDependent()) 4371 Dependent = true; 4372 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4373 Dependent = true; 4374 4375 if (Dependent) { 4376 if (ExecConfig) { 4377 return Owned(new (Context) CUDAKernelCallExpr( 4378 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4379 Context.DependentTy, VK_RValue, RParenLoc)); 4380 } else { 4381 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4382 Context.DependentTy, VK_RValue, 4383 RParenLoc)); 4384 } 4385 } 4386 4387 // Determine whether this is a call to an object (C++ [over.call.object]). 4388 if (Fn->getType()->isRecordType()) 4389 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4390 ArgExprs, RParenLoc)); 4391 4392 if (Fn->getType() == Context.UnknownAnyTy) { 4393 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4394 if (result.isInvalid()) return ExprError(); 4395 Fn = result.take(); 4396 } 4397 4398 if (Fn->getType() == Context.BoundMemberTy) { 4399 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4400 } 4401 } 4402 4403 // Check for overloaded calls. This can happen even in C due to extensions. 4404 if (Fn->getType() == Context.OverloadTy) { 4405 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4406 4407 // We aren't supposed to apply this logic for if there's an '&' involved. 4408 if (!find.HasFormOfMemberPointer) { 4409 OverloadExpr *ovl = find.Expression; 4410 if (isa<UnresolvedLookupExpr>(ovl)) { 4411 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4412 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4413 RParenLoc, ExecConfig); 4414 } else { 4415 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4416 RParenLoc); 4417 } 4418 } 4419 } 4420 4421 // If we're directly calling a function, get the appropriate declaration. 4422 if (Fn->getType() == Context.UnknownAnyTy) { 4423 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4424 if (result.isInvalid()) return ExprError(); 4425 Fn = result.take(); 4426 } 4427 4428 Expr *NakedFn = Fn->IgnoreParens(); 4429 4430 NamedDecl *NDecl = 0; 4431 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4432 if (UnOp->getOpcode() == UO_AddrOf) 4433 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4434 4435 if (isa<DeclRefExpr>(NakedFn)) 4436 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4437 else if (isa<MemberExpr>(NakedFn)) 4438 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4439 4440 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4441 ExecConfig, IsExecConfig); 4442 } 4443 4444 ExprResult 4445 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4446 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4447 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4448 if (!ConfigDecl) 4449 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4450 << "cudaConfigureCall"); 4451 QualType ConfigQTy = ConfigDecl->getType(); 4452 4453 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4454 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4455 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4456 4457 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4458 /*IsExecConfig=*/true); 4459 } 4460 4461 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4462 /// 4463 /// __builtin_astype( value, dst type ) 4464 /// 4465 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4466 SourceLocation BuiltinLoc, 4467 SourceLocation RParenLoc) { 4468 ExprValueKind VK = VK_RValue; 4469 ExprObjectKind OK = OK_Ordinary; 4470 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4471 QualType SrcTy = E->getType(); 4472 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4473 return ExprError(Diag(BuiltinLoc, 4474 diag::err_invalid_astype_of_different_size) 4475 << DstTy 4476 << SrcTy 4477 << E->getSourceRange()); 4478 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4479 RParenLoc)); 4480 } 4481 4482 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4483 /// i.e. an expression not of \p OverloadTy. The expression should 4484 /// unary-convert to an expression of function-pointer or 4485 /// block-pointer type. 4486 /// 4487 /// \param NDecl the declaration being called, if available 4488 ExprResult 4489 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4490 SourceLocation LParenLoc, 4491 ArrayRef<Expr *> Args, 4492 SourceLocation RParenLoc, 4493 Expr *Config, bool IsExecConfig) { 4494 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4495 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4496 4497 // Promote the function operand. 4498 // We special-case function promotion here because we only allow promoting 4499 // builtin functions to function pointers in the callee of a call. 4500 ExprResult Result; 4501 if (BuiltinID && 4502 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4503 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4504 CK_BuiltinFnToFnPtr).take(); 4505 } else { 4506 Result = UsualUnaryConversions(Fn); 4507 } 4508 if (Result.isInvalid()) 4509 return ExprError(); 4510 Fn = Result.take(); 4511 4512 // Make the call expr early, before semantic checks. This guarantees cleanup 4513 // of arguments and function on error. 4514 CallExpr *TheCall; 4515 if (Config) 4516 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4517 cast<CallExpr>(Config), Args, 4518 Context.BoolTy, VK_RValue, 4519 RParenLoc); 4520 else 4521 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4522 VK_RValue, RParenLoc); 4523 4524 // Bail out early if calling a builtin with custom typechecking. 4525 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4526 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4527 4528 retry: 4529 const FunctionType *FuncT; 4530 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4531 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4532 // have type pointer to function". 4533 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4534 if (FuncT == 0) 4535 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4536 << Fn->getType() << Fn->getSourceRange()); 4537 } else if (const BlockPointerType *BPT = 4538 Fn->getType()->getAs<BlockPointerType>()) { 4539 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4540 } else { 4541 // Handle calls to expressions of unknown-any type. 4542 if (Fn->getType() == Context.UnknownAnyTy) { 4543 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4544 if (rewrite.isInvalid()) return ExprError(); 4545 Fn = rewrite.take(); 4546 TheCall->setCallee(Fn); 4547 goto retry; 4548 } 4549 4550 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4551 << Fn->getType() << Fn->getSourceRange()); 4552 } 4553 4554 if (getLangOpts().CUDA) { 4555 if (Config) { 4556 // CUDA: Kernel calls must be to global functions 4557 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4558 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4559 << FDecl->getName() << Fn->getSourceRange()); 4560 4561 // CUDA: Kernel function must have 'void' return type 4562 if (!FuncT->getResultType()->isVoidType()) 4563 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4564 << Fn->getType() << Fn->getSourceRange()); 4565 } else { 4566 // CUDA: Calls to global functions must be configured 4567 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4568 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4569 << FDecl->getName() << Fn->getSourceRange()); 4570 } 4571 } 4572 4573 // Check for a valid return type 4574 if (CheckCallReturnType(FuncT->getResultType(), 4575 Fn->getLocStart(), TheCall, 4576 FDecl)) 4577 return ExprError(); 4578 4579 // We know the result type of the call, set it. 4580 TheCall->setType(FuncT->getCallResultType(Context)); 4581 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4582 4583 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4584 if (Proto) { 4585 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4586 IsExecConfig)) 4587 return ExprError(); 4588 } else { 4589 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4590 4591 if (FDecl) { 4592 // Check if we have too few/too many template arguments, based 4593 // on our knowledge of the function definition. 4594 const FunctionDecl *Def = 0; 4595 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4596 Proto = Def->getType()->getAs<FunctionProtoType>(); 4597 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4598 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4599 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4600 } 4601 4602 // If the function we're calling isn't a function prototype, but we have 4603 // a function prototype from a prior declaratiom, use that prototype. 4604 if (!FDecl->hasPrototype()) 4605 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4606 } 4607 4608 // Promote the arguments (C99 6.5.2.2p6). 4609 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4610 Expr *Arg = Args[i]; 4611 4612 if (Proto && i < Proto->getNumArgs()) { 4613 InitializedEntity Entity 4614 = InitializedEntity::InitializeParameter(Context, 4615 Proto->getArgType(i), 4616 Proto->isArgConsumed(i)); 4617 ExprResult ArgE = PerformCopyInitialization(Entity, 4618 SourceLocation(), 4619 Owned(Arg)); 4620 if (ArgE.isInvalid()) 4621 return true; 4622 4623 Arg = ArgE.takeAs<Expr>(); 4624 4625 } else { 4626 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4627 4628 if (ArgE.isInvalid()) 4629 return true; 4630 4631 Arg = ArgE.takeAs<Expr>(); 4632 } 4633 4634 if (RequireCompleteType(Arg->getLocStart(), 4635 Arg->getType(), 4636 diag::err_call_incomplete_argument, Arg)) 4637 return ExprError(); 4638 4639 TheCall->setArg(i, Arg); 4640 } 4641 } 4642 4643 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4644 if (!Method->isStatic()) 4645 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4646 << Fn->getSourceRange()); 4647 4648 // Check for sentinels 4649 if (NDecl) 4650 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4651 4652 // Do special checking on direct calls to functions. 4653 if (FDecl) { 4654 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4655 return ExprError(); 4656 4657 if (BuiltinID) 4658 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4659 } else if (NDecl) { 4660 if (CheckPointerCall(NDecl, TheCall, Proto)) 4661 return ExprError(); 4662 } else { 4663 if (CheckOtherCall(TheCall, Proto)) 4664 return ExprError(); 4665 } 4666 4667 return MaybeBindToTemporary(TheCall); 4668 } 4669 4670 ExprResult 4671 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4672 SourceLocation RParenLoc, Expr *InitExpr) { 4673 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4674 // FIXME: put back this assert when initializers are worked out. 4675 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4676 4677 TypeSourceInfo *TInfo; 4678 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4679 if (!TInfo) 4680 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4681 4682 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4683 } 4684 4685 ExprResult 4686 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4687 SourceLocation RParenLoc, Expr *LiteralExpr) { 4688 QualType literalType = TInfo->getType(); 4689 4690 if (literalType->isArrayType()) { 4691 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4692 diag::err_illegal_decl_array_incomplete_type, 4693 SourceRange(LParenLoc, 4694 LiteralExpr->getSourceRange().getEnd()))) 4695 return ExprError(); 4696 if (literalType->isVariableArrayType()) 4697 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4698 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4699 } else if (!literalType->isDependentType() && 4700 RequireCompleteType(LParenLoc, literalType, 4701 diag::err_typecheck_decl_incomplete_type, 4702 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4703 return ExprError(); 4704 4705 InitializedEntity Entity 4706 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4707 InitializationKind Kind 4708 = InitializationKind::CreateCStyleCast(LParenLoc, 4709 SourceRange(LParenLoc, RParenLoc), 4710 /*InitList=*/true); 4711 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4712 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4713 &literalType); 4714 if (Result.isInvalid()) 4715 return ExprError(); 4716 LiteralExpr = Result.get(); 4717 4718 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4719 if (!getLangOpts().CPlusPlus && isFileScope) { // 6.5.2.5p3 4720 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4721 return ExprError(); 4722 } 4723 4724 // In C, compound literals are l-values for some reason. 4725 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4726 4727 return MaybeBindToTemporary( 4728 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4729 VK, LiteralExpr, isFileScope)); 4730 } 4731 4732 ExprResult 4733 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4734 SourceLocation RBraceLoc) { 4735 // Immediately handle non-overload placeholders. Overloads can be 4736 // resolved contextually, but everything else here can't. 4737 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4738 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4739 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4740 4741 // Ignore failures; dropping the entire initializer list because 4742 // of one failure would be terrible for indexing/etc. 4743 if (result.isInvalid()) continue; 4744 4745 InitArgList[I] = result.take(); 4746 } 4747 } 4748 4749 // Semantic analysis for initializers is done by ActOnDeclarator() and 4750 // CheckInitializer() - it requires knowledge of the object being intialized. 4751 4752 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4753 RBraceLoc); 4754 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4755 return Owned(E); 4756 } 4757 4758 /// Do an explicit extend of the given block pointer if we're in ARC. 4759 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4760 assert(E.get()->getType()->isBlockPointerType()); 4761 assert(E.get()->isRValue()); 4762 4763 // Only do this in an r-value context. 4764 if (!S.getLangOpts().ObjCAutoRefCount) return; 4765 4766 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4767 CK_ARCExtendBlockObject, E.get(), 4768 /*base path*/ 0, VK_RValue); 4769 S.ExprNeedsCleanups = true; 4770 } 4771 4772 /// Prepare a conversion of the given expression to an ObjC object 4773 /// pointer type. 4774 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4775 QualType type = E.get()->getType(); 4776 if (type->isObjCObjectPointerType()) { 4777 return CK_BitCast; 4778 } else if (type->isBlockPointerType()) { 4779 maybeExtendBlockObject(*this, E); 4780 return CK_BlockPointerToObjCPointerCast; 4781 } else { 4782 assert(type->isPointerType()); 4783 return CK_CPointerToObjCPointerCast; 4784 } 4785 } 4786 4787 /// Prepares for a scalar cast, performing all the necessary stages 4788 /// except the final cast and returning the kind required. 4789 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4790 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4791 // Also, callers should have filtered out the invalid cases with 4792 // pointers. Everything else should be possible. 4793 4794 QualType SrcTy = Src.get()->getType(); 4795 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4796 return CK_NoOp; 4797 4798 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4799 case Type::STK_MemberPointer: 4800 llvm_unreachable("member pointer type in C"); 4801 4802 case Type::STK_CPointer: 4803 case Type::STK_BlockPointer: 4804 case Type::STK_ObjCObjectPointer: 4805 switch (DestTy->getScalarTypeKind()) { 4806 case Type::STK_CPointer: 4807 return CK_BitCast; 4808 case Type::STK_BlockPointer: 4809 return (SrcKind == Type::STK_BlockPointer 4810 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4811 case Type::STK_ObjCObjectPointer: 4812 if (SrcKind == Type::STK_ObjCObjectPointer) 4813 return CK_BitCast; 4814 if (SrcKind == Type::STK_CPointer) 4815 return CK_CPointerToObjCPointerCast; 4816 maybeExtendBlockObject(*this, Src); 4817 return CK_BlockPointerToObjCPointerCast; 4818 case Type::STK_Bool: 4819 return CK_PointerToBoolean; 4820 case Type::STK_Integral: 4821 return CK_PointerToIntegral; 4822 case Type::STK_Floating: 4823 case Type::STK_FloatingComplex: 4824 case Type::STK_IntegralComplex: 4825 case Type::STK_MemberPointer: 4826 llvm_unreachable("illegal cast from pointer"); 4827 } 4828 llvm_unreachable("Should have returned before this"); 4829 4830 case Type::STK_Bool: // casting from bool is like casting from an integer 4831 case Type::STK_Integral: 4832 switch (DestTy->getScalarTypeKind()) { 4833 case Type::STK_CPointer: 4834 case Type::STK_ObjCObjectPointer: 4835 case Type::STK_BlockPointer: 4836 if (Src.get()->isNullPointerConstant(Context, 4837 Expr::NPC_ValueDependentIsNull)) 4838 return CK_NullToPointer; 4839 return CK_IntegralToPointer; 4840 case Type::STK_Bool: 4841 return CK_IntegralToBoolean; 4842 case Type::STK_Integral: 4843 return CK_IntegralCast; 4844 case Type::STK_Floating: 4845 return CK_IntegralToFloating; 4846 case Type::STK_IntegralComplex: 4847 Src = ImpCastExprToType(Src.take(), 4848 DestTy->castAs<ComplexType>()->getElementType(), 4849 CK_IntegralCast); 4850 return CK_IntegralRealToComplex; 4851 case Type::STK_FloatingComplex: 4852 Src = ImpCastExprToType(Src.take(), 4853 DestTy->castAs<ComplexType>()->getElementType(), 4854 CK_IntegralToFloating); 4855 return CK_FloatingRealToComplex; 4856 case Type::STK_MemberPointer: 4857 llvm_unreachable("member pointer type in C"); 4858 } 4859 llvm_unreachable("Should have returned before this"); 4860 4861 case Type::STK_Floating: 4862 switch (DestTy->getScalarTypeKind()) { 4863 case Type::STK_Floating: 4864 return CK_FloatingCast; 4865 case Type::STK_Bool: 4866 return CK_FloatingToBoolean; 4867 case Type::STK_Integral: 4868 return CK_FloatingToIntegral; 4869 case Type::STK_FloatingComplex: 4870 Src = ImpCastExprToType(Src.take(), 4871 DestTy->castAs<ComplexType>()->getElementType(), 4872 CK_FloatingCast); 4873 return CK_FloatingRealToComplex; 4874 case Type::STK_IntegralComplex: 4875 Src = ImpCastExprToType(Src.take(), 4876 DestTy->castAs<ComplexType>()->getElementType(), 4877 CK_FloatingToIntegral); 4878 return CK_IntegralRealToComplex; 4879 case Type::STK_CPointer: 4880 case Type::STK_ObjCObjectPointer: 4881 case Type::STK_BlockPointer: 4882 llvm_unreachable("valid float->pointer cast?"); 4883 case Type::STK_MemberPointer: 4884 llvm_unreachable("member pointer type in C"); 4885 } 4886 llvm_unreachable("Should have returned before this"); 4887 4888 case Type::STK_FloatingComplex: 4889 switch (DestTy->getScalarTypeKind()) { 4890 case Type::STK_FloatingComplex: 4891 return CK_FloatingComplexCast; 4892 case Type::STK_IntegralComplex: 4893 return CK_FloatingComplexToIntegralComplex; 4894 case Type::STK_Floating: { 4895 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4896 if (Context.hasSameType(ET, DestTy)) 4897 return CK_FloatingComplexToReal; 4898 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4899 return CK_FloatingCast; 4900 } 4901 case Type::STK_Bool: 4902 return CK_FloatingComplexToBoolean; 4903 case Type::STK_Integral: 4904 Src = ImpCastExprToType(Src.take(), 4905 SrcTy->castAs<ComplexType>()->getElementType(), 4906 CK_FloatingComplexToReal); 4907 return CK_FloatingToIntegral; 4908 case Type::STK_CPointer: 4909 case Type::STK_ObjCObjectPointer: 4910 case Type::STK_BlockPointer: 4911 llvm_unreachable("valid complex float->pointer cast?"); 4912 case Type::STK_MemberPointer: 4913 llvm_unreachable("member pointer type in C"); 4914 } 4915 llvm_unreachable("Should have returned before this"); 4916 4917 case Type::STK_IntegralComplex: 4918 switch (DestTy->getScalarTypeKind()) { 4919 case Type::STK_FloatingComplex: 4920 return CK_IntegralComplexToFloatingComplex; 4921 case Type::STK_IntegralComplex: 4922 return CK_IntegralComplexCast; 4923 case Type::STK_Integral: { 4924 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4925 if (Context.hasSameType(ET, DestTy)) 4926 return CK_IntegralComplexToReal; 4927 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4928 return CK_IntegralCast; 4929 } 4930 case Type::STK_Bool: 4931 return CK_IntegralComplexToBoolean; 4932 case Type::STK_Floating: 4933 Src = ImpCastExprToType(Src.take(), 4934 SrcTy->castAs<ComplexType>()->getElementType(), 4935 CK_IntegralComplexToReal); 4936 return CK_IntegralToFloating; 4937 case Type::STK_CPointer: 4938 case Type::STK_ObjCObjectPointer: 4939 case Type::STK_BlockPointer: 4940 llvm_unreachable("valid complex int->pointer cast?"); 4941 case Type::STK_MemberPointer: 4942 llvm_unreachable("member pointer type in C"); 4943 } 4944 llvm_unreachable("Should have returned before this"); 4945 } 4946 4947 llvm_unreachable("Unhandled scalar cast"); 4948 } 4949 4950 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4951 CastKind &Kind) { 4952 assert(VectorTy->isVectorType() && "Not a vector type!"); 4953 4954 if (Ty->isVectorType() || Ty->isIntegerType()) { 4955 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4956 return Diag(R.getBegin(), 4957 Ty->isVectorType() ? 4958 diag::err_invalid_conversion_between_vectors : 4959 diag::err_invalid_conversion_between_vector_and_integer) 4960 << VectorTy << Ty << R; 4961 } else 4962 return Diag(R.getBegin(), 4963 diag::err_invalid_conversion_between_vector_and_scalar) 4964 << VectorTy << Ty << R; 4965 4966 Kind = CK_BitCast; 4967 return false; 4968 } 4969 4970 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4971 Expr *CastExpr, CastKind &Kind) { 4972 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4973 4974 QualType SrcTy = CastExpr->getType(); 4975 4976 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4977 // an ExtVectorType. 4978 // In OpenCL, casts between vectors of different types are not allowed. 4979 // (See OpenCL 6.2). 4980 if (SrcTy->isVectorType()) { 4981 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4982 || (getLangOpts().OpenCL && 4983 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4984 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4985 << DestTy << SrcTy << R; 4986 return ExprError(); 4987 } 4988 Kind = CK_BitCast; 4989 return Owned(CastExpr); 4990 } 4991 4992 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4993 // conversion will take place first from scalar to elt type, and then 4994 // splat from elt type to vector. 4995 if (SrcTy->isPointerType()) 4996 return Diag(R.getBegin(), 4997 diag::err_invalid_conversion_between_vector_and_scalar) 4998 << DestTy << SrcTy << R; 4999 5000 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5001 ExprResult CastExprRes = Owned(CastExpr); 5002 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5003 if (CastExprRes.isInvalid()) 5004 return ExprError(); 5005 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5006 5007 Kind = CK_VectorSplat; 5008 return Owned(CastExpr); 5009 } 5010 5011 ExprResult 5012 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5013 Declarator &D, ParsedType &Ty, 5014 SourceLocation RParenLoc, Expr *CastExpr) { 5015 assert(!D.isInvalidType() && (CastExpr != 0) && 5016 "ActOnCastExpr(): missing type or expr"); 5017 5018 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5019 if (D.isInvalidType()) 5020 return ExprError(); 5021 5022 if (getLangOpts().CPlusPlus) { 5023 // Check that there are no default arguments (C++ only). 5024 CheckExtraCXXDefaultArguments(D); 5025 } 5026 5027 checkUnusedDeclAttributes(D); 5028 5029 QualType castType = castTInfo->getType(); 5030 Ty = CreateParsedType(castType, castTInfo); 5031 5032 bool isVectorLiteral = false; 5033 5034 // Check for an altivec or OpenCL literal, 5035 // i.e. all the elements are integer constants. 5036 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5037 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5038 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5039 && castType->isVectorType() && (PE || PLE)) { 5040 if (PLE && PLE->getNumExprs() == 0) { 5041 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5042 return ExprError(); 5043 } 5044 if (PE || PLE->getNumExprs() == 1) { 5045 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5046 if (!E->getType()->isVectorType()) 5047 isVectorLiteral = true; 5048 } 5049 else 5050 isVectorLiteral = true; 5051 } 5052 5053 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5054 // then handle it as such. 5055 if (isVectorLiteral) 5056 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5057 5058 // If the Expr being casted is a ParenListExpr, handle it specially. 5059 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5060 // sequence of BinOp comma operators. 5061 if (isa<ParenListExpr>(CastExpr)) { 5062 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5063 if (Result.isInvalid()) return ExprError(); 5064 CastExpr = Result.take(); 5065 } 5066 5067 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5068 } 5069 5070 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5071 SourceLocation RParenLoc, Expr *E, 5072 TypeSourceInfo *TInfo) { 5073 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5074 "Expected paren or paren list expression"); 5075 5076 Expr **exprs; 5077 unsigned numExprs; 5078 Expr *subExpr; 5079 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5080 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5081 LiteralLParenLoc = PE->getLParenLoc(); 5082 LiteralRParenLoc = PE->getRParenLoc(); 5083 exprs = PE->getExprs(); 5084 numExprs = PE->getNumExprs(); 5085 } else { // isa<ParenExpr> by assertion at function entrance 5086 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5087 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5088 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5089 exprs = &subExpr; 5090 numExprs = 1; 5091 } 5092 5093 QualType Ty = TInfo->getType(); 5094 assert(Ty->isVectorType() && "Expected vector type"); 5095 5096 SmallVector<Expr *, 8> initExprs; 5097 const VectorType *VTy = Ty->getAs<VectorType>(); 5098 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5099 5100 // '(...)' form of vector initialization in AltiVec: the number of 5101 // initializers must be one or must match the size of the vector. 5102 // If a single value is specified in the initializer then it will be 5103 // replicated to all the components of the vector 5104 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5105 // The number of initializers must be one or must match the size of the 5106 // vector. If a single value is specified in the initializer then it will 5107 // be replicated to all the components of the vector 5108 if (numExprs == 1) { 5109 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5110 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5111 if (Literal.isInvalid()) 5112 return ExprError(); 5113 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5114 PrepareScalarCast(Literal, ElemTy)); 5115 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5116 } 5117 else if (numExprs < numElems) { 5118 Diag(E->getExprLoc(), 5119 diag::err_incorrect_number_of_vector_initializers); 5120 return ExprError(); 5121 } 5122 else 5123 initExprs.append(exprs, exprs + numExprs); 5124 } 5125 else { 5126 // For OpenCL, when the number of initializers is a single value, 5127 // it will be replicated to all components of the vector. 5128 if (getLangOpts().OpenCL && 5129 VTy->getVectorKind() == VectorType::GenericVector && 5130 numExprs == 1) { 5131 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5132 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5133 if (Literal.isInvalid()) 5134 return ExprError(); 5135 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5136 PrepareScalarCast(Literal, ElemTy)); 5137 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5138 } 5139 5140 initExprs.append(exprs, exprs + numExprs); 5141 } 5142 // FIXME: This means that pretty-printing the final AST will produce curly 5143 // braces instead of the original commas. 5144 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5145 initExprs, LiteralRParenLoc); 5146 initE->setType(Ty); 5147 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5148 } 5149 5150 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5151 /// the ParenListExpr into a sequence of comma binary operators. 5152 ExprResult 5153 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5154 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5155 if (!E) 5156 return Owned(OrigExpr); 5157 5158 ExprResult Result(E->getExpr(0)); 5159 5160 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5161 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5162 E->getExpr(i)); 5163 5164 if (Result.isInvalid()) return ExprError(); 5165 5166 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5167 } 5168 5169 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5170 SourceLocation R, 5171 MultiExprArg Val) { 5172 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5173 return Owned(expr); 5174 } 5175 5176 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5177 /// constant and the other is not a pointer. Returns true if a diagnostic is 5178 /// emitted. 5179 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5180 SourceLocation QuestionLoc) { 5181 Expr *NullExpr = LHSExpr; 5182 Expr *NonPointerExpr = RHSExpr; 5183 Expr::NullPointerConstantKind NullKind = 5184 NullExpr->isNullPointerConstant(Context, 5185 Expr::NPC_ValueDependentIsNotNull); 5186 5187 if (NullKind == Expr::NPCK_NotNull) { 5188 NullExpr = RHSExpr; 5189 NonPointerExpr = LHSExpr; 5190 NullKind = 5191 NullExpr->isNullPointerConstant(Context, 5192 Expr::NPC_ValueDependentIsNotNull); 5193 } 5194 5195 if (NullKind == Expr::NPCK_NotNull) 5196 return false; 5197 5198 if (NullKind == Expr::NPCK_ZeroExpression) 5199 return false; 5200 5201 if (NullKind == Expr::NPCK_ZeroLiteral) { 5202 // In this case, check to make sure that we got here from a "NULL" 5203 // string in the source code. 5204 NullExpr = NullExpr->IgnoreParenImpCasts(); 5205 SourceLocation loc = NullExpr->getExprLoc(); 5206 if (!findMacroSpelling(loc, "NULL")) 5207 return false; 5208 } 5209 5210 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5211 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5212 << NonPointerExpr->getType() << DiagType 5213 << NonPointerExpr->getSourceRange(); 5214 return true; 5215 } 5216 5217 /// \brief Return false if the condition expression is valid, true otherwise. 5218 static bool checkCondition(Sema &S, Expr *Cond) { 5219 QualType CondTy = Cond->getType(); 5220 5221 // C99 6.5.15p2 5222 if (CondTy->isScalarType()) return false; 5223 5224 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5225 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5226 return false; 5227 5228 // Emit the proper error message. 5229 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5230 diag::err_typecheck_cond_expect_scalar : 5231 diag::err_typecheck_cond_expect_scalar_or_vector) 5232 << CondTy; 5233 return true; 5234 } 5235 5236 /// \brief Return false if the two expressions can be converted to a vector, 5237 /// true otherwise 5238 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5239 ExprResult &RHS, 5240 QualType CondTy) { 5241 // Both operands should be of scalar type. 5242 if (!LHS.get()->getType()->isScalarType()) { 5243 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5244 << CondTy; 5245 return true; 5246 } 5247 if (!RHS.get()->getType()->isScalarType()) { 5248 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5249 << CondTy; 5250 return true; 5251 } 5252 5253 // Implicity convert these scalars to the type of the condition. 5254 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5255 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5256 return false; 5257 } 5258 5259 /// \brief Handle when one or both operands are void type. 5260 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5261 ExprResult &RHS) { 5262 Expr *LHSExpr = LHS.get(); 5263 Expr *RHSExpr = RHS.get(); 5264 5265 if (!LHSExpr->getType()->isVoidType()) 5266 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5267 << RHSExpr->getSourceRange(); 5268 if (!RHSExpr->getType()->isVoidType()) 5269 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5270 << LHSExpr->getSourceRange(); 5271 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5272 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5273 return S.Context.VoidTy; 5274 } 5275 5276 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5277 /// true otherwise. 5278 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5279 QualType PointerTy) { 5280 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5281 !NullExpr.get()->isNullPointerConstant(S.Context, 5282 Expr::NPC_ValueDependentIsNull)) 5283 return true; 5284 5285 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5286 return false; 5287 } 5288 5289 /// \brief Checks compatibility between two pointers and return the resulting 5290 /// type. 5291 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5292 ExprResult &RHS, 5293 SourceLocation Loc) { 5294 QualType LHSTy = LHS.get()->getType(); 5295 QualType RHSTy = RHS.get()->getType(); 5296 5297 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5298 // Two identical pointers types are always compatible. 5299 return LHSTy; 5300 } 5301 5302 QualType lhptee, rhptee; 5303 5304 // Get the pointee types. 5305 bool IsBlockPointer = false; 5306 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5307 lhptee = LHSBTy->getPointeeType(); 5308 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5309 IsBlockPointer = true; 5310 } else { 5311 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5312 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5313 } 5314 5315 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5316 // differently qualified versions of compatible types, the result type is 5317 // a pointer to an appropriately qualified version of the composite 5318 // type. 5319 5320 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5321 // clause doesn't make sense for our extensions. E.g. address space 2 should 5322 // be incompatible with address space 3: they may live on different devices or 5323 // anything. 5324 Qualifiers lhQual = lhptee.getQualifiers(); 5325 Qualifiers rhQual = rhptee.getQualifiers(); 5326 5327 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5328 lhQual.removeCVRQualifiers(); 5329 rhQual.removeCVRQualifiers(); 5330 5331 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5332 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5333 5334 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5335 5336 if (CompositeTy.isNull()) { 5337 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5338 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5339 << RHS.get()->getSourceRange(); 5340 // In this situation, we assume void* type. No especially good 5341 // reason, but this is what gcc does, and we do have to pick 5342 // to get a consistent AST. 5343 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5344 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5345 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5346 return incompatTy; 5347 } 5348 5349 // The pointer types are compatible. 5350 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5351 if (IsBlockPointer) 5352 ResultTy = S.Context.getBlockPointerType(ResultTy); 5353 else 5354 ResultTy = S.Context.getPointerType(ResultTy); 5355 5356 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5357 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5358 return ResultTy; 5359 } 5360 5361 /// \brief Return the resulting type when the operands are both block pointers. 5362 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5363 ExprResult &LHS, 5364 ExprResult &RHS, 5365 SourceLocation Loc) { 5366 QualType LHSTy = LHS.get()->getType(); 5367 QualType RHSTy = RHS.get()->getType(); 5368 5369 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5370 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5371 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5372 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5373 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5374 return destType; 5375 } 5376 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5377 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5378 << RHS.get()->getSourceRange(); 5379 return QualType(); 5380 } 5381 5382 // We have 2 block pointer types. 5383 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5384 } 5385 5386 /// \brief Return the resulting type when the operands are both pointers. 5387 static QualType 5388 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5389 ExprResult &RHS, 5390 SourceLocation Loc) { 5391 // get the pointer types 5392 QualType LHSTy = LHS.get()->getType(); 5393 QualType RHSTy = RHS.get()->getType(); 5394 5395 // get the "pointed to" types 5396 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5397 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5398 5399 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5400 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5401 // Figure out necessary qualifiers (C99 6.5.15p6) 5402 QualType destPointee 5403 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5404 QualType destType = S.Context.getPointerType(destPointee); 5405 // Add qualifiers if necessary. 5406 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5407 // Promote to void*. 5408 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5409 return destType; 5410 } 5411 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5412 QualType destPointee 5413 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5414 QualType destType = S.Context.getPointerType(destPointee); 5415 // Add qualifiers if necessary. 5416 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5417 // Promote to void*. 5418 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5419 return destType; 5420 } 5421 5422 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5423 } 5424 5425 /// \brief Return false if the first expression is not an integer and the second 5426 /// expression is not a pointer, true otherwise. 5427 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5428 Expr* PointerExpr, SourceLocation Loc, 5429 bool IsIntFirstExpr) { 5430 if (!PointerExpr->getType()->isPointerType() || 5431 !Int.get()->getType()->isIntegerType()) 5432 return false; 5433 5434 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5435 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5436 5437 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5438 << Expr1->getType() << Expr2->getType() 5439 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5440 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5441 CK_IntegralToPointer); 5442 return true; 5443 } 5444 5445 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5446 /// In that case, LHS = cond. 5447 /// C99 6.5.15 5448 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5449 ExprResult &RHS, ExprValueKind &VK, 5450 ExprObjectKind &OK, 5451 SourceLocation QuestionLoc) { 5452 5453 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5454 if (!LHSResult.isUsable()) return QualType(); 5455 LHS = LHSResult; 5456 5457 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5458 if (!RHSResult.isUsable()) return QualType(); 5459 RHS = RHSResult; 5460 5461 // C++ is sufficiently different to merit its own checker. 5462 if (getLangOpts().CPlusPlus) 5463 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5464 5465 VK = VK_RValue; 5466 OK = OK_Ordinary; 5467 5468 Cond = UsualUnaryConversions(Cond.take()); 5469 if (Cond.isInvalid()) 5470 return QualType(); 5471 UsualArithmeticConversions(LHS, RHS); 5472 if (LHS.isInvalid() || RHS.isInvalid()) 5473 return QualType(); 5474 5475 QualType CondTy = Cond.get()->getType(); 5476 QualType LHSTy = LHS.get()->getType(); 5477 QualType RHSTy = RHS.get()->getType(); 5478 5479 // first, check the condition. 5480 if (checkCondition(*this, Cond.get())) 5481 return QualType(); 5482 5483 // Now check the two expressions. 5484 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5485 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5486 5487 // If the condition is a vector, and both operands are scalar, 5488 // attempt to implicity convert them to the vector type to act like the 5489 // built in select. (OpenCL v1.1 s6.3.i) 5490 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5491 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5492 return QualType(); 5493 5494 // If both operands have arithmetic type, do the usual arithmetic conversions 5495 // to find a common type: C99 6.5.15p3,5. 5496 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5497 return LHS.get()->getType(); 5498 5499 // If both operands are the same structure or union type, the result is that 5500 // type. 5501 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5502 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5503 if (LHSRT->getDecl() == RHSRT->getDecl()) 5504 // "If both the operands have structure or union type, the result has 5505 // that type." This implies that CV qualifiers are dropped. 5506 return LHSTy.getUnqualifiedType(); 5507 // FIXME: Type of conditional expression must be complete in C mode. 5508 } 5509 5510 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5511 // The following || allows only one side to be void (a GCC-ism). 5512 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5513 return checkConditionalVoidType(*this, LHS, RHS); 5514 } 5515 5516 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5517 // the type of the other operand." 5518 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5519 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5520 5521 // All objective-c pointer type analysis is done here. 5522 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5523 QuestionLoc); 5524 if (LHS.isInvalid() || RHS.isInvalid()) 5525 return QualType(); 5526 if (!compositeType.isNull()) 5527 return compositeType; 5528 5529 5530 // Handle block pointer types. 5531 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5532 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5533 QuestionLoc); 5534 5535 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5536 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5537 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5538 QuestionLoc); 5539 5540 // GCC compatibility: soften pointer/integer mismatch. Note that 5541 // null pointers have been filtered out by this point. 5542 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5543 /*isIntFirstExpr=*/true)) 5544 return RHSTy; 5545 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5546 /*isIntFirstExpr=*/false)) 5547 return LHSTy; 5548 5549 // Emit a better diagnostic if one of the expressions is a null pointer 5550 // constant and the other is not a pointer type. In this case, the user most 5551 // likely forgot to take the address of the other expression. 5552 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5553 return QualType(); 5554 5555 // Otherwise, the operands are not compatible. 5556 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5557 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5558 << RHS.get()->getSourceRange(); 5559 return QualType(); 5560 } 5561 5562 /// FindCompositeObjCPointerType - Helper method to find composite type of 5563 /// two objective-c pointer types of the two input expressions. 5564 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5565 SourceLocation QuestionLoc) { 5566 QualType LHSTy = LHS.get()->getType(); 5567 QualType RHSTy = RHS.get()->getType(); 5568 5569 // Handle things like Class and struct objc_class*. Here we case the result 5570 // to the pseudo-builtin, because that will be implicitly cast back to the 5571 // redefinition type if an attempt is made to access its fields. 5572 if (LHSTy->isObjCClassType() && 5573 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5574 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5575 return LHSTy; 5576 } 5577 if (RHSTy->isObjCClassType() && 5578 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5579 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5580 return RHSTy; 5581 } 5582 // And the same for struct objc_object* / id 5583 if (LHSTy->isObjCIdType() && 5584 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5585 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5586 return LHSTy; 5587 } 5588 if (RHSTy->isObjCIdType() && 5589 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5590 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5591 return RHSTy; 5592 } 5593 // And the same for struct objc_selector* / SEL 5594 if (Context.isObjCSelType(LHSTy) && 5595 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5596 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5597 return LHSTy; 5598 } 5599 if (Context.isObjCSelType(RHSTy) && 5600 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5601 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5602 return RHSTy; 5603 } 5604 // Check constraints for Objective-C object pointers types. 5605 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5606 5607 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5608 // Two identical object pointer types are always compatible. 5609 return LHSTy; 5610 } 5611 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5612 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5613 QualType compositeType = LHSTy; 5614 5615 // If both operands are interfaces and either operand can be 5616 // assigned to the other, use that type as the composite 5617 // type. This allows 5618 // xxx ? (A*) a : (B*) b 5619 // where B is a subclass of A. 5620 // 5621 // Additionally, as for assignment, if either type is 'id' 5622 // allow silent coercion. Finally, if the types are 5623 // incompatible then make sure to use 'id' as the composite 5624 // type so the result is acceptable for sending messages to. 5625 5626 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5627 // It could return the composite type. 5628 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5629 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5630 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5631 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5632 } else if ((LHSTy->isObjCQualifiedIdType() || 5633 RHSTy->isObjCQualifiedIdType()) && 5634 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5635 // Need to handle "id<xx>" explicitly. 5636 // GCC allows qualified id and any Objective-C type to devolve to 5637 // id. Currently localizing to here until clear this should be 5638 // part of ObjCQualifiedIdTypesAreCompatible. 5639 compositeType = Context.getObjCIdType(); 5640 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5641 compositeType = Context.getObjCIdType(); 5642 } else if (!(compositeType = 5643 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5644 ; 5645 else { 5646 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5647 << LHSTy << RHSTy 5648 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5649 QualType incompatTy = Context.getObjCIdType(); 5650 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5651 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5652 return incompatTy; 5653 } 5654 // The object pointer types are compatible. 5655 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5656 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5657 return compositeType; 5658 } 5659 // Check Objective-C object pointer types and 'void *' 5660 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5661 if (getLangOpts().ObjCAutoRefCount) { 5662 // ARC forbids the implicit conversion of object pointers to 'void *', 5663 // so these types are not compatible. 5664 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5665 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5666 LHS = RHS = true; 5667 return QualType(); 5668 } 5669 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5670 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5671 QualType destPointee 5672 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5673 QualType destType = Context.getPointerType(destPointee); 5674 // Add qualifiers if necessary. 5675 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5676 // Promote to void*. 5677 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5678 return destType; 5679 } 5680 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5681 if (getLangOpts().ObjCAutoRefCount) { 5682 // ARC forbids the implicit conversion of object pointers to 'void *', 5683 // so these types are not compatible. 5684 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5685 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5686 LHS = RHS = true; 5687 return QualType(); 5688 } 5689 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5690 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5691 QualType destPointee 5692 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5693 QualType destType = Context.getPointerType(destPointee); 5694 // Add qualifiers if necessary. 5695 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5696 // Promote to void*. 5697 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5698 return destType; 5699 } 5700 return QualType(); 5701 } 5702 5703 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5704 /// ParenRange in parentheses. 5705 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5706 const PartialDiagnostic &Note, 5707 SourceRange ParenRange) { 5708 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5709 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5710 EndLoc.isValid()) { 5711 Self.Diag(Loc, Note) 5712 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5713 << FixItHint::CreateInsertion(EndLoc, ")"); 5714 } else { 5715 // We can't display the parentheses, so just show the bare note. 5716 Self.Diag(Loc, Note) << ParenRange; 5717 } 5718 } 5719 5720 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5721 return Opc >= BO_Mul && Opc <= BO_Shr; 5722 } 5723 5724 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5725 /// expression, either using a built-in or overloaded operator, 5726 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5727 /// expression. 5728 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5729 Expr **RHSExprs) { 5730 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5731 E = E->IgnoreImpCasts(); 5732 E = E->IgnoreConversionOperator(); 5733 E = E->IgnoreImpCasts(); 5734 5735 // Built-in binary operator. 5736 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5737 if (IsArithmeticOp(OP->getOpcode())) { 5738 *Opcode = OP->getOpcode(); 5739 *RHSExprs = OP->getRHS(); 5740 return true; 5741 } 5742 } 5743 5744 // Overloaded operator. 5745 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5746 if (Call->getNumArgs() != 2) 5747 return false; 5748 5749 // Make sure this is really a binary operator that is safe to pass into 5750 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5751 OverloadedOperatorKind OO = Call->getOperator(); 5752 if (OO < OO_Plus || OO > OO_Arrow || 5753 OO == OO_PlusPlus || OO == OO_MinusMinus) 5754 return false; 5755 5756 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5757 if (IsArithmeticOp(OpKind)) { 5758 *Opcode = OpKind; 5759 *RHSExprs = Call->getArg(1); 5760 return true; 5761 } 5762 } 5763 5764 return false; 5765 } 5766 5767 static bool IsLogicOp(BinaryOperatorKind Opc) { 5768 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5769 } 5770 5771 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5772 /// or is a logical expression such as (x==y) which has int type, but is 5773 /// commonly interpreted as boolean. 5774 static bool ExprLooksBoolean(Expr *E) { 5775 E = E->IgnoreParenImpCasts(); 5776 5777 if (E->getType()->isBooleanType()) 5778 return true; 5779 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5780 return IsLogicOp(OP->getOpcode()); 5781 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5782 return OP->getOpcode() == UO_LNot; 5783 5784 return false; 5785 } 5786 5787 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5788 /// and binary operator are mixed in a way that suggests the programmer assumed 5789 /// the conditional operator has higher precedence, for example: 5790 /// "int x = a + someBinaryCondition ? 1 : 2". 5791 static void DiagnoseConditionalPrecedence(Sema &Self, 5792 SourceLocation OpLoc, 5793 Expr *Condition, 5794 Expr *LHSExpr, 5795 Expr *RHSExpr) { 5796 BinaryOperatorKind CondOpcode; 5797 Expr *CondRHS; 5798 5799 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5800 return; 5801 if (!ExprLooksBoolean(CondRHS)) 5802 return; 5803 5804 // The condition is an arithmetic binary expression, with a right- 5805 // hand side that looks boolean, so warn. 5806 5807 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5808 << Condition->getSourceRange() 5809 << BinaryOperator::getOpcodeStr(CondOpcode); 5810 5811 SuggestParentheses(Self, OpLoc, 5812 Self.PDiag(diag::note_precedence_silence) 5813 << BinaryOperator::getOpcodeStr(CondOpcode), 5814 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5815 5816 SuggestParentheses(Self, OpLoc, 5817 Self.PDiag(diag::note_precedence_conditional_first), 5818 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5819 } 5820 5821 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5822 /// in the case of a the GNU conditional expr extension. 5823 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5824 SourceLocation ColonLoc, 5825 Expr *CondExpr, Expr *LHSExpr, 5826 Expr *RHSExpr) { 5827 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5828 // was the condition. 5829 OpaqueValueExpr *opaqueValue = 0; 5830 Expr *commonExpr = 0; 5831 if (LHSExpr == 0) { 5832 commonExpr = CondExpr; 5833 // Lower out placeholder types first. This is important so that we don't 5834 // try to capture a placeholder. This happens in few cases in C++; such 5835 // as Objective-C++'s dictionary subscripting syntax. 5836 if (commonExpr->hasPlaceholderType()) { 5837 ExprResult result = CheckPlaceholderExpr(commonExpr); 5838 if (!result.isUsable()) return ExprError(); 5839 commonExpr = result.take(); 5840 } 5841 // We usually want to apply unary conversions *before* saving, except 5842 // in the special case of a C++ l-value conditional. 5843 if (!(getLangOpts().CPlusPlus 5844 && !commonExpr->isTypeDependent() 5845 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5846 && commonExpr->isGLValue() 5847 && commonExpr->isOrdinaryOrBitFieldObject() 5848 && RHSExpr->isOrdinaryOrBitFieldObject() 5849 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5850 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5851 if (commonRes.isInvalid()) 5852 return ExprError(); 5853 commonExpr = commonRes.take(); 5854 } 5855 5856 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5857 commonExpr->getType(), 5858 commonExpr->getValueKind(), 5859 commonExpr->getObjectKind(), 5860 commonExpr); 5861 LHSExpr = CondExpr = opaqueValue; 5862 } 5863 5864 ExprValueKind VK = VK_RValue; 5865 ExprObjectKind OK = OK_Ordinary; 5866 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5867 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5868 VK, OK, QuestionLoc); 5869 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5870 RHS.isInvalid()) 5871 return ExprError(); 5872 5873 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5874 RHS.get()); 5875 5876 if (!commonExpr) 5877 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5878 LHS.take(), ColonLoc, 5879 RHS.take(), result, VK, OK)); 5880 5881 return Owned(new (Context) 5882 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5883 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5884 OK)); 5885 } 5886 5887 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5888 // being closely modeled after the C99 spec:-). The odd characteristic of this 5889 // routine is it effectively iqnores the qualifiers on the top level pointee. 5890 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5891 // FIXME: add a couple examples in this comment. 5892 static Sema::AssignConvertType 5893 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5894 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5895 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5896 5897 // get the "pointed to" type (ignoring qualifiers at the top level) 5898 const Type *lhptee, *rhptee; 5899 Qualifiers lhq, rhq; 5900 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5901 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5902 5903 Sema::AssignConvertType ConvTy = Sema::Compatible; 5904 5905 // C99 6.5.16.1p1: This following citation is common to constraints 5906 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5907 // qualifiers of the type *pointed to* by the right; 5908 Qualifiers lq; 5909 5910 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5911 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5912 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5913 // Ignore lifetime for further calculation. 5914 lhq.removeObjCLifetime(); 5915 rhq.removeObjCLifetime(); 5916 } 5917 5918 if (!lhq.compatiblyIncludes(rhq)) { 5919 // Treat address-space mismatches as fatal. TODO: address subspaces 5920 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5921 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5922 5923 // It's okay to add or remove GC or lifetime qualifiers when converting to 5924 // and from void*. 5925 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5926 .compatiblyIncludes( 5927 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5928 && (lhptee->isVoidType() || rhptee->isVoidType())) 5929 ; // keep old 5930 5931 // Treat lifetime mismatches as fatal. 5932 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5933 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5934 5935 // For GCC compatibility, other qualifier mismatches are treated 5936 // as still compatible in C. 5937 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5938 } 5939 5940 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5941 // incomplete type and the other is a pointer to a qualified or unqualified 5942 // version of void... 5943 if (lhptee->isVoidType()) { 5944 if (rhptee->isIncompleteOrObjectType()) 5945 return ConvTy; 5946 5947 // As an extension, we allow cast to/from void* to function pointer. 5948 assert(rhptee->isFunctionType()); 5949 return Sema::FunctionVoidPointer; 5950 } 5951 5952 if (rhptee->isVoidType()) { 5953 if (lhptee->isIncompleteOrObjectType()) 5954 return ConvTy; 5955 5956 // As an extension, we allow cast to/from void* to function pointer. 5957 assert(lhptee->isFunctionType()); 5958 return Sema::FunctionVoidPointer; 5959 } 5960 5961 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5962 // unqualified versions of compatible types, ... 5963 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5964 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5965 // Check if the pointee types are compatible ignoring the sign. 5966 // We explicitly check for char so that we catch "char" vs 5967 // "unsigned char" on systems where "char" is unsigned. 5968 if (lhptee->isCharType()) 5969 ltrans = S.Context.UnsignedCharTy; 5970 else if (lhptee->hasSignedIntegerRepresentation()) 5971 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5972 5973 if (rhptee->isCharType()) 5974 rtrans = S.Context.UnsignedCharTy; 5975 else if (rhptee->hasSignedIntegerRepresentation()) 5976 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5977 5978 if (ltrans == rtrans) { 5979 // Types are compatible ignoring the sign. Qualifier incompatibility 5980 // takes priority over sign incompatibility because the sign 5981 // warning can be disabled. 5982 if (ConvTy != Sema::Compatible) 5983 return ConvTy; 5984 5985 return Sema::IncompatiblePointerSign; 5986 } 5987 5988 // If we are a multi-level pointer, it's possible that our issue is simply 5989 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5990 // the eventual target type is the same and the pointers have the same 5991 // level of indirection, this must be the issue. 5992 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5993 do { 5994 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5995 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5996 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5997 5998 if (lhptee == rhptee) 5999 return Sema::IncompatibleNestedPointerQualifiers; 6000 } 6001 6002 // General pointer incompatibility takes priority over qualifiers. 6003 return Sema::IncompatiblePointer; 6004 } 6005 if (!S.getLangOpts().CPlusPlus && 6006 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6007 return Sema::IncompatiblePointer; 6008 return ConvTy; 6009 } 6010 6011 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6012 /// block pointer types are compatible or whether a block and normal pointer 6013 /// are compatible. It is more restrict than comparing two function pointer 6014 // types. 6015 static Sema::AssignConvertType 6016 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6017 QualType RHSType) { 6018 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6019 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6020 6021 QualType lhptee, rhptee; 6022 6023 // get the "pointed to" type (ignoring qualifiers at the top level) 6024 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6025 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6026 6027 // In C++, the types have to match exactly. 6028 if (S.getLangOpts().CPlusPlus) 6029 return Sema::IncompatibleBlockPointer; 6030 6031 Sema::AssignConvertType ConvTy = Sema::Compatible; 6032 6033 // For blocks we enforce that qualifiers are identical. 6034 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6035 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6036 6037 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6038 return Sema::IncompatibleBlockPointer; 6039 6040 return ConvTy; 6041 } 6042 6043 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6044 /// for assignment compatibility. 6045 static Sema::AssignConvertType 6046 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6047 QualType RHSType) { 6048 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6049 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6050 6051 if (LHSType->isObjCBuiltinType()) { 6052 // Class is not compatible with ObjC object pointers. 6053 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6054 !RHSType->isObjCQualifiedClassType()) 6055 return Sema::IncompatiblePointer; 6056 return Sema::Compatible; 6057 } 6058 if (RHSType->isObjCBuiltinType()) { 6059 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6060 !LHSType->isObjCQualifiedClassType()) 6061 return Sema::IncompatiblePointer; 6062 return Sema::Compatible; 6063 } 6064 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6065 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6066 6067 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6068 // make an exception for id<P> 6069 !LHSType->isObjCQualifiedIdType()) 6070 return Sema::CompatiblePointerDiscardsQualifiers; 6071 6072 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6073 return Sema::Compatible; 6074 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6075 return Sema::IncompatibleObjCQualifiedId; 6076 return Sema::IncompatiblePointer; 6077 } 6078 6079 Sema::AssignConvertType 6080 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6081 QualType LHSType, QualType RHSType) { 6082 // Fake up an opaque expression. We don't actually care about what 6083 // cast operations are required, so if CheckAssignmentConstraints 6084 // adds casts to this they'll be wasted, but fortunately that doesn't 6085 // usually happen on valid code. 6086 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6087 ExprResult RHSPtr = &RHSExpr; 6088 CastKind K = CK_Invalid; 6089 6090 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6091 } 6092 6093 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6094 /// has code to accommodate several GCC extensions when type checking 6095 /// pointers. Here are some objectionable examples that GCC considers warnings: 6096 /// 6097 /// int a, *pint; 6098 /// short *pshort; 6099 /// struct foo *pfoo; 6100 /// 6101 /// pint = pshort; // warning: assignment from incompatible pointer type 6102 /// a = pint; // warning: assignment makes integer from pointer without a cast 6103 /// pint = a; // warning: assignment makes pointer from integer without a cast 6104 /// pint = pfoo; // warning: assignment from incompatible pointer type 6105 /// 6106 /// As a result, the code for dealing with pointers is more complex than the 6107 /// C99 spec dictates. 6108 /// 6109 /// Sets 'Kind' for any result kind except Incompatible. 6110 Sema::AssignConvertType 6111 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6112 CastKind &Kind) { 6113 QualType RHSType = RHS.get()->getType(); 6114 QualType OrigLHSType = LHSType; 6115 6116 // Get canonical types. We're not formatting these types, just comparing 6117 // them. 6118 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6119 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6120 6121 // Common case: no conversion required. 6122 if (LHSType == RHSType) { 6123 Kind = CK_NoOp; 6124 return Compatible; 6125 } 6126 6127 // If we have an atomic type, try a non-atomic assignment, then just add an 6128 // atomic qualification step. 6129 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6130 Sema::AssignConvertType result = 6131 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6132 if (result != Compatible) 6133 return result; 6134 if (Kind != CK_NoOp) 6135 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6136 Kind = CK_NonAtomicToAtomic; 6137 return Compatible; 6138 } 6139 6140 // If the left-hand side is a reference type, then we are in a 6141 // (rare!) case where we've allowed the use of references in C, 6142 // e.g., as a parameter type in a built-in function. In this case, 6143 // just make sure that the type referenced is compatible with the 6144 // right-hand side type. The caller is responsible for adjusting 6145 // LHSType so that the resulting expression does not have reference 6146 // type. 6147 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6148 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6149 Kind = CK_LValueBitCast; 6150 return Compatible; 6151 } 6152 return Incompatible; 6153 } 6154 6155 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6156 // to the same ExtVector type. 6157 if (LHSType->isExtVectorType()) { 6158 if (RHSType->isExtVectorType()) 6159 return Incompatible; 6160 if (RHSType->isArithmeticType()) { 6161 // CK_VectorSplat does T -> vector T, so first cast to the 6162 // element type. 6163 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6164 if (elType != RHSType) { 6165 Kind = PrepareScalarCast(RHS, elType); 6166 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6167 } 6168 Kind = CK_VectorSplat; 6169 return Compatible; 6170 } 6171 } 6172 6173 // Conversions to or from vector type. 6174 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6175 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6176 // Allow assignments of an AltiVec vector type to an equivalent GCC 6177 // vector type and vice versa 6178 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6179 Kind = CK_BitCast; 6180 return Compatible; 6181 } 6182 6183 // If we are allowing lax vector conversions, and LHS and RHS are both 6184 // vectors, the total size only needs to be the same. This is a bitcast; 6185 // no bits are changed but the result type is different. 6186 if (getLangOpts().LaxVectorConversions && 6187 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 6188 Kind = CK_BitCast; 6189 return IncompatibleVectors; 6190 } 6191 } 6192 return Incompatible; 6193 } 6194 6195 // Arithmetic conversions. 6196 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6197 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6198 Kind = PrepareScalarCast(RHS, LHSType); 6199 return Compatible; 6200 } 6201 6202 // Conversions to normal pointers. 6203 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6204 // U* -> T* 6205 if (isa<PointerType>(RHSType)) { 6206 Kind = CK_BitCast; 6207 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6208 } 6209 6210 // int -> T* 6211 if (RHSType->isIntegerType()) { 6212 Kind = CK_IntegralToPointer; // FIXME: null? 6213 return IntToPointer; 6214 } 6215 6216 // C pointers are not compatible with ObjC object pointers, 6217 // with two exceptions: 6218 if (isa<ObjCObjectPointerType>(RHSType)) { 6219 // - conversions to void* 6220 if (LHSPointer->getPointeeType()->isVoidType()) { 6221 Kind = CK_BitCast; 6222 return Compatible; 6223 } 6224 6225 // - conversions from 'Class' to the redefinition type 6226 if (RHSType->isObjCClassType() && 6227 Context.hasSameType(LHSType, 6228 Context.getObjCClassRedefinitionType())) { 6229 Kind = CK_BitCast; 6230 return Compatible; 6231 } 6232 6233 Kind = CK_BitCast; 6234 return IncompatiblePointer; 6235 } 6236 6237 // U^ -> void* 6238 if (RHSType->getAs<BlockPointerType>()) { 6239 if (LHSPointer->getPointeeType()->isVoidType()) { 6240 Kind = CK_BitCast; 6241 return Compatible; 6242 } 6243 } 6244 6245 return Incompatible; 6246 } 6247 6248 // Conversions to block pointers. 6249 if (isa<BlockPointerType>(LHSType)) { 6250 // U^ -> T^ 6251 if (RHSType->isBlockPointerType()) { 6252 Kind = CK_BitCast; 6253 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6254 } 6255 6256 // int or null -> T^ 6257 if (RHSType->isIntegerType()) { 6258 Kind = CK_IntegralToPointer; // FIXME: null 6259 return IntToBlockPointer; 6260 } 6261 6262 // id -> T^ 6263 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6264 Kind = CK_AnyPointerToBlockPointerCast; 6265 return Compatible; 6266 } 6267 6268 // void* -> T^ 6269 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6270 if (RHSPT->getPointeeType()->isVoidType()) { 6271 Kind = CK_AnyPointerToBlockPointerCast; 6272 return Compatible; 6273 } 6274 6275 return Incompatible; 6276 } 6277 6278 // Conversions to Objective-C pointers. 6279 if (isa<ObjCObjectPointerType>(LHSType)) { 6280 // A* -> B* 6281 if (RHSType->isObjCObjectPointerType()) { 6282 Kind = CK_BitCast; 6283 Sema::AssignConvertType result = 6284 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6285 if (getLangOpts().ObjCAutoRefCount && 6286 result == Compatible && 6287 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6288 result = IncompatibleObjCWeakRef; 6289 return result; 6290 } 6291 6292 // int or null -> A* 6293 if (RHSType->isIntegerType()) { 6294 Kind = CK_IntegralToPointer; // FIXME: null 6295 return IntToPointer; 6296 } 6297 6298 // In general, C pointers are not compatible with ObjC object pointers, 6299 // with two exceptions: 6300 if (isa<PointerType>(RHSType)) { 6301 Kind = CK_CPointerToObjCPointerCast; 6302 6303 // - conversions from 'void*' 6304 if (RHSType->isVoidPointerType()) { 6305 return Compatible; 6306 } 6307 6308 // - conversions to 'Class' from its redefinition type 6309 if (LHSType->isObjCClassType() && 6310 Context.hasSameType(RHSType, 6311 Context.getObjCClassRedefinitionType())) { 6312 return Compatible; 6313 } 6314 6315 return IncompatiblePointer; 6316 } 6317 6318 // T^ -> A* 6319 if (RHSType->isBlockPointerType()) { 6320 maybeExtendBlockObject(*this, RHS); 6321 Kind = CK_BlockPointerToObjCPointerCast; 6322 return Compatible; 6323 } 6324 6325 return Incompatible; 6326 } 6327 6328 // Conversions from pointers that are not covered by the above. 6329 if (isa<PointerType>(RHSType)) { 6330 // T* -> _Bool 6331 if (LHSType == Context.BoolTy) { 6332 Kind = CK_PointerToBoolean; 6333 return Compatible; 6334 } 6335 6336 // T* -> int 6337 if (LHSType->isIntegerType()) { 6338 Kind = CK_PointerToIntegral; 6339 return PointerToInt; 6340 } 6341 6342 return Incompatible; 6343 } 6344 6345 // Conversions from Objective-C pointers that are not covered by the above. 6346 if (isa<ObjCObjectPointerType>(RHSType)) { 6347 // T* -> _Bool 6348 if (LHSType == Context.BoolTy) { 6349 Kind = CK_PointerToBoolean; 6350 return Compatible; 6351 } 6352 6353 // T* -> int 6354 if (LHSType->isIntegerType()) { 6355 Kind = CK_PointerToIntegral; 6356 return PointerToInt; 6357 } 6358 6359 return Incompatible; 6360 } 6361 6362 // struct A -> struct B 6363 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6364 if (Context.typesAreCompatible(LHSType, RHSType)) { 6365 Kind = CK_NoOp; 6366 return Compatible; 6367 } 6368 } 6369 6370 return Incompatible; 6371 } 6372 6373 /// \brief Constructs a transparent union from an expression that is 6374 /// used to initialize the transparent union. 6375 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6376 ExprResult &EResult, QualType UnionType, 6377 FieldDecl *Field) { 6378 // Build an initializer list that designates the appropriate member 6379 // of the transparent union. 6380 Expr *E = EResult.take(); 6381 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6382 E, SourceLocation()); 6383 Initializer->setType(UnionType); 6384 Initializer->setInitializedFieldInUnion(Field); 6385 6386 // Build a compound literal constructing a value of the transparent 6387 // union type from this initializer list. 6388 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6389 EResult = S.Owned( 6390 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6391 VK_RValue, Initializer, false)); 6392 } 6393 6394 Sema::AssignConvertType 6395 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6396 ExprResult &RHS) { 6397 QualType RHSType = RHS.get()->getType(); 6398 6399 // If the ArgType is a Union type, we want to handle a potential 6400 // transparent_union GCC extension. 6401 const RecordType *UT = ArgType->getAsUnionType(); 6402 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6403 return Incompatible; 6404 6405 // The field to initialize within the transparent union. 6406 RecordDecl *UD = UT->getDecl(); 6407 FieldDecl *InitField = 0; 6408 // It's compatible if the expression matches any of the fields. 6409 for (RecordDecl::field_iterator it = UD->field_begin(), 6410 itend = UD->field_end(); 6411 it != itend; ++it) { 6412 if (it->getType()->isPointerType()) { 6413 // If the transparent union contains a pointer type, we allow: 6414 // 1) void pointer 6415 // 2) null pointer constant 6416 if (RHSType->isPointerType()) 6417 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6418 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6419 InitField = *it; 6420 break; 6421 } 6422 6423 if (RHS.get()->isNullPointerConstant(Context, 6424 Expr::NPC_ValueDependentIsNull)) { 6425 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6426 CK_NullToPointer); 6427 InitField = *it; 6428 break; 6429 } 6430 } 6431 6432 CastKind Kind = CK_Invalid; 6433 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6434 == Compatible) { 6435 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6436 InitField = *it; 6437 break; 6438 } 6439 } 6440 6441 if (!InitField) 6442 return Incompatible; 6443 6444 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6445 return Compatible; 6446 } 6447 6448 Sema::AssignConvertType 6449 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6450 bool Diagnose, 6451 bool DiagnoseCFAudited) { 6452 if (getLangOpts().CPlusPlus) { 6453 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6454 // C++ 5.17p3: If the left operand is not of class type, the 6455 // expression is implicitly converted (C++ 4) to the 6456 // cv-unqualified type of the left operand. 6457 ExprResult Res; 6458 if (Diagnose) { 6459 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6460 AA_Assigning); 6461 } else { 6462 ImplicitConversionSequence ICS = 6463 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6464 /*SuppressUserConversions=*/false, 6465 /*AllowExplicit=*/false, 6466 /*InOverloadResolution=*/false, 6467 /*CStyle=*/false, 6468 /*AllowObjCWritebackConversion=*/false); 6469 if (ICS.isFailure()) 6470 return Incompatible; 6471 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6472 ICS, AA_Assigning); 6473 } 6474 if (Res.isInvalid()) 6475 return Incompatible; 6476 Sema::AssignConvertType result = Compatible; 6477 if (getLangOpts().ObjCAutoRefCount && 6478 !CheckObjCARCUnavailableWeakConversion(LHSType, 6479 RHS.get()->getType())) 6480 result = IncompatibleObjCWeakRef; 6481 RHS = Res; 6482 return result; 6483 } 6484 6485 // FIXME: Currently, we fall through and treat C++ classes like C 6486 // structures. 6487 // FIXME: We also fall through for atomics; not sure what should 6488 // happen there, though. 6489 } 6490 6491 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6492 // a null pointer constant. 6493 if ((LHSType->isPointerType() || 6494 LHSType->isObjCObjectPointerType() || 6495 LHSType->isBlockPointerType()) 6496 && RHS.get()->isNullPointerConstant(Context, 6497 Expr::NPC_ValueDependentIsNull)) { 6498 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6499 return Compatible; 6500 } 6501 6502 // This check seems unnatural, however it is necessary to ensure the proper 6503 // conversion of functions/arrays. If the conversion were done for all 6504 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6505 // expressions that suppress this implicit conversion (&, sizeof). 6506 // 6507 // Suppress this for references: C++ 8.5.3p5. 6508 if (!LHSType->isReferenceType()) { 6509 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6510 if (RHS.isInvalid()) 6511 return Incompatible; 6512 } 6513 6514 CastKind Kind = CK_Invalid; 6515 Sema::AssignConvertType result = 6516 CheckAssignmentConstraints(LHSType, RHS, Kind); 6517 6518 // C99 6.5.16.1p2: The value of the right operand is converted to the 6519 // type of the assignment expression. 6520 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6521 // so that we can use references in built-in functions even in C. 6522 // The getNonReferenceType() call makes sure that the resulting expression 6523 // does not have reference type. 6524 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6525 QualType Ty = LHSType.getNonLValueExprType(Context); 6526 Expr *E = RHS.take(); 6527 if (getLangOpts().ObjCAutoRefCount) 6528 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6529 DiagnoseCFAudited); 6530 RHS = ImpCastExprToType(E, Ty, Kind); 6531 } 6532 return result; 6533 } 6534 6535 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6536 ExprResult &RHS) { 6537 Diag(Loc, diag::err_typecheck_invalid_operands) 6538 << LHS.get()->getType() << RHS.get()->getType() 6539 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6540 return QualType(); 6541 } 6542 6543 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6544 SourceLocation Loc, bool IsCompAssign) { 6545 if (!IsCompAssign) { 6546 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6547 if (LHS.isInvalid()) 6548 return QualType(); 6549 } 6550 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6551 if (RHS.isInvalid()) 6552 return QualType(); 6553 6554 // For conversion purposes, we ignore any qualifiers. 6555 // For example, "const float" and "float" are equivalent. 6556 QualType LHSType = 6557 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6558 QualType RHSType = 6559 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6560 6561 // If the vector types are identical, return. 6562 if (LHSType == RHSType) 6563 return LHSType; 6564 6565 // Handle the case of equivalent AltiVec and GCC vector types 6566 if (LHSType->isVectorType() && RHSType->isVectorType() && 6567 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6568 if (LHSType->isExtVectorType()) { 6569 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6570 return LHSType; 6571 } 6572 6573 if (!IsCompAssign) 6574 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6575 return RHSType; 6576 } 6577 6578 if (getLangOpts().LaxVectorConversions && 6579 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6580 // If we are allowing lax vector conversions, and LHS and RHS are both 6581 // vectors, the total size only needs to be the same. This is a 6582 // bitcast; no bits are changed but the result type is different. 6583 // FIXME: Should we really be allowing this? 6584 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6585 return LHSType; 6586 } 6587 6588 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6589 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6590 bool swapped = false; 6591 if (RHSType->isExtVectorType() && !IsCompAssign) { 6592 swapped = true; 6593 std::swap(RHS, LHS); 6594 std::swap(RHSType, LHSType); 6595 } 6596 6597 // Handle the case of an ext vector and scalar. 6598 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6599 QualType EltTy = LV->getElementType(); 6600 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6601 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6602 if (order > 0) 6603 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6604 if (order >= 0) { 6605 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6606 if (swapped) std::swap(RHS, LHS); 6607 return LHSType; 6608 } 6609 } 6610 if (EltTy->isRealFloatingType() && RHSType->isScalarType()) { 6611 if (RHSType->isRealFloatingType()) { 6612 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6613 if (order > 0) 6614 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6615 if (order >= 0) { 6616 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6617 if (swapped) std::swap(RHS, LHS); 6618 return LHSType; 6619 } 6620 } 6621 if (RHSType->isIntegralType(Context)) { 6622 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating); 6623 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6624 if (swapped) std::swap(RHS, LHS); 6625 return LHSType; 6626 } 6627 } 6628 } 6629 6630 // Vectors of different size or scalar and non-ext-vector are errors. 6631 if (swapped) std::swap(RHS, LHS); 6632 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6633 << LHS.get()->getType() << RHS.get()->getType() 6634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6635 return QualType(); 6636 } 6637 6638 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6639 // expression. These are mainly cases where the null pointer is used as an 6640 // integer instead of a pointer. 6641 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6642 SourceLocation Loc, bool IsCompare) { 6643 // The canonical way to check for a GNU null is with isNullPointerConstant, 6644 // but we use a bit of a hack here for speed; this is a relatively 6645 // hot path, and isNullPointerConstant is slow. 6646 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6647 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6648 6649 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6650 6651 // Avoid analyzing cases where the result will either be invalid (and 6652 // diagnosed as such) or entirely valid and not something to warn about. 6653 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6654 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6655 return; 6656 6657 // Comparison operations would not make sense with a null pointer no matter 6658 // what the other expression is. 6659 if (!IsCompare) { 6660 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6661 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6662 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6663 return; 6664 } 6665 6666 // The rest of the operations only make sense with a null pointer 6667 // if the other expression is a pointer. 6668 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6669 NonNullType->canDecayToPointerType()) 6670 return; 6671 6672 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6673 << LHSNull /* LHS is NULL */ << NonNullType 6674 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6675 } 6676 6677 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6678 SourceLocation Loc, 6679 bool IsCompAssign, bool IsDiv) { 6680 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6681 6682 if (LHS.get()->getType()->isVectorType() || 6683 RHS.get()->getType()->isVectorType()) 6684 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6685 6686 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6687 if (LHS.isInvalid() || RHS.isInvalid()) 6688 return QualType(); 6689 6690 6691 if (compType.isNull() || !compType->isArithmeticType()) 6692 return InvalidOperands(Loc, LHS, RHS); 6693 6694 // Check for division by zero. 6695 llvm::APSInt RHSValue; 6696 if (IsDiv && !RHS.get()->isValueDependent() && 6697 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6698 DiagRuntimeBehavior(Loc, RHS.get(), 6699 PDiag(diag::warn_division_by_zero) 6700 << RHS.get()->getSourceRange()); 6701 6702 return compType; 6703 } 6704 6705 QualType Sema::CheckRemainderOperands( 6706 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6707 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6708 6709 if (LHS.get()->getType()->isVectorType() || 6710 RHS.get()->getType()->isVectorType()) { 6711 if (LHS.get()->getType()->hasIntegerRepresentation() && 6712 RHS.get()->getType()->hasIntegerRepresentation()) 6713 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6714 return InvalidOperands(Loc, LHS, RHS); 6715 } 6716 6717 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6718 if (LHS.isInvalid() || RHS.isInvalid()) 6719 return QualType(); 6720 6721 if (compType.isNull() || !compType->isIntegerType()) 6722 return InvalidOperands(Loc, LHS, RHS); 6723 6724 // Check for remainder by zero. 6725 llvm::APSInt RHSValue; 6726 if (!RHS.get()->isValueDependent() && 6727 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6728 DiagRuntimeBehavior(Loc, RHS.get(), 6729 PDiag(diag::warn_remainder_by_zero) 6730 << RHS.get()->getSourceRange()); 6731 6732 return compType; 6733 } 6734 6735 /// \brief Diagnose invalid arithmetic on two void pointers. 6736 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6737 Expr *LHSExpr, Expr *RHSExpr) { 6738 S.Diag(Loc, S.getLangOpts().CPlusPlus 6739 ? diag::err_typecheck_pointer_arith_void_type 6740 : diag::ext_gnu_void_ptr) 6741 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6742 << RHSExpr->getSourceRange(); 6743 } 6744 6745 /// \brief Diagnose invalid arithmetic on a void pointer. 6746 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6747 Expr *Pointer) { 6748 S.Diag(Loc, S.getLangOpts().CPlusPlus 6749 ? diag::err_typecheck_pointer_arith_void_type 6750 : diag::ext_gnu_void_ptr) 6751 << 0 /* one pointer */ << Pointer->getSourceRange(); 6752 } 6753 6754 /// \brief Diagnose invalid arithmetic on two function pointers. 6755 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6756 Expr *LHS, Expr *RHS) { 6757 assert(LHS->getType()->isAnyPointerType()); 6758 assert(RHS->getType()->isAnyPointerType()); 6759 S.Diag(Loc, S.getLangOpts().CPlusPlus 6760 ? diag::err_typecheck_pointer_arith_function_type 6761 : diag::ext_gnu_ptr_func_arith) 6762 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6763 // We only show the second type if it differs from the first. 6764 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6765 RHS->getType()) 6766 << RHS->getType()->getPointeeType() 6767 << LHS->getSourceRange() << RHS->getSourceRange(); 6768 } 6769 6770 /// \brief Diagnose invalid arithmetic on a function pointer. 6771 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6772 Expr *Pointer) { 6773 assert(Pointer->getType()->isAnyPointerType()); 6774 S.Diag(Loc, S.getLangOpts().CPlusPlus 6775 ? diag::err_typecheck_pointer_arith_function_type 6776 : diag::ext_gnu_ptr_func_arith) 6777 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6778 << 0 /* one pointer, so only one type */ 6779 << Pointer->getSourceRange(); 6780 } 6781 6782 /// \brief Emit error if Operand is incomplete pointer type 6783 /// 6784 /// \returns True if pointer has incomplete type 6785 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6786 Expr *Operand) { 6787 assert(Operand->getType()->isAnyPointerType() && 6788 !Operand->getType()->isDependentType()); 6789 QualType PointeeTy = Operand->getType()->getPointeeType(); 6790 return S.RequireCompleteType(Loc, PointeeTy, 6791 diag::err_typecheck_arithmetic_incomplete_type, 6792 PointeeTy, Operand->getSourceRange()); 6793 } 6794 6795 /// \brief Check the validity of an arithmetic pointer operand. 6796 /// 6797 /// If the operand has pointer type, this code will check for pointer types 6798 /// which are invalid in arithmetic operations. These will be diagnosed 6799 /// appropriately, including whether or not the use is supported as an 6800 /// extension. 6801 /// 6802 /// \returns True when the operand is valid to use (even if as an extension). 6803 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6804 Expr *Operand) { 6805 if (!Operand->getType()->isAnyPointerType()) return true; 6806 6807 QualType PointeeTy = Operand->getType()->getPointeeType(); 6808 if (PointeeTy->isVoidType()) { 6809 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6810 return !S.getLangOpts().CPlusPlus; 6811 } 6812 if (PointeeTy->isFunctionType()) { 6813 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6814 return !S.getLangOpts().CPlusPlus; 6815 } 6816 6817 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6818 6819 return true; 6820 } 6821 6822 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6823 /// operands. 6824 /// 6825 /// This routine will diagnose any invalid arithmetic on pointer operands much 6826 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6827 /// for emitting a single diagnostic even for operations where both LHS and RHS 6828 /// are (potentially problematic) pointers. 6829 /// 6830 /// \returns True when the operand is valid to use (even if as an extension). 6831 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6832 Expr *LHSExpr, Expr *RHSExpr) { 6833 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6834 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6835 if (!isLHSPointer && !isRHSPointer) return true; 6836 6837 QualType LHSPointeeTy, RHSPointeeTy; 6838 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6839 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6840 6841 // Check for arithmetic on pointers to incomplete types. 6842 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6843 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6844 if (isLHSVoidPtr || isRHSVoidPtr) { 6845 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6846 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6847 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6848 6849 return !S.getLangOpts().CPlusPlus; 6850 } 6851 6852 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6853 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6854 if (isLHSFuncPtr || isRHSFuncPtr) { 6855 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6856 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6857 RHSExpr); 6858 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6859 6860 return !S.getLangOpts().CPlusPlus; 6861 } 6862 6863 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6864 return false; 6865 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6866 return false; 6867 6868 return true; 6869 } 6870 6871 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6872 /// literal. 6873 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6874 Expr *LHSExpr, Expr *RHSExpr) { 6875 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6876 Expr* IndexExpr = RHSExpr; 6877 if (!StrExpr) { 6878 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6879 IndexExpr = LHSExpr; 6880 } 6881 6882 bool IsStringPlusInt = StrExpr && 6883 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6884 if (!IsStringPlusInt) 6885 return; 6886 6887 llvm::APSInt index; 6888 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6889 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6890 if (index.isNonNegative() && 6891 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6892 index.isUnsigned())) 6893 return; 6894 } 6895 6896 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6897 Self.Diag(OpLoc, diag::warn_string_plus_int) 6898 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6899 6900 // Only print a fixit for "str" + int, not for int + "str". 6901 if (IndexExpr == RHSExpr) { 6902 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6903 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6904 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6905 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6906 << FixItHint::CreateInsertion(EndLoc, "]"); 6907 } else 6908 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6909 } 6910 6911 /// \brief Emit error when two pointers are incompatible. 6912 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6913 Expr *LHSExpr, Expr *RHSExpr) { 6914 assert(LHSExpr->getType()->isAnyPointerType()); 6915 assert(RHSExpr->getType()->isAnyPointerType()); 6916 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6917 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6918 << RHSExpr->getSourceRange(); 6919 } 6920 6921 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6922 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6923 QualType* CompLHSTy) { 6924 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6925 6926 if (LHS.get()->getType()->isVectorType() || 6927 RHS.get()->getType()->isVectorType()) { 6928 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6929 if (CompLHSTy) *CompLHSTy = compType; 6930 return compType; 6931 } 6932 6933 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6934 if (LHS.isInvalid() || RHS.isInvalid()) 6935 return QualType(); 6936 6937 // Diagnose "string literal" '+' int. 6938 if (Opc == BO_Add) 6939 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6940 6941 // handle the common case first (both operands are arithmetic). 6942 if (!compType.isNull() && compType->isArithmeticType()) { 6943 if (CompLHSTy) *CompLHSTy = compType; 6944 return compType; 6945 } 6946 6947 // Type-checking. Ultimately the pointer's going to be in PExp; 6948 // note that we bias towards the LHS being the pointer. 6949 Expr *PExp = LHS.get(), *IExp = RHS.get(); 6950 6951 bool isObjCPointer; 6952 if (PExp->getType()->isPointerType()) { 6953 isObjCPointer = false; 6954 } else if (PExp->getType()->isObjCObjectPointerType()) { 6955 isObjCPointer = true; 6956 } else { 6957 std::swap(PExp, IExp); 6958 if (PExp->getType()->isPointerType()) { 6959 isObjCPointer = false; 6960 } else if (PExp->getType()->isObjCObjectPointerType()) { 6961 isObjCPointer = true; 6962 } else { 6963 return InvalidOperands(Loc, LHS, RHS); 6964 } 6965 } 6966 assert(PExp->getType()->isAnyPointerType()); 6967 6968 if (!IExp->getType()->isIntegerType()) 6969 return InvalidOperands(Loc, LHS, RHS); 6970 6971 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6972 return QualType(); 6973 6974 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 6975 return QualType(); 6976 6977 // Check array bounds for pointer arithemtic 6978 CheckArrayAccess(PExp, IExp); 6979 6980 if (CompLHSTy) { 6981 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6982 if (LHSTy.isNull()) { 6983 LHSTy = LHS.get()->getType(); 6984 if (LHSTy->isPromotableIntegerType()) 6985 LHSTy = Context.getPromotedIntegerType(LHSTy); 6986 } 6987 *CompLHSTy = LHSTy; 6988 } 6989 6990 return PExp->getType(); 6991 } 6992 6993 // C99 6.5.6 6994 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6995 SourceLocation Loc, 6996 QualType* CompLHSTy) { 6997 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6998 6999 if (LHS.get()->getType()->isVectorType() || 7000 RHS.get()->getType()->isVectorType()) { 7001 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7002 if (CompLHSTy) *CompLHSTy = compType; 7003 return compType; 7004 } 7005 7006 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7007 if (LHS.isInvalid() || RHS.isInvalid()) 7008 return QualType(); 7009 7010 // Enforce type constraints: C99 6.5.6p3. 7011 7012 // Handle the common case first (both operands are arithmetic). 7013 if (!compType.isNull() && compType->isArithmeticType()) { 7014 if (CompLHSTy) *CompLHSTy = compType; 7015 return compType; 7016 } 7017 7018 // Either ptr - int or ptr - ptr. 7019 if (LHS.get()->getType()->isAnyPointerType()) { 7020 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7021 7022 // Diagnose bad cases where we step over interface counts. 7023 if (LHS.get()->getType()->isObjCObjectPointerType() && 7024 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7025 return QualType(); 7026 7027 // The result type of a pointer-int computation is the pointer type. 7028 if (RHS.get()->getType()->isIntegerType()) { 7029 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7030 return QualType(); 7031 7032 // Check array bounds for pointer arithemtic 7033 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7034 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7035 7036 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7037 return LHS.get()->getType(); 7038 } 7039 7040 // Handle pointer-pointer subtractions. 7041 if (const PointerType *RHSPTy 7042 = RHS.get()->getType()->getAs<PointerType>()) { 7043 QualType rpointee = RHSPTy->getPointeeType(); 7044 7045 if (getLangOpts().CPlusPlus) { 7046 // Pointee types must be the same: C++ [expr.add] 7047 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7048 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7049 } 7050 } else { 7051 // Pointee types must be compatible C99 6.5.6p3 7052 if (!Context.typesAreCompatible( 7053 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7054 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7055 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7056 return QualType(); 7057 } 7058 } 7059 7060 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7061 LHS.get(), RHS.get())) 7062 return QualType(); 7063 7064 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7065 return Context.getPointerDiffType(); 7066 } 7067 } 7068 7069 return InvalidOperands(Loc, LHS, RHS); 7070 } 7071 7072 static bool isScopedEnumerationType(QualType T) { 7073 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7074 return ET->getDecl()->isScoped(); 7075 return false; 7076 } 7077 7078 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7079 SourceLocation Loc, unsigned Opc, 7080 QualType LHSType) { 7081 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7082 // so skip remaining warnings as we don't want to modify values within Sema. 7083 if (S.getLangOpts().OpenCL) 7084 return; 7085 7086 llvm::APSInt Right; 7087 // Check right/shifter operand 7088 if (RHS.get()->isValueDependent() || 7089 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7090 return; 7091 7092 if (Right.isNegative()) { 7093 S.DiagRuntimeBehavior(Loc, RHS.get(), 7094 S.PDiag(diag::warn_shift_negative) 7095 << RHS.get()->getSourceRange()); 7096 return; 7097 } 7098 llvm::APInt LeftBits(Right.getBitWidth(), 7099 S.Context.getTypeSize(LHS.get()->getType())); 7100 if (Right.uge(LeftBits)) { 7101 S.DiagRuntimeBehavior(Loc, RHS.get(), 7102 S.PDiag(diag::warn_shift_gt_typewidth) 7103 << RHS.get()->getSourceRange()); 7104 return; 7105 } 7106 if (Opc != BO_Shl) 7107 return; 7108 7109 // When left shifting an ICE which is signed, we can check for overflow which 7110 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7111 // integers have defined behavior modulo one more than the maximum value 7112 // representable in the result type, so never warn for those. 7113 llvm::APSInt Left; 7114 if (LHS.get()->isValueDependent() || 7115 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7116 LHSType->hasUnsignedIntegerRepresentation()) 7117 return; 7118 llvm::APInt ResultBits = 7119 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7120 if (LeftBits.uge(ResultBits)) 7121 return; 7122 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7123 Result = Result.shl(Right); 7124 7125 // Print the bit representation of the signed integer as an unsigned 7126 // hexadecimal number. 7127 SmallString<40> HexResult; 7128 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7129 7130 // If we are only missing a sign bit, this is less likely to result in actual 7131 // bugs -- if the result is cast back to an unsigned type, it will have the 7132 // expected value. Thus we place this behind a different warning that can be 7133 // turned off separately if needed. 7134 if (LeftBits == ResultBits - 1) { 7135 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7136 << HexResult.str() << LHSType 7137 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7138 return; 7139 } 7140 7141 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7142 << HexResult.str() << Result.getMinSignedBits() << LHSType 7143 << Left.getBitWidth() << LHS.get()->getSourceRange() 7144 << RHS.get()->getSourceRange(); 7145 } 7146 7147 // C99 6.5.7 7148 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7149 SourceLocation Loc, unsigned Opc, 7150 bool IsCompAssign) { 7151 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7152 7153 // Vector shifts promote their scalar inputs to vector type. 7154 if (LHS.get()->getType()->isVectorType() || 7155 RHS.get()->getType()->isVectorType()) 7156 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7157 7158 // Shifts don't perform usual arithmetic conversions, they just do integer 7159 // promotions on each operand. C99 6.5.7p3 7160 7161 // For the LHS, do usual unary conversions, but then reset them away 7162 // if this is a compound assignment. 7163 ExprResult OldLHS = LHS; 7164 LHS = UsualUnaryConversions(LHS.take()); 7165 if (LHS.isInvalid()) 7166 return QualType(); 7167 QualType LHSType = LHS.get()->getType(); 7168 if (IsCompAssign) LHS = OldLHS; 7169 7170 // The RHS is simpler. 7171 RHS = UsualUnaryConversions(RHS.take()); 7172 if (RHS.isInvalid()) 7173 return QualType(); 7174 QualType RHSType = RHS.get()->getType(); 7175 7176 // C99 6.5.7p2: Each of the operands shall have integer type. 7177 if (!LHSType->hasIntegerRepresentation() || 7178 !RHSType->hasIntegerRepresentation()) 7179 return InvalidOperands(Loc, LHS, RHS); 7180 7181 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7182 // hasIntegerRepresentation() above instead of this. 7183 if (isScopedEnumerationType(LHSType) || 7184 isScopedEnumerationType(RHSType)) { 7185 return InvalidOperands(Loc, LHS, RHS); 7186 } 7187 // Sanity-check shift operands 7188 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7189 7190 // "The type of the result is that of the promoted left operand." 7191 return LHSType; 7192 } 7193 7194 static bool IsWithinTemplateSpecialization(Decl *D) { 7195 if (DeclContext *DC = D->getDeclContext()) { 7196 if (isa<ClassTemplateSpecializationDecl>(DC)) 7197 return true; 7198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7199 return FD->isFunctionTemplateSpecialization(); 7200 } 7201 return false; 7202 } 7203 7204 /// If two different enums are compared, raise a warning. 7205 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7206 Expr *RHS) { 7207 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7208 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7209 7210 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7211 if (!LHSEnumType) 7212 return; 7213 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7214 if (!RHSEnumType) 7215 return; 7216 7217 // Ignore anonymous enums. 7218 if (!LHSEnumType->getDecl()->getIdentifier()) 7219 return; 7220 if (!RHSEnumType->getDecl()->getIdentifier()) 7221 return; 7222 7223 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7224 return; 7225 7226 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7227 << LHSStrippedType << RHSStrippedType 7228 << LHS->getSourceRange() << RHS->getSourceRange(); 7229 } 7230 7231 /// \brief Diagnose bad pointer comparisons. 7232 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7233 ExprResult &LHS, ExprResult &RHS, 7234 bool IsError) { 7235 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7236 : diag::ext_typecheck_comparison_of_distinct_pointers) 7237 << LHS.get()->getType() << RHS.get()->getType() 7238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7239 } 7240 7241 /// \brief Returns false if the pointers are converted to a composite type, 7242 /// true otherwise. 7243 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7244 ExprResult &LHS, ExprResult &RHS) { 7245 // C++ [expr.rel]p2: 7246 // [...] Pointer conversions (4.10) and qualification 7247 // conversions (4.4) are performed on pointer operands (or on 7248 // a pointer operand and a null pointer constant) to bring 7249 // them to their composite pointer type. [...] 7250 // 7251 // C++ [expr.eq]p1 uses the same notion for (in)equality 7252 // comparisons of pointers. 7253 7254 // C++ [expr.eq]p2: 7255 // In addition, pointers to members can be compared, or a pointer to 7256 // member and a null pointer constant. Pointer to member conversions 7257 // (4.11) and qualification conversions (4.4) are performed to bring 7258 // them to a common type. If one operand is a null pointer constant, 7259 // the common type is the type of the other operand. Otherwise, the 7260 // common type is a pointer to member type similar (4.4) to the type 7261 // of one of the operands, with a cv-qualification signature (4.4) 7262 // that is the union of the cv-qualification signatures of the operand 7263 // types. 7264 7265 QualType LHSType = LHS.get()->getType(); 7266 QualType RHSType = RHS.get()->getType(); 7267 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7268 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7269 7270 bool NonStandardCompositeType = false; 7271 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7272 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7273 if (T.isNull()) { 7274 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7275 return true; 7276 } 7277 7278 if (NonStandardCompositeType) 7279 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7280 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7281 << RHS.get()->getSourceRange(); 7282 7283 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7284 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7285 return false; 7286 } 7287 7288 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7289 ExprResult &LHS, 7290 ExprResult &RHS, 7291 bool IsError) { 7292 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7293 : diag::ext_typecheck_comparison_of_fptr_to_void) 7294 << LHS.get()->getType() << RHS.get()->getType() 7295 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7296 } 7297 7298 static bool isObjCObjectLiteral(ExprResult &E) { 7299 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7300 case Stmt::ObjCArrayLiteralClass: 7301 case Stmt::ObjCDictionaryLiteralClass: 7302 case Stmt::ObjCStringLiteralClass: 7303 case Stmt::ObjCBoxedExprClass: 7304 return true; 7305 default: 7306 // Note that ObjCBoolLiteral is NOT an object literal! 7307 return false; 7308 } 7309 } 7310 7311 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7312 const ObjCObjectPointerType *Type = 7313 LHS->getType()->getAs<ObjCObjectPointerType>(); 7314 7315 // If this is not actually an Objective-C object, bail out. 7316 if (!Type) 7317 return false; 7318 7319 // Get the LHS object's interface type. 7320 QualType InterfaceType = Type->getPointeeType(); 7321 if (const ObjCObjectType *iQFaceTy = 7322 InterfaceType->getAsObjCQualifiedInterfaceType()) 7323 InterfaceType = iQFaceTy->getBaseType(); 7324 7325 // If the RHS isn't an Objective-C object, bail out. 7326 if (!RHS->getType()->isObjCObjectPointerType()) 7327 return false; 7328 7329 // Try to find the -isEqual: method. 7330 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7331 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7332 InterfaceType, 7333 /*instance=*/true); 7334 if (!Method) { 7335 if (Type->isObjCIdType()) { 7336 // For 'id', just check the global pool. 7337 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7338 /*receiverId=*/true, 7339 /*warn=*/false); 7340 } else { 7341 // Check protocols. 7342 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7343 /*instance=*/true); 7344 } 7345 } 7346 7347 if (!Method) 7348 return false; 7349 7350 QualType T = Method->param_begin()[0]->getType(); 7351 if (!T->isObjCObjectPointerType()) 7352 return false; 7353 7354 QualType R = Method->getResultType(); 7355 if (!R->isScalarType()) 7356 return false; 7357 7358 return true; 7359 } 7360 7361 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7362 FromE = FromE->IgnoreParenImpCasts(); 7363 switch (FromE->getStmtClass()) { 7364 default: 7365 break; 7366 case Stmt::ObjCStringLiteralClass: 7367 // "string literal" 7368 return LK_String; 7369 case Stmt::ObjCArrayLiteralClass: 7370 // "array literal" 7371 return LK_Array; 7372 case Stmt::ObjCDictionaryLiteralClass: 7373 // "dictionary literal" 7374 return LK_Dictionary; 7375 case Stmt::BlockExprClass: 7376 return LK_Block; 7377 case Stmt::ObjCBoxedExprClass: { 7378 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7379 switch (Inner->getStmtClass()) { 7380 case Stmt::IntegerLiteralClass: 7381 case Stmt::FloatingLiteralClass: 7382 case Stmt::CharacterLiteralClass: 7383 case Stmt::ObjCBoolLiteralExprClass: 7384 case Stmt::CXXBoolLiteralExprClass: 7385 // "numeric literal" 7386 return LK_Numeric; 7387 case Stmt::ImplicitCastExprClass: { 7388 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7389 // Boolean literals can be represented by implicit casts. 7390 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7391 return LK_Numeric; 7392 break; 7393 } 7394 default: 7395 break; 7396 } 7397 return LK_Boxed; 7398 } 7399 } 7400 return LK_None; 7401 } 7402 7403 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7404 ExprResult &LHS, ExprResult &RHS, 7405 BinaryOperator::Opcode Opc){ 7406 Expr *Literal; 7407 Expr *Other; 7408 if (isObjCObjectLiteral(LHS)) { 7409 Literal = LHS.get(); 7410 Other = RHS.get(); 7411 } else { 7412 Literal = RHS.get(); 7413 Other = LHS.get(); 7414 } 7415 7416 // Don't warn on comparisons against nil. 7417 Other = Other->IgnoreParenCasts(); 7418 if (Other->isNullPointerConstant(S.getASTContext(), 7419 Expr::NPC_ValueDependentIsNotNull)) 7420 return; 7421 7422 // This should be kept in sync with warn_objc_literal_comparison. 7423 // LK_String should always be after the other literals, since it has its own 7424 // warning flag. 7425 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7426 assert(LiteralKind != Sema::LK_Block); 7427 if (LiteralKind == Sema::LK_None) { 7428 llvm_unreachable("Unknown Objective-C object literal kind"); 7429 } 7430 7431 if (LiteralKind == Sema::LK_String) 7432 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7433 << Literal->getSourceRange(); 7434 else 7435 S.Diag(Loc, diag::warn_objc_literal_comparison) 7436 << LiteralKind << Literal->getSourceRange(); 7437 7438 if (BinaryOperator::isEqualityOp(Opc) && 7439 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7440 SourceLocation Start = LHS.get()->getLocStart(); 7441 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7442 CharSourceRange OpRange = 7443 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7444 7445 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7446 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7447 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7448 << FixItHint::CreateInsertion(End, "]"); 7449 } 7450 } 7451 7452 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7453 ExprResult &RHS, 7454 SourceLocation Loc, 7455 unsigned OpaqueOpc) { 7456 // This checking requires bools. 7457 if (!S.getLangOpts().Bool) return; 7458 7459 // Check that left hand side is !something. 7460 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7461 if (!UO || UO->getOpcode() != UO_LNot) return; 7462 7463 // Only check if the right hand side is non-bool arithmetic type. 7464 if (RHS.get()->getType()->isBooleanType()) return; 7465 7466 // Make sure that the something in !something is not bool. 7467 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7468 if (SubExpr->getType()->isBooleanType()) return; 7469 7470 // Emit warning. 7471 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7472 << Loc; 7473 7474 // First note suggest !(x < y) 7475 SourceLocation FirstOpen = SubExpr->getLocStart(); 7476 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7477 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7478 if (FirstClose.isInvalid()) 7479 FirstOpen = SourceLocation(); 7480 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7481 << FixItHint::CreateInsertion(FirstOpen, "(") 7482 << FixItHint::CreateInsertion(FirstClose, ")"); 7483 7484 // Second note suggests (!x) < y 7485 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7486 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7487 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7488 if (SecondClose.isInvalid()) 7489 SecondOpen = SourceLocation(); 7490 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7491 << FixItHint::CreateInsertion(SecondOpen, "(") 7492 << FixItHint::CreateInsertion(SecondClose, ")"); 7493 } 7494 7495 // C99 6.5.8, C++ [expr.rel] 7496 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7497 SourceLocation Loc, unsigned OpaqueOpc, 7498 bool IsRelational) { 7499 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7500 7501 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7502 7503 // Handle vector comparisons separately. 7504 if (LHS.get()->getType()->isVectorType() || 7505 RHS.get()->getType()->isVectorType()) 7506 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7507 7508 QualType LHSType = LHS.get()->getType(); 7509 QualType RHSType = RHS.get()->getType(); 7510 7511 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7512 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7513 7514 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7515 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7516 7517 if (!LHSType->hasFloatingRepresentation() && 7518 !(LHSType->isBlockPointerType() && IsRelational) && 7519 !LHS.get()->getLocStart().isMacroID() && 7520 !RHS.get()->getLocStart().isMacroID()) { 7521 // For non-floating point types, check for self-comparisons of the form 7522 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7523 // often indicate logic errors in the program. 7524 // 7525 // NOTE: Don't warn about comparison expressions resulting from macro 7526 // expansion. Also don't warn about comparisons which are only self 7527 // comparisons within a template specialization. The warnings should catch 7528 // obvious cases in the definition of the template anyways. The idea is to 7529 // warn when the typed comparison operator will always evaluate to the same 7530 // result. 7531 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 7532 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 7533 if (DRL->getDecl() == DRR->getDecl() && 7534 !IsWithinTemplateSpecialization(DRL->getDecl())) { 7535 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7536 << 0 // self- 7537 << (Opc == BO_EQ 7538 || Opc == BO_LE 7539 || Opc == BO_GE)); 7540 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 7541 !DRL->getDecl()->getType()->isReferenceType() && 7542 !DRR->getDecl()->getType()->isReferenceType()) { 7543 // what is it always going to eval to? 7544 char always_evals_to; 7545 switch(Opc) { 7546 case BO_EQ: // e.g. array1 == array2 7547 always_evals_to = 0; // false 7548 break; 7549 case BO_NE: // e.g. array1 != array2 7550 always_evals_to = 1; // true 7551 break; 7552 default: 7553 // best we can say is 'a constant' 7554 always_evals_to = 2; // e.g. array1 <= array2 7555 break; 7556 } 7557 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7558 << 1 // array 7559 << always_evals_to); 7560 } 7561 } 7562 } 7563 7564 if (isa<CastExpr>(LHSStripped)) 7565 LHSStripped = LHSStripped->IgnoreParenCasts(); 7566 if (isa<CastExpr>(RHSStripped)) 7567 RHSStripped = RHSStripped->IgnoreParenCasts(); 7568 7569 // Warn about comparisons against a string constant (unless the other 7570 // operand is null), the user probably wants strcmp. 7571 Expr *literalString = 0; 7572 Expr *literalStringStripped = 0; 7573 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7574 !RHSStripped->isNullPointerConstant(Context, 7575 Expr::NPC_ValueDependentIsNull)) { 7576 literalString = LHS.get(); 7577 literalStringStripped = LHSStripped; 7578 } else if ((isa<StringLiteral>(RHSStripped) || 7579 isa<ObjCEncodeExpr>(RHSStripped)) && 7580 !LHSStripped->isNullPointerConstant(Context, 7581 Expr::NPC_ValueDependentIsNull)) { 7582 literalString = RHS.get(); 7583 literalStringStripped = RHSStripped; 7584 } 7585 7586 if (literalString) { 7587 DiagRuntimeBehavior(Loc, 0, 7588 PDiag(diag::warn_stringcompare) 7589 << isa<ObjCEncodeExpr>(literalStringStripped) 7590 << literalString->getSourceRange()); 7591 } 7592 } 7593 7594 // C99 6.5.8p3 / C99 6.5.9p4 7595 UsualArithmeticConversions(LHS, RHS); 7596 if (LHS.isInvalid() || RHS.isInvalid()) 7597 return QualType(); 7598 7599 LHSType = LHS.get()->getType(); 7600 RHSType = RHS.get()->getType(); 7601 7602 // The result of comparisons is 'bool' in C++, 'int' in C. 7603 QualType ResultTy = Context.getLogicalOperationType(); 7604 7605 if (IsRelational) { 7606 if (LHSType->isRealType() && RHSType->isRealType()) 7607 return ResultTy; 7608 } else { 7609 // Check for comparisons of floating point operands using != and ==. 7610 if (LHSType->hasFloatingRepresentation()) 7611 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7612 7613 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7614 return ResultTy; 7615 } 7616 7617 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7618 Expr::NPC_ValueDependentIsNull); 7619 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7620 Expr::NPC_ValueDependentIsNull); 7621 7622 // All of the following pointer-related warnings are GCC extensions, except 7623 // when handling null pointer constants. 7624 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7625 QualType LCanPointeeTy = 7626 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7627 QualType RCanPointeeTy = 7628 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7629 7630 if (getLangOpts().CPlusPlus) { 7631 if (LCanPointeeTy == RCanPointeeTy) 7632 return ResultTy; 7633 if (!IsRelational && 7634 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7635 // Valid unless comparison between non-null pointer and function pointer 7636 // This is a gcc extension compatibility comparison. 7637 // In a SFINAE context, we treat this as a hard error to maintain 7638 // conformance with the C++ standard. 7639 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7640 && !LHSIsNull && !RHSIsNull) { 7641 diagnoseFunctionPointerToVoidComparison( 7642 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7643 7644 if (isSFINAEContext()) 7645 return QualType(); 7646 7647 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7648 return ResultTy; 7649 } 7650 } 7651 7652 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7653 return QualType(); 7654 else 7655 return ResultTy; 7656 } 7657 // C99 6.5.9p2 and C99 6.5.8p2 7658 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7659 RCanPointeeTy.getUnqualifiedType())) { 7660 // Valid unless a relational comparison of function pointers 7661 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7662 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7663 << LHSType << RHSType << LHS.get()->getSourceRange() 7664 << RHS.get()->getSourceRange(); 7665 } 7666 } else if (!IsRelational && 7667 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7668 // Valid unless comparison between non-null pointer and function pointer 7669 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7670 && !LHSIsNull && !RHSIsNull) 7671 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7672 /*isError*/false); 7673 } else { 7674 // Invalid 7675 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7676 } 7677 if (LCanPointeeTy != RCanPointeeTy) { 7678 if (LHSIsNull && !RHSIsNull) 7679 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7680 else 7681 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7682 } 7683 return ResultTy; 7684 } 7685 7686 if (getLangOpts().CPlusPlus) { 7687 // Comparison of nullptr_t with itself. 7688 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7689 return ResultTy; 7690 7691 // Comparison of pointers with null pointer constants and equality 7692 // comparisons of member pointers to null pointer constants. 7693 if (RHSIsNull && 7694 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7695 (!IsRelational && 7696 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7697 RHS = ImpCastExprToType(RHS.take(), LHSType, 7698 LHSType->isMemberPointerType() 7699 ? CK_NullToMemberPointer 7700 : CK_NullToPointer); 7701 return ResultTy; 7702 } 7703 if (LHSIsNull && 7704 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7705 (!IsRelational && 7706 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7707 LHS = ImpCastExprToType(LHS.take(), RHSType, 7708 RHSType->isMemberPointerType() 7709 ? CK_NullToMemberPointer 7710 : CK_NullToPointer); 7711 return ResultTy; 7712 } 7713 7714 // Comparison of member pointers. 7715 if (!IsRelational && 7716 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7717 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7718 return QualType(); 7719 else 7720 return ResultTy; 7721 } 7722 7723 // Handle scoped enumeration types specifically, since they don't promote 7724 // to integers. 7725 if (LHS.get()->getType()->isEnumeralType() && 7726 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7727 RHS.get()->getType())) 7728 return ResultTy; 7729 } 7730 7731 // Handle block pointer types. 7732 if (!IsRelational && LHSType->isBlockPointerType() && 7733 RHSType->isBlockPointerType()) { 7734 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7735 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7736 7737 if (!LHSIsNull && !RHSIsNull && 7738 !Context.typesAreCompatible(lpointee, rpointee)) { 7739 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7740 << LHSType << RHSType << LHS.get()->getSourceRange() 7741 << RHS.get()->getSourceRange(); 7742 } 7743 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7744 return ResultTy; 7745 } 7746 7747 // Allow block pointers to be compared with null pointer constants. 7748 if (!IsRelational 7749 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7750 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7751 if (!LHSIsNull && !RHSIsNull) { 7752 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7753 ->getPointeeType()->isVoidType()) 7754 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7755 ->getPointeeType()->isVoidType()))) 7756 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7757 << LHSType << RHSType << LHS.get()->getSourceRange() 7758 << RHS.get()->getSourceRange(); 7759 } 7760 if (LHSIsNull && !RHSIsNull) 7761 LHS = ImpCastExprToType(LHS.take(), RHSType, 7762 RHSType->isPointerType() ? CK_BitCast 7763 : CK_AnyPointerToBlockPointerCast); 7764 else 7765 RHS = ImpCastExprToType(RHS.take(), LHSType, 7766 LHSType->isPointerType() ? CK_BitCast 7767 : CK_AnyPointerToBlockPointerCast); 7768 return ResultTy; 7769 } 7770 7771 if (LHSType->isObjCObjectPointerType() || 7772 RHSType->isObjCObjectPointerType()) { 7773 const PointerType *LPT = LHSType->getAs<PointerType>(); 7774 const PointerType *RPT = RHSType->getAs<PointerType>(); 7775 if (LPT || RPT) { 7776 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7777 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7778 7779 if (!LPtrToVoid && !RPtrToVoid && 7780 !Context.typesAreCompatible(LHSType, RHSType)) { 7781 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7782 /*isError*/false); 7783 } 7784 if (LHSIsNull && !RHSIsNull) { 7785 Expr *E = LHS.take(); 7786 if (getLangOpts().ObjCAutoRefCount) 7787 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 7788 LHS = ImpCastExprToType(E, RHSType, 7789 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7790 } 7791 else { 7792 Expr *E = RHS.take(); 7793 if (getLangOpts().ObjCAutoRefCount) 7794 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 7795 RHS = ImpCastExprToType(E, LHSType, 7796 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7797 } 7798 return ResultTy; 7799 } 7800 if (LHSType->isObjCObjectPointerType() && 7801 RHSType->isObjCObjectPointerType()) { 7802 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7803 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7804 /*isError*/false); 7805 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7806 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7807 7808 if (LHSIsNull && !RHSIsNull) 7809 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7810 else 7811 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7812 return ResultTy; 7813 } 7814 } 7815 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7816 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7817 unsigned DiagID = 0; 7818 bool isError = false; 7819 if (LangOpts.DebuggerSupport) { 7820 // Under a debugger, allow the comparison of pointers to integers, 7821 // since users tend to want to compare addresses. 7822 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7823 (RHSIsNull && RHSType->isIntegerType())) { 7824 if (IsRelational && !getLangOpts().CPlusPlus) 7825 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7826 } else if (IsRelational && !getLangOpts().CPlusPlus) 7827 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7828 else if (getLangOpts().CPlusPlus) { 7829 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7830 isError = true; 7831 } else 7832 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7833 7834 if (DiagID) { 7835 Diag(Loc, DiagID) 7836 << LHSType << RHSType << LHS.get()->getSourceRange() 7837 << RHS.get()->getSourceRange(); 7838 if (isError) 7839 return QualType(); 7840 } 7841 7842 if (LHSType->isIntegerType()) 7843 LHS = ImpCastExprToType(LHS.take(), RHSType, 7844 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7845 else 7846 RHS = ImpCastExprToType(RHS.take(), LHSType, 7847 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7848 return ResultTy; 7849 } 7850 7851 // Handle block pointers. 7852 if (!IsRelational && RHSIsNull 7853 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7854 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7855 return ResultTy; 7856 } 7857 if (!IsRelational && LHSIsNull 7858 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7859 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7860 return ResultTy; 7861 } 7862 7863 return InvalidOperands(Loc, LHS, RHS); 7864 } 7865 7866 7867 // Return a signed type that is of identical size and number of elements. 7868 // For floating point vectors, return an integer type of identical size 7869 // and number of elements. 7870 QualType Sema::GetSignedVectorType(QualType V) { 7871 const VectorType *VTy = V->getAs<VectorType>(); 7872 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7873 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7874 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7875 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7876 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7877 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7878 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7879 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7880 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7881 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7882 "Unhandled vector element size in vector compare"); 7883 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7884 } 7885 7886 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7887 /// operates on extended vector types. Instead of producing an IntTy result, 7888 /// like a scalar comparison, a vector comparison produces a vector of integer 7889 /// types. 7890 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7891 SourceLocation Loc, 7892 bool IsRelational) { 7893 // Check to make sure we're operating on vectors of the same type and width, 7894 // Allowing one side to be a scalar of element type. 7895 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7896 if (vType.isNull()) 7897 return vType; 7898 7899 QualType LHSType = LHS.get()->getType(); 7900 7901 // If AltiVec, the comparison results in a numeric type, i.e. 7902 // bool for C++, int for C 7903 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7904 return Context.getLogicalOperationType(); 7905 7906 // For non-floating point types, check for self-comparisons of the form 7907 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7908 // often indicate logic errors in the program. 7909 if (!LHSType->hasFloatingRepresentation()) { 7910 if (DeclRefExpr* DRL 7911 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7912 if (DeclRefExpr* DRR 7913 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7914 if (DRL->getDecl() == DRR->getDecl()) 7915 DiagRuntimeBehavior(Loc, 0, 7916 PDiag(diag::warn_comparison_always) 7917 << 0 // self- 7918 << 2 // "a constant" 7919 ); 7920 } 7921 7922 // Check for comparisons of floating point operands using != and ==. 7923 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7924 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7925 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7926 } 7927 7928 // Return a signed type for the vector. 7929 return GetSignedVectorType(LHSType); 7930 } 7931 7932 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7933 SourceLocation Loc) { 7934 // Ensure that either both operands are of the same vector type, or 7935 // one operand is of a vector type and the other is of its element type. 7936 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7937 if (vType.isNull()) 7938 return InvalidOperands(Loc, LHS, RHS); 7939 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 7940 vType->hasFloatingRepresentation()) 7941 return InvalidOperands(Loc, LHS, RHS); 7942 7943 return GetSignedVectorType(LHS.get()->getType()); 7944 } 7945 7946 inline QualType Sema::CheckBitwiseOperands( 7947 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7948 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7949 7950 if (LHS.get()->getType()->isVectorType() || 7951 RHS.get()->getType()->isVectorType()) { 7952 if (LHS.get()->getType()->hasIntegerRepresentation() && 7953 RHS.get()->getType()->hasIntegerRepresentation()) 7954 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7955 7956 return InvalidOperands(Loc, LHS, RHS); 7957 } 7958 7959 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7960 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7961 IsCompAssign); 7962 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7963 return QualType(); 7964 LHS = LHSResult.take(); 7965 RHS = RHSResult.take(); 7966 7967 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7968 return compType; 7969 return InvalidOperands(Loc, LHS, RHS); 7970 } 7971 7972 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7973 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7974 7975 // Check vector operands differently. 7976 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7977 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7978 7979 // Diagnose cases where the user write a logical and/or but probably meant a 7980 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7981 // is a constant. 7982 if (LHS.get()->getType()->isIntegerType() && 7983 !LHS.get()->getType()->isBooleanType() && 7984 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7985 // Don't warn in macros or template instantiations. 7986 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7987 // If the RHS can be constant folded, and if it constant folds to something 7988 // that isn't 0 or 1 (which indicate a potential logical operation that 7989 // happened to fold to true/false) then warn. 7990 // Parens on the RHS are ignored. 7991 llvm::APSInt Result; 7992 if (RHS.get()->EvaluateAsInt(Result, Context)) 7993 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7994 (Result != 0 && Result != 1)) { 7995 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7996 << RHS.get()->getSourceRange() 7997 << (Opc == BO_LAnd ? "&&" : "||"); 7998 // Suggest replacing the logical operator with the bitwise version 7999 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8000 << (Opc == BO_LAnd ? "&" : "|") 8001 << FixItHint::CreateReplacement(SourceRange( 8002 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8003 getLangOpts())), 8004 Opc == BO_LAnd ? "&" : "|"); 8005 if (Opc == BO_LAnd) 8006 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8007 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8008 << FixItHint::CreateRemoval( 8009 SourceRange( 8010 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8011 0, getSourceManager(), 8012 getLangOpts()), 8013 RHS.get()->getLocEnd())); 8014 } 8015 } 8016 8017 if (!Context.getLangOpts().CPlusPlus) { 8018 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8019 // not operate on the built-in scalar and vector float types. 8020 if (Context.getLangOpts().OpenCL && 8021 Context.getLangOpts().OpenCLVersion < 120) { 8022 if (LHS.get()->getType()->isFloatingType() || 8023 RHS.get()->getType()->isFloatingType()) 8024 return InvalidOperands(Loc, LHS, RHS); 8025 } 8026 8027 LHS = UsualUnaryConversions(LHS.take()); 8028 if (LHS.isInvalid()) 8029 return QualType(); 8030 8031 RHS = UsualUnaryConversions(RHS.take()); 8032 if (RHS.isInvalid()) 8033 return QualType(); 8034 8035 if (!LHS.get()->getType()->isScalarType() || 8036 !RHS.get()->getType()->isScalarType()) 8037 return InvalidOperands(Loc, LHS, RHS); 8038 8039 return Context.IntTy; 8040 } 8041 8042 // The following is safe because we only use this method for 8043 // non-overloadable operands. 8044 8045 // C++ [expr.log.and]p1 8046 // C++ [expr.log.or]p1 8047 // The operands are both contextually converted to type bool. 8048 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8049 if (LHSRes.isInvalid()) 8050 return InvalidOperands(Loc, LHS, RHS); 8051 LHS = LHSRes; 8052 8053 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8054 if (RHSRes.isInvalid()) 8055 return InvalidOperands(Loc, LHS, RHS); 8056 RHS = RHSRes; 8057 8058 // C++ [expr.log.and]p2 8059 // C++ [expr.log.or]p2 8060 // The result is a bool. 8061 return Context.BoolTy; 8062 } 8063 8064 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8065 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8066 if (!ME) return false; 8067 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8068 ObjCMessageExpr *Base = 8069 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8070 if (!Base) return false; 8071 return Base->getMethodDecl() != 0; 8072 } 8073 8074 /// Is the given expression (which must be 'const') a reference to a 8075 /// variable which was originally non-const, but which has become 8076 /// 'const' due to being captured within a block? 8077 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8078 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8079 assert(E->isLValue() && E->getType().isConstQualified()); 8080 E = E->IgnoreParens(); 8081 8082 // Must be a reference to a declaration from an enclosing scope. 8083 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8084 if (!DRE) return NCCK_None; 8085 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8086 8087 // The declaration must be a variable which is not declared 'const'. 8088 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8089 if (!var) return NCCK_None; 8090 if (var->getType().isConstQualified()) return NCCK_None; 8091 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8092 8093 // Decide whether the first capture was for a block or a lambda. 8094 DeclContext *DC = S.CurContext; 8095 while (DC->getParent() != var->getDeclContext()) 8096 DC = DC->getParent(); 8097 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8098 } 8099 8100 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8101 /// emit an error and return true. If so, return false. 8102 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8103 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8104 SourceLocation OrigLoc = Loc; 8105 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8106 &Loc); 8107 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8108 IsLV = Expr::MLV_InvalidMessageExpression; 8109 if (IsLV == Expr::MLV_Valid) 8110 return false; 8111 8112 unsigned Diag = 0; 8113 bool NeedType = false; 8114 switch (IsLV) { // C99 6.5.16p2 8115 case Expr::MLV_ConstQualified: 8116 Diag = diag::err_typecheck_assign_const; 8117 8118 // Use a specialized diagnostic when we're assigning to an object 8119 // from an enclosing function or block. 8120 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8121 if (NCCK == NCCK_Block) 8122 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8123 else 8124 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8125 break; 8126 } 8127 8128 // In ARC, use some specialized diagnostics for occasions where we 8129 // infer 'const'. These are always pseudo-strong variables. 8130 if (S.getLangOpts().ObjCAutoRefCount) { 8131 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8132 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8133 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8134 8135 // Use the normal diagnostic if it's pseudo-__strong but the 8136 // user actually wrote 'const'. 8137 if (var->isARCPseudoStrong() && 8138 (!var->getTypeSourceInfo() || 8139 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8140 // There are two pseudo-strong cases: 8141 // - self 8142 ObjCMethodDecl *method = S.getCurMethodDecl(); 8143 if (method && var == method->getSelfDecl()) 8144 Diag = method->isClassMethod() 8145 ? diag::err_typecheck_arc_assign_self_class_method 8146 : diag::err_typecheck_arc_assign_self; 8147 8148 // - fast enumeration variables 8149 else 8150 Diag = diag::err_typecheck_arr_assign_enumeration; 8151 8152 SourceRange Assign; 8153 if (Loc != OrigLoc) 8154 Assign = SourceRange(OrigLoc, OrigLoc); 8155 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8156 // We need to preserve the AST regardless, so migration tool 8157 // can do its job. 8158 return false; 8159 } 8160 } 8161 } 8162 8163 break; 8164 case Expr::MLV_ArrayType: 8165 case Expr::MLV_ArrayTemporary: 8166 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8167 NeedType = true; 8168 break; 8169 case Expr::MLV_NotObjectType: 8170 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8171 NeedType = true; 8172 break; 8173 case Expr::MLV_LValueCast: 8174 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8175 break; 8176 case Expr::MLV_Valid: 8177 llvm_unreachable("did not take early return for MLV_Valid"); 8178 case Expr::MLV_InvalidExpression: 8179 case Expr::MLV_MemberFunction: 8180 case Expr::MLV_ClassTemporary: 8181 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8182 break; 8183 case Expr::MLV_IncompleteType: 8184 case Expr::MLV_IncompleteVoidType: 8185 return S.RequireCompleteType(Loc, E->getType(), 8186 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8187 case Expr::MLV_DuplicateVectorComponents: 8188 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8189 break; 8190 case Expr::MLV_NoSetterProperty: 8191 llvm_unreachable("readonly properties should be processed differently"); 8192 case Expr::MLV_InvalidMessageExpression: 8193 Diag = diag::error_readonly_message_assignment; 8194 break; 8195 case Expr::MLV_SubObjCPropertySetting: 8196 Diag = diag::error_no_subobject_property_setting; 8197 break; 8198 } 8199 8200 SourceRange Assign; 8201 if (Loc != OrigLoc) 8202 Assign = SourceRange(OrigLoc, OrigLoc); 8203 if (NeedType) 8204 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8205 else 8206 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8207 return true; 8208 } 8209 8210 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8211 SourceLocation Loc, 8212 Sema &Sema) { 8213 // C / C++ fields 8214 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8215 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8216 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8217 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8218 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8219 } 8220 8221 // Objective-C instance variables 8222 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8223 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8224 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8225 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8226 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8227 if (RL && RR && RL->getDecl() == RR->getDecl()) 8228 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8229 } 8230 } 8231 8232 // C99 6.5.16.1 8233 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8234 SourceLocation Loc, 8235 QualType CompoundType) { 8236 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8237 8238 // Verify that LHS is a modifiable lvalue, and emit error if not. 8239 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8240 return QualType(); 8241 8242 QualType LHSType = LHSExpr->getType(); 8243 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8244 CompoundType; 8245 AssignConvertType ConvTy; 8246 if (CompoundType.isNull()) { 8247 Expr *RHSCheck = RHS.get(); 8248 8249 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8250 8251 QualType LHSTy(LHSType); 8252 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8253 if (RHS.isInvalid()) 8254 return QualType(); 8255 // Special case of NSObject attributes on c-style pointer types. 8256 if (ConvTy == IncompatiblePointer && 8257 ((Context.isObjCNSObjectType(LHSType) && 8258 RHSType->isObjCObjectPointerType()) || 8259 (Context.isObjCNSObjectType(RHSType) && 8260 LHSType->isObjCObjectPointerType()))) 8261 ConvTy = Compatible; 8262 8263 if (ConvTy == Compatible && 8264 LHSType->isObjCObjectType()) 8265 Diag(Loc, diag::err_objc_object_assignment) 8266 << LHSType; 8267 8268 // If the RHS is a unary plus or minus, check to see if they = and + are 8269 // right next to each other. If so, the user may have typo'd "x =+ 4" 8270 // instead of "x += 4". 8271 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8272 RHSCheck = ICE->getSubExpr(); 8273 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8274 if ((UO->getOpcode() == UO_Plus || 8275 UO->getOpcode() == UO_Minus) && 8276 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8277 // Only if the two operators are exactly adjacent. 8278 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8279 // And there is a space or other character before the subexpr of the 8280 // unary +/-. We don't want to warn on "x=-1". 8281 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8282 UO->getSubExpr()->getLocStart().isFileID()) { 8283 Diag(Loc, diag::warn_not_compound_assign) 8284 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8285 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8286 } 8287 } 8288 8289 if (ConvTy == Compatible) { 8290 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8291 // Warn about retain cycles where a block captures the LHS, but 8292 // not if the LHS is a simple variable into which the block is 8293 // being stored...unless that variable can be captured by reference! 8294 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8295 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8296 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8297 checkRetainCycles(LHSExpr, RHS.get()); 8298 8299 // It is safe to assign a weak reference into a strong variable. 8300 // Although this code can still have problems: 8301 // id x = self.weakProp; 8302 // id y = self.weakProp; 8303 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8304 // paths through the function. This should be revisited if 8305 // -Wrepeated-use-of-weak is made flow-sensitive. 8306 DiagnosticsEngine::Level Level = 8307 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8308 RHS.get()->getLocStart()); 8309 if (Level != DiagnosticsEngine::Ignored) 8310 getCurFunction()->markSafeWeakUse(RHS.get()); 8311 8312 } else if (getLangOpts().ObjCAutoRefCount) { 8313 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8314 } 8315 } 8316 } else { 8317 // Compound assignment "x += y" 8318 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8319 } 8320 8321 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8322 RHS.get(), AA_Assigning)) 8323 return QualType(); 8324 8325 CheckForNullPointerDereference(*this, LHSExpr); 8326 8327 // C99 6.5.16p3: The type of an assignment expression is the type of the 8328 // left operand unless the left operand has qualified type, in which case 8329 // it is the unqualified version of the type of the left operand. 8330 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8331 // is converted to the type of the assignment expression (above). 8332 // C++ 5.17p1: the type of the assignment expression is that of its left 8333 // operand. 8334 return (getLangOpts().CPlusPlus 8335 ? LHSType : LHSType.getUnqualifiedType()); 8336 } 8337 8338 // C99 6.5.17 8339 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8340 SourceLocation Loc) { 8341 LHS = S.CheckPlaceholderExpr(LHS.take()); 8342 RHS = S.CheckPlaceholderExpr(RHS.take()); 8343 if (LHS.isInvalid() || RHS.isInvalid()) 8344 return QualType(); 8345 8346 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8347 // operands, but not unary promotions. 8348 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8349 8350 // So we treat the LHS as a ignored value, and in C++ we allow the 8351 // containing site to determine what should be done with the RHS. 8352 LHS = S.IgnoredValueConversions(LHS.take()); 8353 if (LHS.isInvalid()) 8354 return QualType(); 8355 8356 S.DiagnoseUnusedExprResult(LHS.get()); 8357 8358 if (!S.getLangOpts().CPlusPlus) { 8359 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8360 if (RHS.isInvalid()) 8361 return QualType(); 8362 if (!RHS.get()->getType()->isVoidType()) 8363 S.RequireCompleteType(Loc, RHS.get()->getType(), 8364 diag::err_incomplete_type); 8365 } 8366 8367 return RHS.get()->getType(); 8368 } 8369 8370 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8371 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8372 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8373 ExprValueKind &VK, 8374 SourceLocation OpLoc, 8375 bool IsInc, bool IsPrefix) { 8376 if (Op->isTypeDependent()) 8377 return S.Context.DependentTy; 8378 8379 QualType ResType = Op->getType(); 8380 // Atomic types can be used for increment / decrement where the non-atomic 8381 // versions can, so ignore the _Atomic() specifier for the purpose of 8382 // checking. 8383 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8384 ResType = ResAtomicType->getValueType(); 8385 8386 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8387 8388 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8389 // Decrement of bool is not allowed. 8390 if (!IsInc) { 8391 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8392 return QualType(); 8393 } 8394 // Increment of bool sets it to true, but is deprecated. 8395 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8396 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8397 // Error on enum increments and decrements in C++ mode 8398 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8399 return QualType(); 8400 } else if (ResType->isRealType()) { 8401 // OK! 8402 } else if (ResType->isPointerType()) { 8403 // C99 6.5.2.4p2, 6.5.6p2 8404 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8405 return QualType(); 8406 } else if (ResType->isObjCObjectPointerType()) { 8407 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8408 // Otherwise, we just need a complete type. 8409 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8410 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8411 return QualType(); 8412 } else if (ResType->isAnyComplexType()) { 8413 // C99 does not support ++/-- on complex types, we allow as an extension. 8414 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8415 << ResType << Op->getSourceRange(); 8416 } else if (ResType->isPlaceholderType()) { 8417 ExprResult PR = S.CheckPlaceholderExpr(Op); 8418 if (PR.isInvalid()) return QualType(); 8419 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8420 IsInc, IsPrefix); 8421 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8422 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8423 } else { 8424 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8425 << ResType << int(IsInc) << Op->getSourceRange(); 8426 return QualType(); 8427 } 8428 // At this point, we know we have a real, complex or pointer type. 8429 // Now make sure the operand is a modifiable lvalue. 8430 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8431 return QualType(); 8432 // In C++, a prefix increment is the same type as the operand. Otherwise 8433 // (in C or with postfix), the increment is the unqualified type of the 8434 // operand. 8435 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8436 VK = VK_LValue; 8437 return ResType; 8438 } else { 8439 VK = VK_RValue; 8440 return ResType.getUnqualifiedType(); 8441 } 8442 } 8443 8444 8445 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8446 /// This routine allows us to typecheck complex/recursive expressions 8447 /// where the declaration is needed for type checking. We only need to 8448 /// handle cases when the expression references a function designator 8449 /// or is an lvalue. Here are some examples: 8450 /// - &(x) => x 8451 /// - &*****f => f for f a function designator. 8452 /// - &s.xx => s 8453 /// - &s.zz[1].yy -> s, if zz is an array 8454 /// - *(x + 1) -> x, if x is an array 8455 /// - &"123"[2] -> 0 8456 /// - & __real__ x -> x 8457 static ValueDecl *getPrimaryDecl(Expr *E) { 8458 switch (E->getStmtClass()) { 8459 case Stmt::DeclRefExprClass: 8460 return cast<DeclRefExpr>(E)->getDecl(); 8461 case Stmt::MemberExprClass: 8462 // If this is an arrow operator, the address is an offset from 8463 // the base's value, so the object the base refers to is 8464 // irrelevant. 8465 if (cast<MemberExpr>(E)->isArrow()) 8466 return 0; 8467 // Otherwise, the expression refers to a part of the base 8468 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8469 case Stmt::ArraySubscriptExprClass: { 8470 // FIXME: This code shouldn't be necessary! We should catch the implicit 8471 // promotion of register arrays earlier. 8472 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8473 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8474 if (ICE->getSubExpr()->getType()->isArrayType()) 8475 return getPrimaryDecl(ICE->getSubExpr()); 8476 } 8477 return 0; 8478 } 8479 case Stmt::UnaryOperatorClass: { 8480 UnaryOperator *UO = cast<UnaryOperator>(E); 8481 8482 switch(UO->getOpcode()) { 8483 case UO_Real: 8484 case UO_Imag: 8485 case UO_Extension: 8486 return getPrimaryDecl(UO->getSubExpr()); 8487 default: 8488 return 0; 8489 } 8490 } 8491 case Stmt::ParenExprClass: 8492 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8493 case Stmt::ImplicitCastExprClass: 8494 // If the result of an implicit cast is an l-value, we care about 8495 // the sub-expression; otherwise, the result here doesn't matter. 8496 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8497 default: 8498 return 0; 8499 } 8500 } 8501 8502 namespace { 8503 enum { 8504 AO_Bit_Field = 0, 8505 AO_Vector_Element = 1, 8506 AO_Property_Expansion = 2, 8507 AO_Register_Variable = 3, 8508 AO_No_Error = 4 8509 }; 8510 } 8511 /// \brief Diagnose invalid operand for address of operations. 8512 /// 8513 /// \param Type The type of operand which cannot have its address taken. 8514 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8515 Expr *E, unsigned Type) { 8516 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8517 } 8518 8519 /// CheckAddressOfOperand - The operand of & must be either a function 8520 /// designator or an lvalue designating an object. If it is an lvalue, the 8521 /// object cannot be declared with storage class register or be a bit field. 8522 /// Note: The usual conversions are *not* applied to the operand of the & 8523 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8524 /// In C++, the operand might be an overloaded function name, in which case 8525 /// we allow the '&' but retain the overloaded-function type. 8526 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8527 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8528 if (PTy->getKind() == BuiltinType::Overload) { 8529 Expr *E = OrigOp.get()->IgnoreParens(); 8530 if (!isa<OverloadExpr>(E)) { 8531 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8532 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8533 << OrigOp.get()->getSourceRange(); 8534 return QualType(); 8535 } 8536 8537 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8538 if (isa<UnresolvedMemberExpr>(Ovl)) 8539 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8540 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8541 << OrigOp.get()->getSourceRange(); 8542 return QualType(); 8543 } 8544 8545 return Context.OverloadTy; 8546 } 8547 8548 if (PTy->getKind() == BuiltinType::UnknownAny) 8549 return Context.UnknownAnyTy; 8550 8551 if (PTy->getKind() == BuiltinType::BoundMember) { 8552 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8553 << OrigOp.get()->getSourceRange(); 8554 return QualType(); 8555 } 8556 8557 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8558 if (OrigOp.isInvalid()) return QualType(); 8559 } 8560 8561 if (OrigOp.get()->isTypeDependent()) 8562 return Context.DependentTy; 8563 8564 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8565 8566 // Make sure to ignore parentheses in subsequent checks 8567 Expr *op = OrigOp.get()->IgnoreParens(); 8568 8569 if (getLangOpts().C99) { 8570 // Implement C99-only parts of addressof rules. 8571 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8572 if (uOp->getOpcode() == UO_Deref) 8573 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8574 // (assuming the deref expression is valid). 8575 return uOp->getSubExpr()->getType(); 8576 } 8577 // Technically, there should be a check for array subscript 8578 // expressions here, but the result of one is always an lvalue anyway. 8579 } 8580 ValueDecl *dcl = getPrimaryDecl(op); 8581 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8582 unsigned AddressOfError = AO_No_Error; 8583 8584 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8585 bool sfinae = (bool)isSFINAEContext(); 8586 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8587 : diag::ext_typecheck_addrof_temporary) 8588 << op->getType() << op->getSourceRange(); 8589 if (sfinae) 8590 return QualType(); 8591 // Materialize the temporary as an lvalue so that we can take its address. 8592 OrigOp = op = new (Context) 8593 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8594 } else if (isa<ObjCSelectorExpr>(op)) { 8595 return Context.getPointerType(op->getType()); 8596 } else if (lval == Expr::LV_MemberFunction) { 8597 // If it's an instance method, make a member pointer. 8598 // The expression must have exactly the form &A::foo. 8599 8600 // If the underlying expression isn't a decl ref, give up. 8601 if (!isa<DeclRefExpr>(op)) { 8602 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8603 << OrigOp.get()->getSourceRange(); 8604 return QualType(); 8605 } 8606 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8607 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8608 8609 // The id-expression was parenthesized. 8610 if (OrigOp.get() != DRE) { 8611 Diag(OpLoc, diag::err_parens_pointer_member_function) 8612 << OrigOp.get()->getSourceRange(); 8613 8614 // The method was named without a qualifier. 8615 } else if (!DRE->getQualifier()) { 8616 if (MD->getParent()->getName().empty()) 8617 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8618 << op->getSourceRange(); 8619 else { 8620 SmallString<32> Str; 8621 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8622 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8623 << op->getSourceRange() 8624 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8625 } 8626 } 8627 8628 return Context.getMemberPointerType(op->getType(), 8629 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8630 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8631 // C99 6.5.3.2p1 8632 // The operand must be either an l-value or a function designator 8633 if (!op->getType()->isFunctionType()) { 8634 // Use a special diagnostic for loads from property references. 8635 if (isa<PseudoObjectExpr>(op)) { 8636 AddressOfError = AO_Property_Expansion; 8637 } else { 8638 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8639 << op->getType() << op->getSourceRange(); 8640 return QualType(); 8641 } 8642 } 8643 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8644 // The operand cannot be a bit-field 8645 AddressOfError = AO_Bit_Field; 8646 } else if (op->getObjectKind() == OK_VectorComponent) { 8647 // The operand cannot be an element of a vector 8648 AddressOfError = AO_Vector_Element; 8649 } else if (dcl) { // C99 6.5.3.2p1 8650 // We have an lvalue with a decl. Make sure the decl is not declared 8651 // with the register storage-class specifier. 8652 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8653 // in C++ it is not error to take address of a register 8654 // variable (c++03 7.1.1P3) 8655 if (vd->getStorageClass() == SC_Register && 8656 !getLangOpts().CPlusPlus) { 8657 AddressOfError = AO_Register_Variable; 8658 } 8659 } else if (isa<FunctionTemplateDecl>(dcl)) { 8660 return Context.OverloadTy; 8661 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8662 // Okay: we can take the address of a field. 8663 // Could be a pointer to member, though, if there is an explicit 8664 // scope qualifier for the class. 8665 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8666 DeclContext *Ctx = dcl->getDeclContext(); 8667 if (Ctx && Ctx->isRecord()) { 8668 if (dcl->getType()->isReferenceType()) { 8669 Diag(OpLoc, 8670 diag::err_cannot_form_pointer_to_member_of_reference_type) 8671 << dcl->getDeclName() << dcl->getType(); 8672 return QualType(); 8673 } 8674 8675 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8676 Ctx = Ctx->getParent(); 8677 return Context.getMemberPointerType(op->getType(), 8678 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8679 } 8680 } 8681 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8682 llvm_unreachable("Unknown/unexpected decl type"); 8683 } 8684 8685 if (AddressOfError != AO_No_Error) { 8686 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8687 return QualType(); 8688 } 8689 8690 if (lval == Expr::LV_IncompleteVoidType) { 8691 // Taking the address of a void variable is technically illegal, but we 8692 // allow it in cases which are otherwise valid. 8693 // Example: "extern void x; void* y = &x;". 8694 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8695 } 8696 8697 // If the operand has type "type", the result has type "pointer to type". 8698 if (op->getType()->isObjCObjectType()) 8699 return Context.getObjCObjectPointerType(op->getType()); 8700 return Context.getPointerType(op->getType()); 8701 } 8702 8703 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8704 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8705 SourceLocation OpLoc) { 8706 if (Op->isTypeDependent()) 8707 return S.Context.DependentTy; 8708 8709 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8710 if (ConvResult.isInvalid()) 8711 return QualType(); 8712 Op = ConvResult.take(); 8713 QualType OpTy = Op->getType(); 8714 QualType Result; 8715 8716 if (isa<CXXReinterpretCastExpr>(Op)) { 8717 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8718 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8719 Op->getSourceRange()); 8720 } 8721 8722 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8723 // is an incomplete type or void. It would be possible to warn about 8724 // dereferencing a void pointer, but it's completely well-defined, and such a 8725 // warning is unlikely to catch any mistakes. 8726 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8727 Result = PT->getPointeeType(); 8728 else if (const ObjCObjectPointerType *OPT = 8729 OpTy->getAs<ObjCObjectPointerType>()) 8730 Result = OPT->getPointeeType(); 8731 else { 8732 ExprResult PR = S.CheckPlaceholderExpr(Op); 8733 if (PR.isInvalid()) return QualType(); 8734 if (PR.take() != Op) 8735 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8736 } 8737 8738 if (Result.isNull()) { 8739 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8740 << OpTy << Op->getSourceRange(); 8741 return QualType(); 8742 } 8743 8744 // Dereferences are usually l-values... 8745 VK = VK_LValue; 8746 8747 // ...except that certain expressions are never l-values in C. 8748 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8749 VK = VK_RValue; 8750 8751 return Result; 8752 } 8753 8754 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8755 tok::TokenKind Kind) { 8756 BinaryOperatorKind Opc; 8757 switch (Kind) { 8758 default: llvm_unreachable("Unknown binop!"); 8759 case tok::periodstar: Opc = BO_PtrMemD; break; 8760 case tok::arrowstar: Opc = BO_PtrMemI; break; 8761 case tok::star: Opc = BO_Mul; break; 8762 case tok::slash: Opc = BO_Div; break; 8763 case tok::percent: Opc = BO_Rem; break; 8764 case tok::plus: Opc = BO_Add; break; 8765 case tok::minus: Opc = BO_Sub; break; 8766 case tok::lessless: Opc = BO_Shl; break; 8767 case tok::greatergreater: Opc = BO_Shr; break; 8768 case tok::lessequal: Opc = BO_LE; break; 8769 case tok::less: Opc = BO_LT; break; 8770 case tok::greaterequal: Opc = BO_GE; break; 8771 case tok::greater: Opc = BO_GT; break; 8772 case tok::exclaimequal: Opc = BO_NE; break; 8773 case tok::equalequal: Opc = BO_EQ; break; 8774 case tok::amp: Opc = BO_And; break; 8775 case tok::caret: Opc = BO_Xor; break; 8776 case tok::pipe: Opc = BO_Or; break; 8777 case tok::ampamp: Opc = BO_LAnd; break; 8778 case tok::pipepipe: Opc = BO_LOr; break; 8779 case tok::equal: Opc = BO_Assign; break; 8780 case tok::starequal: Opc = BO_MulAssign; break; 8781 case tok::slashequal: Opc = BO_DivAssign; break; 8782 case tok::percentequal: Opc = BO_RemAssign; break; 8783 case tok::plusequal: Opc = BO_AddAssign; break; 8784 case tok::minusequal: Opc = BO_SubAssign; break; 8785 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8786 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8787 case tok::ampequal: Opc = BO_AndAssign; break; 8788 case tok::caretequal: Opc = BO_XorAssign; break; 8789 case tok::pipeequal: Opc = BO_OrAssign; break; 8790 case tok::comma: Opc = BO_Comma; break; 8791 } 8792 return Opc; 8793 } 8794 8795 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8796 tok::TokenKind Kind) { 8797 UnaryOperatorKind Opc; 8798 switch (Kind) { 8799 default: llvm_unreachable("Unknown unary op!"); 8800 case tok::plusplus: Opc = UO_PreInc; break; 8801 case tok::minusminus: Opc = UO_PreDec; break; 8802 case tok::amp: Opc = UO_AddrOf; break; 8803 case tok::star: Opc = UO_Deref; break; 8804 case tok::plus: Opc = UO_Plus; break; 8805 case tok::minus: Opc = UO_Minus; break; 8806 case tok::tilde: Opc = UO_Not; break; 8807 case tok::exclaim: Opc = UO_LNot; break; 8808 case tok::kw___real: Opc = UO_Real; break; 8809 case tok::kw___imag: Opc = UO_Imag; break; 8810 case tok::kw___extension__: Opc = UO_Extension; break; 8811 } 8812 return Opc; 8813 } 8814 8815 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8816 /// This warning is only emitted for builtin assignment operations. It is also 8817 /// suppressed in the event of macro expansions. 8818 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8819 SourceLocation OpLoc) { 8820 if (!S.ActiveTemplateInstantiations.empty()) 8821 return; 8822 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8823 return; 8824 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8825 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8826 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8827 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8828 if (!LHSDeclRef || !RHSDeclRef || 8829 LHSDeclRef->getLocation().isMacroID() || 8830 RHSDeclRef->getLocation().isMacroID()) 8831 return; 8832 const ValueDecl *LHSDecl = 8833 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8834 const ValueDecl *RHSDecl = 8835 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8836 if (LHSDecl != RHSDecl) 8837 return; 8838 if (LHSDecl->getType().isVolatileQualified()) 8839 return; 8840 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8841 if (RefTy->getPointeeType().isVolatileQualified()) 8842 return; 8843 8844 S.Diag(OpLoc, diag::warn_self_assignment) 8845 << LHSDeclRef->getType() 8846 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8847 } 8848 8849 /// Check if a bitwise-& is performed on an Objective-C pointer. This 8850 /// is usually indicative of introspection within the Objective-C pointer. 8851 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 8852 SourceLocation OpLoc) { 8853 if (!S.getLangOpts().ObjC1) 8854 return; 8855 8856 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 8857 const Expr *LHS = L.get(); 8858 const Expr *RHS = R.get(); 8859 8860 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8861 ObjCPointerExpr = LHS; 8862 OtherExpr = RHS; 8863 } 8864 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8865 ObjCPointerExpr = RHS; 8866 OtherExpr = LHS; 8867 } 8868 8869 // This warning is deliberately made very specific to reduce false 8870 // positives with logic that uses '&' for hashing. This logic mainly 8871 // looks for code trying to introspect into tagged pointers, which 8872 // code should generally never do. 8873 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 8874 unsigned Diag = diag::warn_objc_pointer_masking; 8875 // Determine if we are introspecting the result of performSelectorXXX. 8876 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 8877 // Special case messages to -performSelector and friends, which 8878 // can return non-pointer values boxed in a pointer value. 8879 // Some clients may wish to silence warnings in this subcase. 8880 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 8881 Selector S = ME->getSelector(); 8882 StringRef SelArg0 = S.getNameForSlot(0); 8883 if (SelArg0.startswith("performSelector")) 8884 Diag = diag::warn_objc_pointer_masking_performSelector; 8885 } 8886 8887 S.Diag(OpLoc, Diag) 8888 << ObjCPointerExpr->getSourceRange(); 8889 } 8890 } 8891 8892 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 8893 /// operator @p Opc at location @c TokLoc. This routine only supports 8894 /// built-in operations; ActOnBinOp handles overloaded operators. 8895 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8896 BinaryOperatorKind Opc, 8897 Expr *LHSExpr, Expr *RHSExpr) { 8898 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 8899 // The syntax only allows initializer lists on the RHS of assignment, 8900 // so we don't need to worry about accepting invalid code for 8901 // non-assignment operators. 8902 // C++11 5.17p9: 8903 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8904 // of x = {} is x = T(). 8905 InitializationKind Kind = 8906 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8907 InitializedEntity Entity = 8908 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8909 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 8910 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8911 if (Init.isInvalid()) 8912 return Init; 8913 RHSExpr = Init.take(); 8914 } 8915 8916 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8917 QualType ResultTy; // Result type of the binary operator. 8918 // The following two variables are used for compound assignment operators 8919 QualType CompLHSTy; // Type of LHS after promotions for computation 8920 QualType CompResultTy; // Type of computation result 8921 ExprValueKind VK = VK_RValue; 8922 ExprObjectKind OK = OK_Ordinary; 8923 8924 switch (Opc) { 8925 case BO_Assign: 8926 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8927 if (getLangOpts().CPlusPlus && 8928 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8929 VK = LHS.get()->getValueKind(); 8930 OK = LHS.get()->getObjectKind(); 8931 } 8932 if (!ResultTy.isNull()) 8933 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8934 break; 8935 case BO_PtrMemD: 8936 case BO_PtrMemI: 8937 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8938 Opc == BO_PtrMemI); 8939 break; 8940 case BO_Mul: 8941 case BO_Div: 8942 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8943 Opc == BO_Div); 8944 break; 8945 case BO_Rem: 8946 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8947 break; 8948 case BO_Add: 8949 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8950 break; 8951 case BO_Sub: 8952 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8953 break; 8954 case BO_Shl: 8955 case BO_Shr: 8956 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8957 break; 8958 case BO_LE: 8959 case BO_LT: 8960 case BO_GE: 8961 case BO_GT: 8962 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8963 break; 8964 case BO_EQ: 8965 case BO_NE: 8966 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8967 break; 8968 case BO_And: 8969 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 8970 case BO_Xor: 8971 case BO_Or: 8972 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8973 break; 8974 case BO_LAnd: 8975 case BO_LOr: 8976 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8977 break; 8978 case BO_MulAssign: 8979 case BO_DivAssign: 8980 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8981 Opc == BO_DivAssign); 8982 CompLHSTy = CompResultTy; 8983 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8984 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8985 break; 8986 case BO_RemAssign: 8987 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8988 CompLHSTy = CompResultTy; 8989 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8990 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8991 break; 8992 case BO_AddAssign: 8993 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8994 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8995 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8996 break; 8997 case BO_SubAssign: 8998 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8999 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9000 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9001 break; 9002 case BO_ShlAssign: 9003 case BO_ShrAssign: 9004 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9005 CompLHSTy = CompResultTy; 9006 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9007 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9008 break; 9009 case BO_AndAssign: 9010 case BO_XorAssign: 9011 case BO_OrAssign: 9012 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9013 CompLHSTy = CompResultTy; 9014 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9015 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9016 break; 9017 case BO_Comma: 9018 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9019 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9020 VK = RHS.get()->getValueKind(); 9021 OK = RHS.get()->getObjectKind(); 9022 } 9023 break; 9024 } 9025 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9026 return ExprError(); 9027 9028 // Check for array bounds violations for both sides of the BinaryOperator 9029 CheckArrayAccess(LHS.get()); 9030 CheckArrayAccess(RHS.get()); 9031 9032 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9033 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9034 &Context.Idents.get("object_setClass"), 9035 SourceLocation(), LookupOrdinaryName); 9036 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9037 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9038 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9039 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9040 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9041 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9042 } 9043 else 9044 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9045 } 9046 else if (const ObjCIvarRefExpr *OIRE = 9047 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9048 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9049 9050 if (CompResultTy.isNull()) 9051 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9052 ResultTy, VK, OK, OpLoc, 9053 FPFeatures.fp_contract)); 9054 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9055 OK_ObjCProperty) { 9056 VK = VK_LValue; 9057 OK = LHS.get()->getObjectKind(); 9058 } 9059 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9060 ResultTy, VK, OK, CompLHSTy, 9061 CompResultTy, OpLoc, 9062 FPFeatures.fp_contract)); 9063 } 9064 9065 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9066 /// operators are mixed in a way that suggests that the programmer forgot that 9067 /// comparison operators have higher precedence. The most typical example of 9068 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9069 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9070 SourceLocation OpLoc, Expr *LHSExpr, 9071 Expr *RHSExpr) { 9072 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9073 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9074 9075 // Check that one of the sides is a comparison operator. 9076 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9077 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9078 if (!isLeftComp && !isRightComp) 9079 return; 9080 9081 // Bitwise operations are sometimes used as eager logical ops. 9082 // Don't diagnose this. 9083 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9084 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9085 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9086 return; 9087 9088 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9089 OpLoc) 9090 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9091 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9092 SourceRange ParensRange = isLeftComp ? 9093 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9094 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9095 9096 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9097 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9098 SuggestParentheses(Self, OpLoc, 9099 Self.PDiag(diag::note_precedence_silence) << OpStr, 9100 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9101 SuggestParentheses(Self, OpLoc, 9102 Self.PDiag(diag::note_precedence_bitwise_first) 9103 << BinaryOperator::getOpcodeStr(Opc), 9104 ParensRange); 9105 } 9106 9107 /// \brief It accepts a '&' expr that is inside a '|' one. 9108 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9109 /// in parentheses. 9110 static void 9111 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9112 BinaryOperator *Bop) { 9113 assert(Bop->getOpcode() == BO_And); 9114 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9115 << Bop->getSourceRange() << OpLoc; 9116 SuggestParentheses(Self, Bop->getOperatorLoc(), 9117 Self.PDiag(diag::note_precedence_silence) 9118 << Bop->getOpcodeStr(), 9119 Bop->getSourceRange()); 9120 } 9121 9122 /// \brief It accepts a '&&' expr that is inside a '||' one. 9123 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9124 /// in parentheses. 9125 static void 9126 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9127 BinaryOperator *Bop) { 9128 assert(Bop->getOpcode() == BO_LAnd); 9129 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9130 << Bop->getSourceRange() << OpLoc; 9131 SuggestParentheses(Self, Bop->getOperatorLoc(), 9132 Self.PDiag(diag::note_precedence_silence) 9133 << Bop->getOpcodeStr(), 9134 Bop->getSourceRange()); 9135 } 9136 9137 /// \brief Returns true if the given expression can be evaluated as a constant 9138 /// 'true'. 9139 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9140 bool Res; 9141 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9142 } 9143 9144 /// \brief Returns true if the given expression can be evaluated as a constant 9145 /// 'false'. 9146 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9147 bool Res; 9148 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9149 } 9150 9151 /// \brief Look for '&&' in the left hand of a '||' expr. 9152 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9153 Expr *LHSExpr, Expr *RHSExpr) { 9154 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9155 if (Bop->getOpcode() == BO_LAnd) { 9156 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9157 if (EvaluatesAsFalse(S, RHSExpr)) 9158 return; 9159 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9160 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9161 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9162 } else if (Bop->getOpcode() == BO_LOr) { 9163 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9164 // If it's "a || b && 1 || c" we didn't warn earlier for 9165 // "a || b && 1", but warn now. 9166 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9167 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9168 } 9169 } 9170 } 9171 } 9172 9173 /// \brief Look for '&&' in the right hand of a '||' expr. 9174 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9175 Expr *LHSExpr, Expr *RHSExpr) { 9176 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9177 if (Bop->getOpcode() == BO_LAnd) { 9178 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9179 if (EvaluatesAsFalse(S, LHSExpr)) 9180 return; 9181 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9182 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9183 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9184 } 9185 } 9186 } 9187 9188 /// \brief Look for '&' in the left or right hand of a '|' expr. 9189 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9190 Expr *OrArg) { 9191 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9192 if (Bop->getOpcode() == BO_And) 9193 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9194 } 9195 } 9196 9197 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9198 Expr *SubExpr, StringRef Shift) { 9199 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9200 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9201 StringRef Op = Bop->getOpcodeStr(); 9202 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9203 << Bop->getSourceRange() << OpLoc << Shift << Op; 9204 SuggestParentheses(S, Bop->getOperatorLoc(), 9205 S.PDiag(diag::note_precedence_silence) << Op, 9206 Bop->getSourceRange()); 9207 } 9208 } 9209 } 9210 9211 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9212 Expr *LHSExpr, Expr *RHSExpr) { 9213 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9214 if (!OCE) 9215 return; 9216 9217 FunctionDecl *FD = OCE->getDirectCallee(); 9218 if (!FD || !FD->isOverloadedOperator()) 9219 return; 9220 9221 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9222 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9223 return; 9224 9225 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9226 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9227 << (Kind == OO_LessLess); 9228 SuggestParentheses(S, OCE->getOperatorLoc(), 9229 S.PDiag(diag::note_precedence_silence) 9230 << (Kind == OO_LessLess ? "<<" : ">>"), 9231 OCE->getSourceRange()); 9232 SuggestParentheses(S, OpLoc, 9233 S.PDiag(diag::note_evaluate_comparison_first), 9234 SourceRange(OCE->getArg(1)->getLocStart(), 9235 RHSExpr->getLocEnd())); 9236 } 9237 9238 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9239 /// precedence. 9240 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9241 SourceLocation OpLoc, Expr *LHSExpr, 9242 Expr *RHSExpr){ 9243 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9244 if (BinaryOperator::isBitwiseOp(Opc)) 9245 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9246 9247 // Diagnose "arg1 & arg2 | arg3" 9248 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9249 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9250 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9251 } 9252 9253 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9254 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9255 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9256 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9257 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9258 } 9259 9260 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9261 || Opc == BO_Shr) { 9262 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9263 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9264 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9265 } 9266 9267 // Warn on overloaded shift operators and comparisons, such as: 9268 // cout << 5 == 4; 9269 if (BinaryOperator::isComparisonOp(Opc)) 9270 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9271 } 9272 9273 // Binary Operators. 'Tok' is the token for the operator. 9274 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9275 tok::TokenKind Kind, 9276 Expr *LHSExpr, Expr *RHSExpr) { 9277 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9278 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9279 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9280 9281 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9282 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9283 9284 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9285 } 9286 9287 /// Build an overloaded binary operator expression in the given scope. 9288 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9289 BinaryOperatorKind Opc, 9290 Expr *LHS, Expr *RHS) { 9291 // Find all of the overloaded operators visible from this 9292 // point. We perform both an operator-name lookup from the local 9293 // scope and an argument-dependent lookup based on the types of 9294 // the arguments. 9295 UnresolvedSet<16> Functions; 9296 OverloadedOperatorKind OverOp 9297 = BinaryOperator::getOverloadedOperator(Opc); 9298 if (Sc && OverOp != OO_None) 9299 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9300 RHS->getType(), Functions); 9301 9302 // Build the (potentially-overloaded, potentially-dependent) 9303 // binary operation. 9304 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9305 } 9306 9307 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9308 BinaryOperatorKind Opc, 9309 Expr *LHSExpr, Expr *RHSExpr) { 9310 // We want to end up calling one of checkPseudoObjectAssignment 9311 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9312 // both expressions are overloadable or either is type-dependent), 9313 // or CreateBuiltinBinOp (in any other case). We also want to get 9314 // any placeholder types out of the way. 9315 9316 // Handle pseudo-objects in the LHS. 9317 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9318 // Assignments with a pseudo-object l-value need special analysis. 9319 if (pty->getKind() == BuiltinType::PseudoObject && 9320 BinaryOperator::isAssignmentOp(Opc)) 9321 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9322 9323 // Don't resolve overloads if the other type is overloadable. 9324 if (pty->getKind() == BuiltinType::Overload) { 9325 // We can't actually test that if we still have a placeholder, 9326 // though. Fortunately, none of the exceptions we see in that 9327 // code below are valid when the LHS is an overload set. Note 9328 // that an overload set can be dependently-typed, but it never 9329 // instantiates to having an overloadable type. 9330 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9331 if (resolvedRHS.isInvalid()) return ExprError(); 9332 RHSExpr = resolvedRHS.take(); 9333 9334 if (RHSExpr->isTypeDependent() || 9335 RHSExpr->getType()->isOverloadableType()) 9336 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9337 } 9338 9339 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9340 if (LHS.isInvalid()) return ExprError(); 9341 LHSExpr = LHS.take(); 9342 } 9343 9344 // Handle pseudo-objects in the RHS. 9345 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9346 // An overload in the RHS can potentially be resolved by the type 9347 // being assigned to. 9348 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9349 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9350 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9351 9352 if (LHSExpr->getType()->isOverloadableType()) 9353 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9354 9355 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9356 } 9357 9358 // Don't resolve overloads if the other type is overloadable. 9359 if (pty->getKind() == BuiltinType::Overload && 9360 LHSExpr->getType()->isOverloadableType()) 9361 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9362 9363 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9364 if (!resolvedRHS.isUsable()) return ExprError(); 9365 RHSExpr = resolvedRHS.take(); 9366 } 9367 9368 if (getLangOpts().CPlusPlus) { 9369 // If either expression is type-dependent, always build an 9370 // overloaded op. 9371 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9372 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9373 9374 // Otherwise, build an overloaded op if either expression has an 9375 // overloadable type. 9376 if (LHSExpr->getType()->isOverloadableType() || 9377 RHSExpr->getType()->isOverloadableType()) 9378 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9379 } 9380 9381 // Build a built-in binary operation. 9382 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9383 } 9384 9385 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9386 UnaryOperatorKind Opc, 9387 Expr *InputExpr) { 9388 ExprResult Input = Owned(InputExpr); 9389 ExprValueKind VK = VK_RValue; 9390 ExprObjectKind OK = OK_Ordinary; 9391 QualType resultType; 9392 switch (Opc) { 9393 case UO_PreInc: 9394 case UO_PreDec: 9395 case UO_PostInc: 9396 case UO_PostDec: 9397 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9398 Opc == UO_PreInc || 9399 Opc == UO_PostInc, 9400 Opc == UO_PreInc || 9401 Opc == UO_PreDec); 9402 break; 9403 case UO_AddrOf: 9404 resultType = CheckAddressOfOperand(Input, OpLoc); 9405 break; 9406 case UO_Deref: { 9407 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9408 if (Input.isInvalid()) return ExprError(); 9409 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9410 break; 9411 } 9412 case UO_Plus: 9413 case UO_Minus: 9414 Input = UsualUnaryConversions(Input.take()); 9415 if (Input.isInvalid()) return ExprError(); 9416 resultType = Input.get()->getType(); 9417 if (resultType->isDependentType()) 9418 break; 9419 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9420 resultType->isVectorType()) 9421 break; 9422 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 9423 resultType->isEnumeralType()) 9424 break; 9425 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9426 Opc == UO_Plus && 9427 resultType->isPointerType()) 9428 break; 9429 9430 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9431 << resultType << Input.get()->getSourceRange()); 9432 9433 case UO_Not: // bitwise complement 9434 Input = UsualUnaryConversions(Input.take()); 9435 if (Input.isInvalid()) 9436 return ExprError(); 9437 resultType = Input.get()->getType(); 9438 if (resultType->isDependentType()) 9439 break; 9440 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9441 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9442 // C99 does not support '~' for complex conjugation. 9443 Diag(OpLoc, diag::ext_integer_complement_complex) 9444 << resultType << Input.get()->getSourceRange(); 9445 else if (resultType->hasIntegerRepresentation()) 9446 break; 9447 else if (resultType->isExtVectorType()) { 9448 if (Context.getLangOpts().OpenCL) { 9449 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9450 // on vector float types. 9451 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9452 if (!T->isIntegerType()) 9453 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9454 << resultType << Input.get()->getSourceRange()); 9455 } 9456 break; 9457 } else { 9458 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9459 << resultType << Input.get()->getSourceRange()); 9460 } 9461 break; 9462 9463 case UO_LNot: // logical negation 9464 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9465 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9466 if (Input.isInvalid()) return ExprError(); 9467 resultType = Input.get()->getType(); 9468 9469 // Though we still have to promote half FP to float... 9470 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9471 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9472 resultType = Context.FloatTy; 9473 } 9474 9475 if (resultType->isDependentType()) 9476 break; 9477 if (resultType->isScalarType()) { 9478 // C99 6.5.3.3p1: ok, fallthrough; 9479 if (Context.getLangOpts().CPlusPlus) { 9480 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9481 // operand contextually converted to bool. 9482 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9483 ScalarTypeToBooleanCastKind(resultType)); 9484 } else if (Context.getLangOpts().OpenCL && 9485 Context.getLangOpts().OpenCLVersion < 120) { 9486 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9487 // operate on scalar float types. 9488 if (!resultType->isIntegerType()) 9489 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9490 << resultType << Input.get()->getSourceRange()); 9491 } 9492 } else if (resultType->isExtVectorType()) { 9493 if (Context.getLangOpts().OpenCL && 9494 Context.getLangOpts().OpenCLVersion < 120) { 9495 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9496 // operate on vector float types. 9497 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9498 if (!T->isIntegerType()) 9499 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9500 << resultType << Input.get()->getSourceRange()); 9501 } 9502 // Vector logical not returns the signed variant of the operand type. 9503 resultType = GetSignedVectorType(resultType); 9504 break; 9505 } else { 9506 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9507 << resultType << Input.get()->getSourceRange()); 9508 } 9509 9510 // LNot always has type int. C99 6.5.3.3p5. 9511 // In C++, it's bool. C++ 5.3.1p8 9512 resultType = Context.getLogicalOperationType(); 9513 break; 9514 case UO_Real: 9515 case UO_Imag: 9516 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9517 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9518 // complex l-values to ordinary l-values and all other values to r-values. 9519 if (Input.isInvalid()) return ExprError(); 9520 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9521 if (Input.get()->getValueKind() != VK_RValue && 9522 Input.get()->getObjectKind() == OK_Ordinary) 9523 VK = Input.get()->getValueKind(); 9524 } else if (!getLangOpts().CPlusPlus) { 9525 // In C, a volatile scalar is read by __imag. In C++, it is not. 9526 Input = DefaultLvalueConversion(Input.take()); 9527 } 9528 break; 9529 case UO_Extension: 9530 resultType = Input.get()->getType(); 9531 VK = Input.get()->getValueKind(); 9532 OK = Input.get()->getObjectKind(); 9533 break; 9534 } 9535 if (resultType.isNull() || Input.isInvalid()) 9536 return ExprError(); 9537 9538 // Check for array bounds violations in the operand of the UnaryOperator, 9539 // except for the '*' and '&' operators that have to be handled specially 9540 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9541 // that are explicitly defined as valid by the standard). 9542 if (Opc != UO_AddrOf && Opc != UO_Deref) 9543 CheckArrayAccess(Input.get()); 9544 9545 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9546 VK, OK, OpLoc)); 9547 } 9548 9549 /// \brief Determine whether the given expression is a qualified member 9550 /// access expression, of a form that could be turned into a pointer to member 9551 /// with the address-of operator. 9552 static bool isQualifiedMemberAccess(Expr *E) { 9553 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9554 if (!DRE->getQualifier()) 9555 return false; 9556 9557 ValueDecl *VD = DRE->getDecl(); 9558 if (!VD->isCXXClassMember()) 9559 return false; 9560 9561 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9562 return true; 9563 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9564 return Method->isInstance(); 9565 9566 return false; 9567 } 9568 9569 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9570 if (!ULE->getQualifier()) 9571 return false; 9572 9573 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9574 DEnd = ULE->decls_end(); 9575 D != DEnd; ++D) { 9576 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9577 if (Method->isInstance()) 9578 return true; 9579 } else { 9580 // Overload set does not contain methods. 9581 break; 9582 } 9583 } 9584 9585 return false; 9586 } 9587 9588 return false; 9589 } 9590 9591 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9592 UnaryOperatorKind Opc, Expr *Input) { 9593 // First things first: handle placeholders so that the 9594 // overloaded-operator check considers the right type. 9595 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9596 // Increment and decrement of pseudo-object references. 9597 if (pty->getKind() == BuiltinType::PseudoObject && 9598 UnaryOperator::isIncrementDecrementOp(Opc)) 9599 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9600 9601 // extension is always a builtin operator. 9602 if (Opc == UO_Extension) 9603 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9604 9605 // & gets special logic for several kinds of placeholder. 9606 // The builtin code knows what to do. 9607 if (Opc == UO_AddrOf && 9608 (pty->getKind() == BuiltinType::Overload || 9609 pty->getKind() == BuiltinType::UnknownAny || 9610 pty->getKind() == BuiltinType::BoundMember)) 9611 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9612 9613 // Anything else needs to be handled now. 9614 ExprResult Result = CheckPlaceholderExpr(Input); 9615 if (Result.isInvalid()) return ExprError(); 9616 Input = Result.take(); 9617 } 9618 9619 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9620 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9621 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9622 // Find all of the overloaded operators visible from this 9623 // point. We perform both an operator-name lookup from the local 9624 // scope and an argument-dependent lookup based on the types of 9625 // the arguments. 9626 UnresolvedSet<16> Functions; 9627 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9628 if (S && OverOp != OO_None) 9629 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9630 Functions); 9631 9632 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9633 } 9634 9635 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9636 } 9637 9638 // Unary Operators. 'Tok' is the token for the operator. 9639 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9640 tok::TokenKind Op, Expr *Input) { 9641 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9642 } 9643 9644 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9645 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9646 LabelDecl *TheDecl) { 9647 TheDecl->setUsed(); 9648 // Create the AST node. The address of a label always has type 'void*'. 9649 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9650 Context.getPointerType(Context.VoidTy))); 9651 } 9652 9653 /// Given the last statement in a statement-expression, check whether 9654 /// the result is a producing expression (like a call to an 9655 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9656 /// release out of the full-expression. Otherwise, return null. 9657 /// Cannot fail. 9658 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9659 // Should always be wrapped with one of these. 9660 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9661 if (!cleanups) return 0; 9662 9663 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9664 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9665 return 0; 9666 9667 // Splice out the cast. This shouldn't modify any interesting 9668 // features of the statement. 9669 Expr *producer = cast->getSubExpr(); 9670 assert(producer->getType() == cast->getType()); 9671 assert(producer->getValueKind() == cast->getValueKind()); 9672 cleanups->setSubExpr(producer); 9673 return cleanups; 9674 } 9675 9676 void Sema::ActOnStartStmtExpr() { 9677 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9678 } 9679 9680 void Sema::ActOnStmtExprError() { 9681 // Note that function is also called by TreeTransform when leaving a 9682 // StmtExpr scope without rebuilding anything. 9683 9684 DiscardCleanupsInEvaluationContext(); 9685 PopExpressionEvaluationContext(); 9686 } 9687 9688 ExprResult 9689 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9690 SourceLocation RPLoc) { // "({..})" 9691 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9692 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9693 9694 if (hasAnyUnrecoverableErrorsInThisFunction()) 9695 DiscardCleanupsInEvaluationContext(); 9696 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9697 PopExpressionEvaluationContext(); 9698 9699 bool isFileScope 9700 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9701 if (isFileScope) 9702 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9703 9704 // FIXME: there are a variety of strange constraints to enforce here, for 9705 // example, it is not possible to goto into a stmt expression apparently. 9706 // More semantic analysis is needed. 9707 9708 // If there are sub stmts in the compound stmt, take the type of the last one 9709 // as the type of the stmtexpr. 9710 QualType Ty = Context.VoidTy; 9711 bool StmtExprMayBindToTemp = false; 9712 if (!Compound->body_empty()) { 9713 Stmt *LastStmt = Compound->body_back(); 9714 LabelStmt *LastLabelStmt = 0; 9715 // If LastStmt is a label, skip down through into the body. 9716 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9717 LastLabelStmt = Label; 9718 LastStmt = Label->getSubStmt(); 9719 } 9720 9721 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9722 // Do function/array conversion on the last expression, but not 9723 // lvalue-to-rvalue. However, initialize an unqualified type. 9724 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9725 if (LastExpr.isInvalid()) 9726 return ExprError(); 9727 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9728 9729 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9730 // In ARC, if the final expression ends in a consume, splice 9731 // the consume out and bind it later. In the alternate case 9732 // (when dealing with a retainable type), the result 9733 // initialization will create a produce. In both cases the 9734 // result will be +1, and we'll need to balance that out with 9735 // a bind. 9736 if (Expr *rebuiltLastStmt 9737 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9738 LastExpr = rebuiltLastStmt; 9739 } else { 9740 LastExpr = PerformCopyInitialization( 9741 InitializedEntity::InitializeResult(LPLoc, 9742 Ty, 9743 false), 9744 SourceLocation(), 9745 LastExpr); 9746 } 9747 9748 if (LastExpr.isInvalid()) 9749 return ExprError(); 9750 if (LastExpr.get() != 0) { 9751 if (!LastLabelStmt) 9752 Compound->setLastStmt(LastExpr.take()); 9753 else 9754 LastLabelStmt->setSubStmt(LastExpr.take()); 9755 StmtExprMayBindToTemp = true; 9756 } 9757 } 9758 } 9759 } 9760 9761 // FIXME: Check that expression type is complete/non-abstract; statement 9762 // expressions are not lvalues. 9763 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9764 if (StmtExprMayBindToTemp) 9765 return MaybeBindToTemporary(ResStmtExpr); 9766 return Owned(ResStmtExpr); 9767 } 9768 9769 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9770 TypeSourceInfo *TInfo, 9771 OffsetOfComponent *CompPtr, 9772 unsigned NumComponents, 9773 SourceLocation RParenLoc) { 9774 QualType ArgTy = TInfo->getType(); 9775 bool Dependent = ArgTy->isDependentType(); 9776 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9777 9778 // We must have at least one component that refers to the type, and the first 9779 // one is known to be a field designator. Verify that the ArgTy represents 9780 // a struct/union/class. 9781 if (!Dependent && !ArgTy->isRecordType()) 9782 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9783 << ArgTy << TypeRange); 9784 9785 // Type must be complete per C99 7.17p3 because a declaring a variable 9786 // with an incomplete type would be ill-formed. 9787 if (!Dependent 9788 && RequireCompleteType(BuiltinLoc, ArgTy, 9789 diag::err_offsetof_incomplete_type, TypeRange)) 9790 return ExprError(); 9791 9792 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9793 // GCC extension, diagnose them. 9794 // FIXME: This diagnostic isn't actually visible because the location is in 9795 // a system header! 9796 if (NumComponents != 1) 9797 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9798 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9799 9800 bool DidWarnAboutNonPOD = false; 9801 QualType CurrentType = ArgTy; 9802 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9803 SmallVector<OffsetOfNode, 4> Comps; 9804 SmallVector<Expr*, 4> Exprs; 9805 for (unsigned i = 0; i != NumComponents; ++i) { 9806 const OffsetOfComponent &OC = CompPtr[i]; 9807 if (OC.isBrackets) { 9808 // Offset of an array sub-field. TODO: Should we allow vector elements? 9809 if (!CurrentType->isDependentType()) { 9810 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9811 if(!AT) 9812 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9813 << CurrentType); 9814 CurrentType = AT->getElementType(); 9815 } else 9816 CurrentType = Context.DependentTy; 9817 9818 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9819 if (IdxRval.isInvalid()) 9820 return ExprError(); 9821 Expr *Idx = IdxRval.take(); 9822 9823 // The expression must be an integral expression. 9824 // FIXME: An integral constant expression? 9825 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9826 !Idx->getType()->isIntegerType()) 9827 return ExprError(Diag(Idx->getLocStart(), 9828 diag::err_typecheck_subscript_not_integer) 9829 << Idx->getSourceRange()); 9830 9831 // Record this array index. 9832 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9833 Exprs.push_back(Idx); 9834 continue; 9835 } 9836 9837 // Offset of a field. 9838 if (CurrentType->isDependentType()) { 9839 // We have the offset of a field, but we can't look into the dependent 9840 // type. Just record the identifier of the field. 9841 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9842 CurrentType = Context.DependentTy; 9843 continue; 9844 } 9845 9846 // We need to have a complete type to look into. 9847 if (RequireCompleteType(OC.LocStart, CurrentType, 9848 diag::err_offsetof_incomplete_type)) 9849 return ExprError(); 9850 9851 // Look for the designated field. 9852 const RecordType *RC = CurrentType->getAs<RecordType>(); 9853 if (!RC) 9854 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9855 << CurrentType); 9856 RecordDecl *RD = RC->getDecl(); 9857 9858 // C++ [lib.support.types]p5: 9859 // The macro offsetof accepts a restricted set of type arguments in this 9860 // International Standard. type shall be a POD structure or a POD union 9861 // (clause 9). 9862 // C++11 [support.types]p4: 9863 // If type is not a standard-layout class (Clause 9), the results are 9864 // undefined. 9865 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9866 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 9867 unsigned DiagID = 9868 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 9869 : diag::warn_offsetof_non_pod_type; 9870 9871 if (!IsSafe && !DidWarnAboutNonPOD && 9872 DiagRuntimeBehavior(BuiltinLoc, 0, 9873 PDiag(DiagID) 9874 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9875 << CurrentType)) 9876 DidWarnAboutNonPOD = true; 9877 } 9878 9879 // Look for the field. 9880 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9881 LookupQualifiedName(R, RD); 9882 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9883 IndirectFieldDecl *IndirectMemberDecl = 0; 9884 if (!MemberDecl) { 9885 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9886 MemberDecl = IndirectMemberDecl->getAnonField(); 9887 } 9888 9889 if (!MemberDecl) 9890 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9891 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9892 OC.LocEnd)); 9893 9894 // C99 7.17p3: 9895 // (If the specified member is a bit-field, the behavior is undefined.) 9896 // 9897 // We diagnose this as an error. 9898 if (MemberDecl->isBitField()) { 9899 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9900 << MemberDecl->getDeclName() 9901 << SourceRange(BuiltinLoc, RParenLoc); 9902 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9903 return ExprError(); 9904 } 9905 9906 RecordDecl *Parent = MemberDecl->getParent(); 9907 if (IndirectMemberDecl) 9908 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9909 9910 // If the member was found in a base class, introduce OffsetOfNodes for 9911 // the base class indirections. 9912 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9913 /*DetectVirtual=*/false); 9914 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9915 CXXBasePath &Path = Paths.front(); 9916 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9917 B != BEnd; ++B) 9918 Comps.push_back(OffsetOfNode(B->Base)); 9919 } 9920 9921 if (IndirectMemberDecl) { 9922 for (IndirectFieldDecl::chain_iterator FI = 9923 IndirectMemberDecl->chain_begin(), 9924 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9925 assert(isa<FieldDecl>(*FI)); 9926 Comps.push_back(OffsetOfNode(OC.LocStart, 9927 cast<FieldDecl>(*FI), OC.LocEnd)); 9928 } 9929 } else 9930 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9931 9932 CurrentType = MemberDecl->getType().getNonReferenceType(); 9933 } 9934 9935 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9936 TInfo, Comps, Exprs, RParenLoc)); 9937 } 9938 9939 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9940 SourceLocation BuiltinLoc, 9941 SourceLocation TypeLoc, 9942 ParsedType ParsedArgTy, 9943 OffsetOfComponent *CompPtr, 9944 unsigned NumComponents, 9945 SourceLocation RParenLoc) { 9946 9947 TypeSourceInfo *ArgTInfo; 9948 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9949 if (ArgTy.isNull()) 9950 return ExprError(); 9951 9952 if (!ArgTInfo) 9953 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9954 9955 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9956 RParenLoc); 9957 } 9958 9959 9960 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9961 Expr *CondExpr, 9962 Expr *LHSExpr, Expr *RHSExpr, 9963 SourceLocation RPLoc) { 9964 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9965 9966 ExprValueKind VK = VK_RValue; 9967 ExprObjectKind OK = OK_Ordinary; 9968 QualType resType; 9969 bool ValueDependent = false; 9970 bool CondIsTrue = false; 9971 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9972 resType = Context.DependentTy; 9973 ValueDependent = true; 9974 } else { 9975 // The conditional expression is required to be a constant expression. 9976 llvm::APSInt condEval(32); 9977 ExprResult CondICE 9978 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9979 diag::err_typecheck_choose_expr_requires_constant, false); 9980 if (CondICE.isInvalid()) 9981 return ExprError(); 9982 CondExpr = CondICE.take(); 9983 CondIsTrue = condEval.getZExtValue(); 9984 9985 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9986 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 9987 9988 resType = ActiveExpr->getType(); 9989 ValueDependent = ActiveExpr->isValueDependent(); 9990 VK = ActiveExpr->getValueKind(); 9991 OK = ActiveExpr->getObjectKind(); 9992 } 9993 9994 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9995 resType, VK, OK, RPLoc, CondIsTrue, 9996 resType->isDependentType(), 9997 ValueDependent)); 9998 } 9999 10000 //===----------------------------------------------------------------------===// 10001 // Clang Extensions. 10002 //===----------------------------------------------------------------------===// 10003 10004 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10005 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10006 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10007 10008 { 10009 Decl *ManglingContextDecl; 10010 if (MangleNumberingContext *MCtx = 10011 getCurrentMangleNumberContext(Block->getDeclContext(), 10012 ManglingContextDecl)) { 10013 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10014 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10015 } 10016 } 10017 10018 PushBlockScope(CurScope, Block); 10019 CurContext->addDecl(Block); 10020 if (CurScope) 10021 PushDeclContext(CurScope, Block); 10022 else 10023 CurContext = Block; 10024 10025 getCurBlock()->HasImplicitReturnType = true; 10026 10027 // Enter a new evaluation context to insulate the block from any 10028 // cleanups from the enclosing full-expression. 10029 PushExpressionEvaluationContext(PotentiallyEvaluated); 10030 } 10031 10032 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10033 Scope *CurScope) { 10034 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10035 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10036 BlockScopeInfo *CurBlock = getCurBlock(); 10037 10038 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10039 QualType T = Sig->getType(); 10040 10041 // FIXME: We should allow unexpanded parameter packs here, but that would, 10042 // in turn, make the block expression contain unexpanded parameter packs. 10043 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10044 // Drop the parameters. 10045 FunctionProtoType::ExtProtoInfo EPI; 10046 EPI.HasTrailingReturn = false; 10047 EPI.TypeQuals |= DeclSpec::TQ_const; 10048 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10049 Sig = Context.getTrivialTypeSourceInfo(T); 10050 } 10051 10052 // GetTypeForDeclarator always produces a function type for a block 10053 // literal signature. Furthermore, it is always a FunctionProtoType 10054 // unless the function was written with a typedef. 10055 assert(T->isFunctionType() && 10056 "GetTypeForDeclarator made a non-function block signature"); 10057 10058 // Look for an explicit signature in that function type. 10059 FunctionProtoTypeLoc ExplicitSignature; 10060 10061 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10062 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10063 10064 // Check whether that explicit signature was synthesized by 10065 // GetTypeForDeclarator. If so, don't save that as part of the 10066 // written signature. 10067 if (ExplicitSignature.getLocalRangeBegin() == 10068 ExplicitSignature.getLocalRangeEnd()) { 10069 // This would be much cheaper if we stored TypeLocs instead of 10070 // TypeSourceInfos. 10071 TypeLoc Result = ExplicitSignature.getResultLoc(); 10072 unsigned Size = Result.getFullDataSize(); 10073 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10074 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10075 10076 ExplicitSignature = FunctionProtoTypeLoc(); 10077 } 10078 } 10079 10080 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10081 CurBlock->FunctionType = T; 10082 10083 const FunctionType *Fn = T->getAs<FunctionType>(); 10084 QualType RetTy = Fn->getResultType(); 10085 bool isVariadic = 10086 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10087 10088 CurBlock->TheDecl->setIsVariadic(isVariadic); 10089 10090 // Context.DependentTy is used as a placeholder for a missing block 10091 // return type. TODO: what should we do with declarators like: 10092 // ^ * { ... } 10093 // If the answer is "apply template argument deduction".... 10094 if (RetTy != Context.DependentTy) { 10095 CurBlock->ReturnType = RetTy; 10096 CurBlock->TheDecl->setBlockMissingReturnType(false); 10097 CurBlock->HasImplicitReturnType = false; 10098 } 10099 10100 // Push block parameters from the declarator if we had them. 10101 SmallVector<ParmVarDecl*, 8> Params; 10102 if (ExplicitSignature) { 10103 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 10104 ParmVarDecl *Param = ExplicitSignature.getArg(I); 10105 if (Param->getIdentifier() == 0 && 10106 !Param->isImplicit() && 10107 !Param->isInvalidDecl() && 10108 !getLangOpts().CPlusPlus) 10109 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10110 Params.push_back(Param); 10111 } 10112 10113 // Fake up parameter variables if we have a typedef, like 10114 // ^ fntype { ... } 10115 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10116 for (FunctionProtoType::arg_type_iterator 10117 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 10118 ParmVarDecl *Param = 10119 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 10120 ParamInfo.getLocStart(), 10121 *I); 10122 Params.push_back(Param); 10123 } 10124 } 10125 10126 // Set the parameters on the block decl. 10127 if (!Params.empty()) { 10128 CurBlock->TheDecl->setParams(Params); 10129 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10130 CurBlock->TheDecl->param_end(), 10131 /*CheckParameterNames=*/false); 10132 } 10133 10134 // Finally we can process decl attributes. 10135 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10136 10137 // Put the parameter variables in scope. 10138 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 10139 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 10140 (*AI)->setOwningFunction(CurBlock->TheDecl); 10141 10142 // If this has an identifier, add it to the scope stack. 10143 if ((*AI)->getIdentifier()) { 10144 CheckShadow(CurBlock->TheScope, *AI); 10145 10146 PushOnScopeChains(*AI, CurBlock->TheScope); 10147 } 10148 } 10149 } 10150 10151 /// ActOnBlockError - If there is an error parsing a block, this callback 10152 /// is invoked to pop the information about the block from the action impl. 10153 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10154 // Leave the expression-evaluation context. 10155 DiscardCleanupsInEvaluationContext(); 10156 PopExpressionEvaluationContext(); 10157 10158 // Pop off CurBlock, handle nested blocks. 10159 PopDeclContext(); 10160 PopFunctionScopeInfo(); 10161 } 10162 10163 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10164 /// literal was successfully completed. ^(int x){...} 10165 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10166 Stmt *Body, Scope *CurScope) { 10167 // If blocks are disabled, emit an error. 10168 if (!LangOpts.Blocks) 10169 Diag(CaretLoc, diag::err_blocks_disable); 10170 10171 // Leave the expression-evaluation context. 10172 if (hasAnyUnrecoverableErrorsInThisFunction()) 10173 DiscardCleanupsInEvaluationContext(); 10174 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10175 PopExpressionEvaluationContext(); 10176 10177 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10178 10179 if (BSI->HasImplicitReturnType) 10180 deduceClosureReturnType(*BSI); 10181 10182 PopDeclContext(); 10183 10184 QualType RetTy = Context.VoidTy; 10185 if (!BSI->ReturnType.isNull()) 10186 RetTy = BSI->ReturnType; 10187 10188 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 10189 QualType BlockTy; 10190 10191 // Set the captured variables on the block. 10192 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10193 SmallVector<BlockDecl::Capture, 4> Captures; 10194 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10195 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10196 if (Cap.isThisCapture()) 10197 continue; 10198 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10199 Cap.isNested(), Cap.getInitExpr()); 10200 Captures.push_back(NewCap); 10201 } 10202 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10203 BSI->CXXThisCaptureIndex != 0); 10204 10205 // If the user wrote a function type in some form, try to use that. 10206 if (!BSI->FunctionType.isNull()) { 10207 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10208 10209 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10210 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10211 10212 // Turn protoless block types into nullary block types. 10213 if (isa<FunctionNoProtoType>(FTy)) { 10214 FunctionProtoType::ExtProtoInfo EPI; 10215 EPI.ExtInfo = Ext; 10216 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10217 10218 // Otherwise, if we don't need to change anything about the function type, 10219 // preserve its sugar structure. 10220 } else if (FTy->getResultType() == RetTy && 10221 (!NoReturn || FTy->getNoReturnAttr())) { 10222 BlockTy = BSI->FunctionType; 10223 10224 // Otherwise, make the minimal modifications to the function type. 10225 } else { 10226 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10227 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10228 EPI.TypeQuals = 0; // FIXME: silently? 10229 EPI.ExtInfo = Ext; 10230 BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI); 10231 } 10232 10233 // If we don't have a function type, just build one from nothing. 10234 } else { 10235 FunctionProtoType::ExtProtoInfo EPI; 10236 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10237 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10238 } 10239 10240 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10241 BSI->TheDecl->param_end()); 10242 BlockTy = Context.getBlockPointerType(BlockTy); 10243 10244 // If needed, diagnose invalid gotos and switches in the block. 10245 if (getCurFunction()->NeedsScopeChecking() && 10246 !hasAnyUnrecoverableErrorsInThisFunction() && 10247 !PP.isCodeCompletionEnabled()) 10248 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10249 10250 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10251 10252 // Try to apply the named return value optimization. We have to check again 10253 // if we can do this, though, because blocks keep return statements around 10254 // to deduce an implicit return type. 10255 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10256 !BSI->TheDecl->isDependentContext()) 10257 computeNRVO(Body, getCurBlock()); 10258 10259 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10260 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 10261 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10262 10263 // If the block isn't obviously global, i.e. it captures anything at 10264 // all, then we need to do a few things in the surrounding context: 10265 if (Result->getBlockDecl()->hasCaptures()) { 10266 // First, this expression has a new cleanup object. 10267 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10268 ExprNeedsCleanups = true; 10269 10270 // It also gets a branch-protected scope if any of the captured 10271 // variables needs destruction. 10272 for (BlockDecl::capture_const_iterator 10273 ci = Result->getBlockDecl()->capture_begin(), 10274 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10275 const VarDecl *var = ci->getVariable(); 10276 if (var->getType().isDestructedType() != QualType::DK_none) { 10277 getCurFunction()->setHasBranchProtectedScope(); 10278 break; 10279 } 10280 } 10281 } 10282 10283 return Owned(Result); 10284 } 10285 10286 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10287 Expr *E, ParsedType Ty, 10288 SourceLocation RPLoc) { 10289 TypeSourceInfo *TInfo; 10290 GetTypeFromParser(Ty, &TInfo); 10291 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10292 } 10293 10294 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10295 Expr *E, TypeSourceInfo *TInfo, 10296 SourceLocation RPLoc) { 10297 Expr *OrigExpr = E; 10298 10299 // Get the va_list type 10300 QualType VaListType = Context.getBuiltinVaListType(); 10301 if (VaListType->isArrayType()) { 10302 // Deal with implicit array decay; for example, on x86-64, 10303 // va_list is an array, but it's supposed to decay to 10304 // a pointer for va_arg. 10305 VaListType = Context.getArrayDecayedType(VaListType); 10306 // Make sure the input expression also decays appropriately. 10307 ExprResult Result = UsualUnaryConversions(E); 10308 if (Result.isInvalid()) 10309 return ExprError(); 10310 E = Result.take(); 10311 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10312 // If va_list is a record type and we are compiling in C++ mode, 10313 // check the argument using reference binding. 10314 InitializedEntity Entity 10315 = InitializedEntity::InitializeParameter(Context, 10316 Context.getLValueReferenceType(VaListType), false); 10317 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10318 if (Init.isInvalid()) 10319 return ExprError(); 10320 E = Init.takeAs<Expr>(); 10321 } else { 10322 // Otherwise, the va_list argument must be an l-value because 10323 // it is modified by va_arg. 10324 if (!E->isTypeDependent() && 10325 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10326 return ExprError(); 10327 } 10328 10329 if (!E->isTypeDependent() && 10330 !Context.hasSameType(VaListType, E->getType())) { 10331 return ExprError(Diag(E->getLocStart(), 10332 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10333 << OrigExpr->getType() << E->getSourceRange()); 10334 } 10335 10336 if (!TInfo->getType()->isDependentType()) { 10337 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10338 diag::err_second_parameter_to_va_arg_incomplete, 10339 TInfo->getTypeLoc())) 10340 return ExprError(); 10341 10342 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10343 TInfo->getType(), 10344 diag::err_second_parameter_to_va_arg_abstract, 10345 TInfo->getTypeLoc())) 10346 return ExprError(); 10347 10348 if (!TInfo->getType().isPODType(Context)) { 10349 Diag(TInfo->getTypeLoc().getBeginLoc(), 10350 TInfo->getType()->isObjCLifetimeType() 10351 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10352 : diag::warn_second_parameter_to_va_arg_not_pod) 10353 << TInfo->getType() 10354 << TInfo->getTypeLoc().getSourceRange(); 10355 } 10356 10357 // Check for va_arg where arguments of the given type will be promoted 10358 // (i.e. this va_arg is guaranteed to have undefined behavior). 10359 QualType PromoteType; 10360 if (TInfo->getType()->isPromotableIntegerType()) { 10361 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10362 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10363 PromoteType = QualType(); 10364 } 10365 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10366 PromoteType = Context.DoubleTy; 10367 if (!PromoteType.isNull()) 10368 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10369 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10370 << TInfo->getType() 10371 << PromoteType 10372 << TInfo->getTypeLoc().getSourceRange()); 10373 } 10374 10375 QualType T = TInfo->getType().getNonLValueExprType(Context); 10376 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10377 } 10378 10379 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10380 // The type of __null will be int or long, depending on the size of 10381 // pointers on the target. 10382 QualType Ty; 10383 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10384 if (pw == Context.getTargetInfo().getIntWidth()) 10385 Ty = Context.IntTy; 10386 else if (pw == Context.getTargetInfo().getLongWidth()) 10387 Ty = Context.LongTy; 10388 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10389 Ty = Context.LongLongTy; 10390 else { 10391 llvm_unreachable("I don't know size of pointer!"); 10392 } 10393 10394 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10395 } 10396 10397 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10398 Expr *SrcExpr, FixItHint &Hint, 10399 bool &IsNSString) { 10400 if (!SemaRef.getLangOpts().ObjC1) 10401 return; 10402 10403 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10404 if (!PT) 10405 return; 10406 10407 // Check if the destination is of type 'id'. 10408 if (!PT->isObjCIdType()) { 10409 // Check if the destination is the 'NSString' interface. 10410 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10411 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10412 return; 10413 IsNSString = true; 10414 } 10415 10416 // Ignore any parens, implicit casts (should only be 10417 // array-to-pointer decays), and not-so-opaque values. The last is 10418 // important for making this trigger for property assignments. 10419 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10420 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10421 if (OV->getSourceExpr()) 10422 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10423 10424 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10425 if (!SL || !SL->isAscii()) 10426 return; 10427 10428 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10429 } 10430 10431 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10432 SourceLocation Loc, 10433 QualType DstType, QualType SrcType, 10434 Expr *SrcExpr, AssignmentAction Action, 10435 bool *Complained) { 10436 if (Complained) 10437 *Complained = false; 10438 10439 // Decode the result (notice that AST's are still created for extensions). 10440 bool CheckInferredResultType = false; 10441 bool isInvalid = false; 10442 unsigned DiagKind = 0; 10443 FixItHint Hint; 10444 ConversionFixItGenerator ConvHints; 10445 bool MayHaveConvFixit = false; 10446 bool MayHaveFunctionDiff = false; 10447 bool IsNSString = false; 10448 10449 switch (ConvTy) { 10450 case Compatible: 10451 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10452 return false; 10453 10454 case PointerToInt: 10455 DiagKind = diag::ext_typecheck_convert_pointer_int; 10456 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10457 MayHaveConvFixit = true; 10458 break; 10459 case IntToPointer: 10460 DiagKind = diag::ext_typecheck_convert_int_pointer; 10461 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10462 MayHaveConvFixit = true; 10463 break; 10464 case IncompatiblePointer: 10465 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString); 10466 DiagKind = 10467 (Action == AA_Passing_CFAudited ? 10468 diag::err_arc_typecheck_convert_incompatible_pointer : 10469 diag::ext_typecheck_convert_incompatible_pointer); 10470 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10471 SrcType->isObjCObjectPointerType(); 10472 if (Hint.isNull() && !CheckInferredResultType) { 10473 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10474 } 10475 else if (CheckInferredResultType) { 10476 SrcType = SrcType.getUnqualifiedType(); 10477 DstType = DstType.getUnqualifiedType(); 10478 } 10479 else if (IsNSString && !Hint.isNull()) 10480 DiagKind = diag::warn_missing_atsign_prefix; 10481 MayHaveConvFixit = true; 10482 break; 10483 case IncompatiblePointerSign: 10484 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10485 break; 10486 case FunctionVoidPointer: 10487 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10488 break; 10489 case IncompatiblePointerDiscardsQualifiers: { 10490 // Perform array-to-pointer decay if necessary. 10491 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10492 10493 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10494 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10495 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10496 DiagKind = diag::err_typecheck_incompatible_address_space; 10497 break; 10498 10499 10500 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10501 DiagKind = diag::err_typecheck_incompatible_ownership; 10502 break; 10503 } 10504 10505 llvm_unreachable("unknown error case for discarding qualifiers!"); 10506 // fallthrough 10507 } 10508 case CompatiblePointerDiscardsQualifiers: 10509 // If the qualifiers lost were because we were applying the 10510 // (deprecated) C++ conversion from a string literal to a char* 10511 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10512 // Ideally, this check would be performed in 10513 // checkPointerTypesForAssignment. However, that would require a 10514 // bit of refactoring (so that the second argument is an 10515 // expression, rather than a type), which should be done as part 10516 // of a larger effort to fix checkPointerTypesForAssignment for 10517 // C++ semantics. 10518 if (getLangOpts().CPlusPlus && 10519 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10520 return false; 10521 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10522 break; 10523 case IncompatibleNestedPointerQualifiers: 10524 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10525 break; 10526 case IntToBlockPointer: 10527 DiagKind = diag::err_int_to_block_pointer; 10528 break; 10529 case IncompatibleBlockPointer: 10530 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10531 break; 10532 case IncompatibleObjCQualifiedId: 10533 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10534 // it can give a more specific diagnostic. 10535 DiagKind = diag::warn_incompatible_qualified_id; 10536 break; 10537 case IncompatibleVectors: 10538 DiagKind = diag::warn_incompatible_vectors; 10539 break; 10540 case IncompatibleObjCWeakRef: 10541 DiagKind = diag::err_arc_weak_unavailable_assign; 10542 break; 10543 case Incompatible: 10544 DiagKind = diag::err_typecheck_convert_incompatible; 10545 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10546 MayHaveConvFixit = true; 10547 isInvalid = true; 10548 MayHaveFunctionDiff = true; 10549 break; 10550 } 10551 10552 QualType FirstType, SecondType; 10553 switch (Action) { 10554 case AA_Assigning: 10555 case AA_Initializing: 10556 // The destination type comes first. 10557 FirstType = DstType; 10558 SecondType = SrcType; 10559 break; 10560 10561 case AA_Returning: 10562 case AA_Passing: 10563 case AA_Passing_CFAudited: 10564 case AA_Converting: 10565 case AA_Sending: 10566 case AA_Casting: 10567 // The source type comes first. 10568 FirstType = SrcType; 10569 SecondType = DstType; 10570 break; 10571 } 10572 10573 PartialDiagnostic FDiag = PDiag(DiagKind); 10574 if (Action == AA_Passing_CFAudited) 10575 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10576 else 10577 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10578 10579 // If we can fix the conversion, suggest the FixIts. 10580 assert(ConvHints.isNull() || Hint.isNull()); 10581 if (!ConvHints.isNull()) { 10582 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10583 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10584 FDiag << *HI; 10585 } else { 10586 FDiag << Hint; 10587 } 10588 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10589 10590 if (MayHaveFunctionDiff) 10591 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10592 10593 Diag(Loc, FDiag); 10594 10595 if (SecondType == Context.OverloadTy) 10596 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10597 FirstType); 10598 10599 if (CheckInferredResultType) 10600 EmitRelatedResultTypeNote(SrcExpr); 10601 10602 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10603 EmitRelatedResultTypeNoteForReturn(DstType); 10604 10605 if (Complained) 10606 *Complained = true; 10607 return isInvalid; 10608 } 10609 10610 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10611 llvm::APSInt *Result) { 10612 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10613 public: 10614 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10615 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10616 } 10617 } Diagnoser; 10618 10619 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10620 } 10621 10622 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10623 llvm::APSInt *Result, 10624 unsigned DiagID, 10625 bool AllowFold) { 10626 class IDDiagnoser : public VerifyICEDiagnoser { 10627 unsigned DiagID; 10628 10629 public: 10630 IDDiagnoser(unsigned DiagID) 10631 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10632 10633 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10634 S.Diag(Loc, DiagID) << SR; 10635 } 10636 } Diagnoser(DiagID); 10637 10638 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10639 } 10640 10641 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10642 SourceRange SR) { 10643 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10644 } 10645 10646 ExprResult 10647 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10648 VerifyICEDiagnoser &Diagnoser, 10649 bool AllowFold) { 10650 SourceLocation DiagLoc = E->getLocStart(); 10651 10652 if (getLangOpts().CPlusPlus11) { 10653 // C++11 [expr.const]p5: 10654 // If an expression of literal class type is used in a context where an 10655 // integral constant expression is required, then that class type shall 10656 // have a single non-explicit conversion function to an integral or 10657 // unscoped enumeration type 10658 ExprResult Converted; 10659 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10660 public: 10661 CXX11ConvertDiagnoser(bool Silent) 10662 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10663 Silent, true) {} 10664 10665 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10666 QualType T) { 10667 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10668 } 10669 10670 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10671 Sema &S, SourceLocation Loc, QualType T) { 10672 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10673 } 10674 10675 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10676 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10677 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10678 } 10679 10680 virtual SemaDiagnosticBuilder noteExplicitConv( 10681 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10682 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10683 << ConvTy->isEnumeralType() << ConvTy; 10684 } 10685 10686 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10687 Sema &S, SourceLocation Loc, QualType T) { 10688 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10689 } 10690 10691 virtual SemaDiagnosticBuilder noteAmbiguous( 10692 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10693 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10694 << ConvTy->isEnumeralType() << ConvTy; 10695 } 10696 10697 virtual SemaDiagnosticBuilder diagnoseConversion( 10698 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10699 llvm_unreachable("conversion functions are permitted"); 10700 } 10701 } ConvertDiagnoser(Diagnoser.Suppress); 10702 10703 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10704 ConvertDiagnoser); 10705 if (Converted.isInvalid()) 10706 return Converted; 10707 E = Converted.take(); 10708 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10709 return ExprError(); 10710 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10711 // An ICE must be of integral or unscoped enumeration type. 10712 if (!Diagnoser.Suppress) 10713 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10714 return ExprError(); 10715 } 10716 10717 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10718 // in the non-ICE case. 10719 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10720 if (Result) 10721 *Result = E->EvaluateKnownConstInt(Context); 10722 return Owned(E); 10723 } 10724 10725 Expr::EvalResult EvalResult; 10726 SmallVector<PartialDiagnosticAt, 8> Notes; 10727 EvalResult.Diag = &Notes; 10728 10729 // Try to evaluate the expression, and produce diagnostics explaining why it's 10730 // not a constant expression as a side-effect. 10731 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10732 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10733 10734 // In C++11, we can rely on diagnostics being produced for any expression 10735 // which is not a constant expression. If no diagnostics were produced, then 10736 // this is a constant expression. 10737 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10738 if (Result) 10739 *Result = EvalResult.Val.getInt(); 10740 return Owned(E); 10741 } 10742 10743 // If our only note is the usual "invalid subexpression" note, just point 10744 // the caret at its location rather than producing an essentially 10745 // redundant note. 10746 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10747 diag::note_invalid_subexpr_in_const_expr) { 10748 DiagLoc = Notes[0].first; 10749 Notes.clear(); 10750 } 10751 10752 if (!Folded || !AllowFold) { 10753 if (!Diagnoser.Suppress) { 10754 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10755 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10756 Diag(Notes[I].first, Notes[I].second); 10757 } 10758 10759 return ExprError(); 10760 } 10761 10762 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10763 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10764 Diag(Notes[I].first, Notes[I].second); 10765 10766 if (Result) 10767 *Result = EvalResult.Val.getInt(); 10768 return Owned(E); 10769 } 10770 10771 namespace { 10772 // Handle the case where we conclude a expression which we speculatively 10773 // considered to be unevaluated is actually evaluated. 10774 class TransformToPE : public TreeTransform<TransformToPE> { 10775 typedef TreeTransform<TransformToPE> BaseTransform; 10776 10777 public: 10778 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10779 10780 // Make sure we redo semantic analysis 10781 bool AlwaysRebuild() { return true; } 10782 10783 // Make sure we handle LabelStmts correctly. 10784 // FIXME: This does the right thing, but maybe we need a more general 10785 // fix to TreeTransform? 10786 StmtResult TransformLabelStmt(LabelStmt *S) { 10787 S->getDecl()->setStmt(0); 10788 return BaseTransform::TransformLabelStmt(S); 10789 } 10790 10791 // We need to special-case DeclRefExprs referring to FieldDecls which 10792 // are not part of a member pointer formation; normal TreeTransforming 10793 // doesn't catch this case because of the way we represent them in the AST. 10794 // FIXME: This is a bit ugly; is it really the best way to handle this 10795 // case? 10796 // 10797 // Error on DeclRefExprs referring to FieldDecls. 10798 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10799 if (isa<FieldDecl>(E->getDecl()) && 10800 !SemaRef.isUnevaluatedContext()) 10801 return SemaRef.Diag(E->getLocation(), 10802 diag::err_invalid_non_static_member_use) 10803 << E->getDecl() << E->getSourceRange(); 10804 10805 return BaseTransform::TransformDeclRefExpr(E); 10806 } 10807 10808 // Exception: filter out member pointer formation 10809 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10810 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10811 return E; 10812 10813 return BaseTransform::TransformUnaryOperator(E); 10814 } 10815 10816 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10817 // Lambdas never need to be transformed. 10818 return E; 10819 } 10820 }; 10821 } 10822 10823 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10824 assert(isUnevaluatedContext() && 10825 "Should only transform unevaluated expressions"); 10826 ExprEvalContexts.back().Context = 10827 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10828 if (isUnevaluatedContext()) 10829 return E; 10830 return TransformToPE(*this).TransformExpr(E); 10831 } 10832 10833 void 10834 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10835 Decl *LambdaContextDecl, 10836 bool IsDecltype) { 10837 ExprEvalContexts.push_back( 10838 ExpressionEvaluationContextRecord(NewContext, 10839 ExprCleanupObjects.size(), 10840 ExprNeedsCleanups, 10841 LambdaContextDecl, 10842 IsDecltype)); 10843 ExprNeedsCleanups = false; 10844 if (!MaybeODRUseExprs.empty()) 10845 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10846 } 10847 10848 void 10849 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10850 ReuseLambdaContextDecl_t, 10851 bool IsDecltype) { 10852 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 10853 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 10854 } 10855 10856 void Sema::PopExpressionEvaluationContext() { 10857 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10858 10859 if (!Rec.Lambdas.empty()) { 10860 if (Rec.isUnevaluated()) { 10861 // C++11 [expr.prim.lambda]p2: 10862 // A lambda-expression shall not appear in an unevaluated operand 10863 // (Clause 5). 10864 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10865 Diag(Rec.Lambdas[I]->getLocStart(), 10866 diag::err_lambda_unevaluated_operand); 10867 } else { 10868 // Mark the capture expressions odr-used. This was deferred 10869 // during lambda expression creation. 10870 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10871 LambdaExpr *Lambda = Rec.Lambdas[I]; 10872 for (LambdaExpr::capture_init_iterator 10873 C = Lambda->capture_init_begin(), 10874 CEnd = Lambda->capture_init_end(); 10875 C != CEnd; ++C) { 10876 MarkDeclarationsReferencedInExpr(*C); 10877 } 10878 } 10879 } 10880 } 10881 10882 // When are coming out of an unevaluated context, clear out any 10883 // temporaries that we may have created as part of the evaluation of 10884 // the expression in that context: they aren't relevant because they 10885 // will never be constructed. 10886 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 10887 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10888 ExprCleanupObjects.end()); 10889 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10890 CleanupVarDeclMarking(); 10891 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10892 // Otherwise, merge the contexts together. 10893 } else { 10894 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10895 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10896 Rec.SavedMaybeODRUseExprs.end()); 10897 } 10898 10899 // Pop the current expression evaluation context off the stack. 10900 ExprEvalContexts.pop_back(); 10901 } 10902 10903 void Sema::DiscardCleanupsInEvaluationContext() { 10904 ExprCleanupObjects.erase( 10905 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10906 ExprCleanupObjects.end()); 10907 ExprNeedsCleanups = false; 10908 MaybeODRUseExprs.clear(); 10909 } 10910 10911 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10912 if (!E->getType()->isVariablyModifiedType()) 10913 return E; 10914 return TransformToPotentiallyEvaluated(E); 10915 } 10916 10917 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10918 // Do not mark anything as "used" within a dependent context; wait for 10919 // an instantiation. 10920 if (SemaRef.CurContext->isDependentContext()) 10921 return false; 10922 10923 switch (SemaRef.ExprEvalContexts.back().Context) { 10924 case Sema::Unevaluated: 10925 case Sema::UnevaluatedAbstract: 10926 // We are in an expression that is not potentially evaluated; do nothing. 10927 // (Depending on how you read the standard, we actually do need to do 10928 // something here for null pointer constants, but the standard's 10929 // definition of a null pointer constant is completely crazy.) 10930 return false; 10931 10932 case Sema::ConstantEvaluated: 10933 case Sema::PotentiallyEvaluated: 10934 // We are in a potentially evaluated expression (or a constant-expression 10935 // in C++03); we need to do implicit template instantiation, implicitly 10936 // define class members, and mark most declarations as used. 10937 return true; 10938 10939 case Sema::PotentiallyEvaluatedIfUsed: 10940 // Referenced declarations will only be used if the construct in the 10941 // containing expression is used. 10942 return false; 10943 } 10944 llvm_unreachable("Invalid context"); 10945 } 10946 10947 /// \brief Mark a function referenced, and check whether it is odr-used 10948 /// (C++ [basic.def.odr]p2, C99 6.9p3) 10949 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10950 assert(Func && "No function?"); 10951 10952 Func->setReferenced(); 10953 10954 // C++11 [basic.def.odr]p3: 10955 // A function whose name appears as a potentially-evaluated expression is 10956 // odr-used if it is the unique lookup result or the selected member of a 10957 // set of overloaded functions [...]. 10958 // 10959 // We (incorrectly) mark overload resolution as an unevaluated context, so we 10960 // can just check that here. Skip the rest of this function if we've already 10961 // marked the function as used. 10962 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 10963 // C++11 [temp.inst]p3: 10964 // Unless a function template specialization has been explicitly 10965 // instantiated or explicitly specialized, the function template 10966 // specialization is implicitly instantiated when the specialization is 10967 // referenced in a context that requires a function definition to exist. 10968 // 10969 // We consider constexpr function templates to be referenced in a context 10970 // that requires a definition to exist whenever they are referenced. 10971 // 10972 // FIXME: This instantiates constexpr functions too frequently. If this is 10973 // really an unevaluated context (and we're not just in the definition of a 10974 // function template or overload resolution or other cases which we 10975 // incorrectly consider to be unevaluated contexts), and we're not in a 10976 // subexpression which we actually need to evaluate (for instance, a 10977 // template argument, array bound or an expression in a braced-init-list), 10978 // we are not permitted to instantiate this constexpr function definition. 10979 // 10980 // FIXME: This also implicitly defines special members too frequently. They 10981 // are only supposed to be implicitly defined if they are odr-used, but they 10982 // are not odr-used from constant expressions in unevaluated contexts. 10983 // However, they cannot be referenced if they are deleted, and they are 10984 // deleted whenever the implicit definition of the special member would 10985 // fail. 10986 if (!Func->isConstexpr() || Func->getBody()) 10987 return; 10988 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 10989 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 10990 return; 10991 } 10992 10993 // Note that this declaration has been used. 10994 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10995 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10996 if (Constructor->isDefaultConstructor()) { 10997 if (Constructor->isTrivial()) 10998 return; 10999 if (!Constructor->isUsed(false)) 11000 DefineImplicitDefaultConstructor(Loc, Constructor); 11001 } else if (Constructor->isCopyConstructor()) { 11002 if (!Constructor->isUsed(false)) 11003 DefineImplicitCopyConstructor(Loc, Constructor); 11004 } else if (Constructor->isMoveConstructor()) { 11005 if (!Constructor->isUsed(false)) 11006 DefineImplicitMoveConstructor(Loc, Constructor); 11007 } 11008 } else if (Constructor->getInheritedConstructor()) { 11009 if (!Constructor->isUsed(false)) 11010 DefineInheritingConstructor(Loc, Constructor); 11011 } 11012 11013 MarkVTableUsed(Loc, Constructor->getParent()); 11014 } else if (CXXDestructorDecl *Destructor = 11015 dyn_cast<CXXDestructorDecl>(Func)) { 11016 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 11017 !Destructor->isUsed(false)) 11018 DefineImplicitDestructor(Loc, Destructor); 11019 if (Destructor->isVirtual()) 11020 MarkVTableUsed(Loc, Destructor->getParent()); 11021 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11022 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 11023 MethodDecl->isOverloadedOperator() && 11024 MethodDecl->getOverloadedOperator() == OO_Equal) { 11025 if (!MethodDecl->isUsed(false)) { 11026 if (MethodDecl->isCopyAssignmentOperator()) 11027 DefineImplicitCopyAssignment(Loc, MethodDecl); 11028 else 11029 DefineImplicitMoveAssignment(Loc, MethodDecl); 11030 } 11031 } else if (isa<CXXConversionDecl>(MethodDecl) && 11032 MethodDecl->getParent()->isLambda()) { 11033 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 11034 if (Conversion->isLambdaToBlockPointerConversion()) 11035 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11036 else 11037 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11038 } else if (MethodDecl->isVirtual()) 11039 MarkVTableUsed(Loc, MethodDecl->getParent()); 11040 } 11041 11042 // Recursive functions should be marked when used from another function. 11043 // FIXME: Is this really right? 11044 if (CurContext == Func) return; 11045 11046 // Resolve the exception specification for any function which is 11047 // used: CodeGen will need it. 11048 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11049 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11050 ResolveExceptionSpec(Loc, FPT); 11051 11052 // Implicit instantiation of function templates and member functions of 11053 // class templates. 11054 if (Func->isImplicitlyInstantiable()) { 11055 bool AlreadyInstantiated = false; 11056 SourceLocation PointOfInstantiation = Loc; 11057 if (FunctionTemplateSpecializationInfo *SpecInfo 11058 = Func->getTemplateSpecializationInfo()) { 11059 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11060 SpecInfo->setPointOfInstantiation(Loc); 11061 else if (SpecInfo->getTemplateSpecializationKind() 11062 == TSK_ImplicitInstantiation) { 11063 AlreadyInstantiated = true; 11064 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11065 } 11066 } else if (MemberSpecializationInfo *MSInfo 11067 = Func->getMemberSpecializationInfo()) { 11068 if (MSInfo->getPointOfInstantiation().isInvalid()) 11069 MSInfo->setPointOfInstantiation(Loc); 11070 else if (MSInfo->getTemplateSpecializationKind() 11071 == TSK_ImplicitInstantiation) { 11072 AlreadyInstantiated = true; 11073 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11074 } 11075 } 11076 11077 if (!AlreadyInstantiated || Func->isConstexpr()) { 11078 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11079 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11080 ActiveTemplateInstantiations.size()) 11081 PendingLocalImplicitInstantiations.push_back( 11082 std::make_pair(Func, PointOfInstantiation)); 11083 else if (Func->isConstexpr()) 11084 // Do not defer instantiations of constexpr functions, to avoid the 11085 // expression evaluator needing to call back into Sema if it sees a 11086 // call to such a function. 11087 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11088 else { 11089 PendingInstantiations.push_back(std::make_pair(Func, 11090 PointOfInstantiation)); 11091 // Notify the consumer that a function was implicitly instantiated. 11092 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11093 } 11094 } 11095 } else { 11096 // Walk redefinitions, as some of them may be instantiable. 11097 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 11098 e(Func->redecls_end()); i != e; ++i) { 11099 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11100 MarkFunctionReferenced(Loc, *i); 11101 } 11102 } 11103 11104 // Keep track of used but undefined functions. 11105 if (!Func->isDefined()) { 11106 if (mightHaveNonExternalLinkage(Func)) 11107 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11108 else if (Func->getMostRecentDecl()->isInlined() && 11109 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11110 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11111 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11112 } 11113 11114 // Normally the must current decl is marked used while processing the use and 11115 // any subsequent decls are marked used by decl merging. This fails with 11116 // template instantiation since marking can happen at the end of the file 11117 // and, because of the two phase lookup, this function is called with at 11118 // decl in the middle of a decl chain. We loop to maintain the invariant 11119 // that once a decl is used, all decls after it are also used. 11120 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11121 F->setUsed(true); 11122 if (F == Func) 11123 break; 11124 } 11125 } 11126 11127 static void 11128 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11129 VarDecl *var, DeclContext *DC) { 11130 DeclContext *VarDC = var->getDeclContext(); 11131 11132 // If the parameter still belongs to the translation unit, then 11133 // we're actually just using one parameter in the declaration of 11134 // the next. 11135 if (isa<ParmVarDecl>(var) && 11136 isa<TranslationUnitDecl>(VarDC)) 11137 return; 11138 11139 // For C code, don't diagnose about capture if we're not actually in code 11140 // right now; it's impossible to write a non-constant expression outside of 11141 // function context, so we'll get other (more useful) diagnostics later. 11142 // 11143 // For C++, things get a bit more nasty... it would be nice to suppress this 11144 // diagnostic for certain cases like using a local variable in an array bound 11145 // for a member of a local class, but the correct predicate is not obvious. 11146 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11147 return; 11148 11149 if (isa<CXXMethodDecl>(VarDC) && 11150 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11151 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11152 << var->getIdentifier(); 11153 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11154 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11155 << var->getIdentifier() << fn->getDeclName(); 11156 } else if (isa<BlockDecl>(VarDC)) { 11157 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11158 << var->getIdentifier(); 11159 } else { 11160 // FIXME: Is there any other context where a local variable can be 11161 // declared? 11162 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11163 << var->getIdentifier(); 11164 } 11165 11166 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11167 << var->getIdentifier(); 11168 11169 // FIXME: Add additional diagnostic info about class etc. which prevents 11170 // capture. 11171 } 11172 11173 /// \brief Capture the given variable in the captured region. 11174 static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI, 11175 VarDecl *Var, QualType FieldType, 11176 QualType DeclRefType, 11177 SourceLocation Loc, 11178 bool RefersToEnclosingLocal) { 11179 // The current implemention assumes that all variables are captured 11180 // by references. Since there is no capture by copy, no expression evaluation 11181 // will be needed. 11182 // 11183 RecordDecl *RD = RSI->TheRecordDecl; 11184 11185 FieldDecl *Field 11186 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType, 11187 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11188 0, false, ICIS_NoInit); 11189 Field->setImplicit(true); 11190 Field->setAccess(AS_private); 11191 RD->addDecl(Field); 11192 11193 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11194 DeclRefType, VK_LValue, Loc); 11195 Var->setReferenced(true); 11196 Var->setUsed(true); 11197 11198 return Ref; 11199 } 11200 11201 /// \brief Capture the given variable in the given lambda expression. 11202 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 11203 VarDecl *Var, QualType FieldType, 11204 QualType DeclRefType, 11205 SourceLocation Loc, 11206 bool RefersToEnclosingLocal) { 11207 CXXRecordDecl *Lambda = LSI->Lambda; 11208 11209 // Build the non-static data member. 11210 FieldDecl *Field 11211 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11212 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11213 0, false, ICIS_NoInit); 11214 Field->setImplicit(true); 11215 Field->setAccess(AS_private); 11216 Lambda->addDecl(Field); 11217 11218 // C++11 [expr.prim.lambda]p21: 11219 // When the lambda-expression is evaluated, the entities that 11220 // are captured by copy are used to direct-initialize each 11221 // corresponding non-static data member of the resulting closure 11222 // object. (For array members, the array elements are 11223 // direct-initialized in increasing subscript order.) These 11224 // initializations are performed in the (unspecified) order in 11225 // which the non-static data members are declared. 11226 11227 // Introduce a new evaluation context for the initialization, so 11228 // that temporaries introduced as part of the capture are retained 11229 // to be re-"exported" from the lambda expression itself. 11230 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11231 11232 // C++ [expr.prim.labda]p12: 11233 // An entity captured by a lambda-expression is odr-used (3.2) in 11234 // the scope containing the lambda-expression. 11235 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11236 DeclRefType, VK_LValue, Loc); 11237 Var->setReferenced(true); 11238 Var->setUsed(true); 11239 11240 // When the field has array type, create index variables for each 11241 // dimension of the array. We use these index variables to subscript 11242 // the source array, and other clients (e.g., CodeGen) will perform 11243 // the necessary iteration with these index variables. 11244 SmallVector<VarDecl *, 4> IndexVariables; 11245 QualType BaseType = FieldType; 11246 QualType SizeType = S.Context.getSizeType(); 11247 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11248 while (const ConstantArrayType *Array 11249 = S.Context.getAsConstantArrayType(BaseType)) { 11250 // Create the iteration variable for this array index. 11251 IdentifierInfo *IterationVarName = 0; 11252 { 11253 SmallString<8> Str; 11254 llvm::raw_svector_ostream OS(Str); 11255 OS << "__i" << IndexVariables.size(); 11256 IterationVarName = &S.Context.Idents.get(OS.str()); 11257 } 11258 VarDecl *IterationVar 11259 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11260 IterationVarName, SizeType, 11261 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11262 SC_None); 11263 IndexVariables.push_back(IterationVar); 11264 LSI->ArrayIndexVars.push_back(IterationVar); 11265 11266 // Create a reference to the iteration variable. 11267 ExprResult IterationVarRef 11268 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11269 assert(!IterationVarRef.isInvalid() && 11270 "Reference to invented variable cannot fail!"); 11271 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11272 assert(!IterationVarRef.isInvalid() && 11273 "Conversion of invented variable cannot fail!"); 11274 11275 // Subscript the array with this iteration variable. 11276 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11277 Ref, Loc, IterationVarRef.take(), Loc); 11278 if (Subscript.isInvalid()) { 11279 S.CleanupVarDeclMarking(); 11280 S.DiscardCleanupsInEvaluationContext(); 11281 return ExprError(); 11282 } 11283 11284 Ref = Subscript.take(); 11285 BaseType = Array->getElementType(); 11286 } 11287 11288 // Construct the entity that we will be initializing. For an array, this 11289 // will be first element in the array, which may require several levels 11290 // of array-subscript entities. 11291 SmallVector<InitializedEntity, 4> Entities; 11292 Entities.reserve(1 + IndexVariables.size()); 11293 Entities.push_back( 11294 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 11295 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11296 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11297 0, 11298 Entities.back())); 11299 11300 InitializationKind InitKind 11301 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11302 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11303 ExprResult Result(true); 11304 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11305 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11306 11307 // If this initialization requires any cleanups (e.g., due to a 11308 // default argument to a copy constructor), note that for the 11309 // lambda. 11310 if (S.ExprNeedsCleanups) 11311 LSI->ExprNeedsCleanups = true; 11312 11313 // Exit the expression evaluation context used for the capture. 11314 S.CleanupVarDeclMarking(); 11315 S.DiscardCleanupsInEvaluationContext(); 11316 return Result; 11317 } 11318 11319 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11320 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11321 bool BuildAndDiagnose, 11322 QualType &CaptureType, 11323 QualType &DeclRefType) { 11324 bool Nested = false; 11325 11326 DeclContext *DC = CurContext; 11327 if (Var->getDeclContext() == DC) return true; 11328 if (!Var->hasLocalStorage()) return true; 11329 11330 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11331 11332 // Walk up the stack to determine whether we can capture the variable, 11333 // performing the "simple" checks that don't depend on type. We stop when 11334 // we've either hit the declared scope of the variable or find an existing 11335 // capture of that variable. 11336 CaptureType = Var->getType(); 11337 DeclRefType = CaptureType.getNonReferenceType(); 11338 bool Explicit = (Kind != TryCapture_Implicit); 11339 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 11340 do { 11341 // Only block literals, captured statements, and lambda expressions can 11342 // capture; other scopes don't work. 11343 DeclContext *ParentDC; 11344 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) 11345 ParentDC = DC->getParent(); 11346 else if (isa<CXXMethodDecl>(DC) && 11347 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 11348 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 11349 ParentDC = DC->getParent()->getParent(); 11350 else { 11351 if (BuildAndDiagnose) 11352 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 11353 return true; 11354 } 11355 11356 CapturingScopeInfo *CSI = 11357 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 11358 11359 // Check whether we've already captured it. 11360 if (CSI->isCaptured(Var)) { 11361 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11362 11363 // If we found a capture, any subcaptures are nested. 11364 Nested = true; 11365 11366 // Retrieve the capture type for this variable. 11367 CaptureType = Cap.getCaptureType(); 11368 11369 // Compute the type of an expression that refers to this variable. 11370 DeclRefType = CaptureType.getNonReferenceType(); 11371 11372 if (Cap.isCopyCapture() && 11373 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11374 DeclRefType.addConst(); 11375 break; 11376 } 11377 11378 bool IsBlock = isa<BlockScopeInfo>(CSI); 11379 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11380 11381 // Lambdas are not allowed to capture unnamed variables 11382 // (e.g. anonymous unions). 11383 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11384 // assuming that's the intent. 11385 if (IsLambda && !Var->getDeclName()) { 11386 if (BuildAndDiagnose) { 11387 Diag(Loc, diag::err_lambda_capture_anonymous_var); 11388 Diag(Var->getLocation(), diag::note_declared_at); 11389 } 11390 return true; 11391 } 11392 11393 // Prohibit variably-modified types; they're difficult to deal with. 11394 if (Var->getType()->isVariablyModifiedType()) { 11395 if (BuildAndDiagnose) { 11396 if (IsBlock) 11397 Diag(Loc, diag::err_ref_vm_type); 11398 else 11399 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11400 Diag(Var->getLocation(), diag::note_previous_decl) 11401 << Var->getDeclName(); 11402 } 11403 return true; 11404 } 11405 // Prohibit structs with flexible array members too. 11406 // We cannot capture what is in the tail end of the struct. 11407 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11408 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11409 if (BuildAndDiagnose) { 11410 if (IsBlock) 11411 Diag(Loc, diag::err_ref_flexarray_type); 11412 else 11413 Diag(Loc, diag::err_lambda_capture_flexarray_type) 11414 << Var->getDeclName(); 11415 Diag(Var->getLocation(), diag::note_previous_decl) 11416 << Var->getDeclName(); 11417 } 11418 return true; 11419 } 11420 } 11421 // Lambdas and captured statements are not allowed to capture __block 11422 // variables; they don't support the expected semantics. 11423 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11424 if (BuildAndDiagnose) { 11425 Diag(Loc, diag::err_capture_block_variable) 11426 << Var->getDeclName() << !IsLambda; 11427 Diag(Var->getLocation(), diag::note_previous_decl) 11428 << Var->getDeclName(); 11429 } 11430 return true; 11431 } 11432 11433 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11434 // No capture-default 11435 if (BuildAndDiagnose) { 11436 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 11437 Diag(Var->getLocation(), diag::note_previous_decl) 11438 << Var->getDeclName(); 11439 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11440 diag::note_lambda_decl); 11441 } 11442 return true; 11443 } 11444 11445 FunctionScopesIndex--; 11446 DC = ParentDC; 11447 Explicit = false; 11448 } while (!Var->getDeclContext()->Equals(DC)); 11449 11450 // Walk back down the scope stack, computing the type of the capture at 11451 // each step, checking type-specific requirements, and adding captures if 11452 // requested. 11453 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 11454 ++I) { 11455 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11456 11457 // Compute the type of the capture and of a reference to the capture within 11458 // this scope. 11459 if (isa<BlockScopeInfo>(CSI)) { 11460 Expr *CopyExpr = 0; 11461 bool ByRef = false; 11462 11463 // Blocks are not allowed to capture arrays. 11464 if (CaptureType->isArrayType()) { 11465 if (BuildAndDiagnose) { 11466 Diag(Loc, diag::err_ref_array_type); 11467 Diag(Var->getLocation(), diag::note_previous_decl) 11468 << Var->getDeclName(); 11469 } 11470 return true; 11471 } 11472 11473 // Forbid the block-capture of autoreleasing variables. 11474 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11475 if (BuildAndDiagnose) { 11476 Diag(Loc, diag::err_arc_autoreleasing_capture) 11477 << /*block*/ 0; 11478 Diag(Var->getLocation(), diag::note_previous_decl) 11479 << Var->getDeclName(); 11480 } 11481 return true; 11482 } 11483 11484 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11485 // Block capture by reference does not change the capture or 11486 // declaration reference types. 11487 ByRef = true; 11488 } else { 11489 // Block capture by copy introduces 'const'. 11490 CaptureType = CaptureType.getNonReferenceType().withConst(); 11491 DeclRefType = CaptureType; 11492 11493 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 11494 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11495 // The capture logic needs the destructor, so make sure we mark it. 11496 // Usually this is unnecessary because most local variables have 11497 // their destructors marked at declaration time, but parameters are 11498 // an exception because it's technically only the call site that 11499 // actually requires the destructor. 11500 if (isa<ParmVarDecl>(Var)) 11501 FinalizeVarWithDestructor(Var, Record); 11502 11503 // Enter a new evaluation context to insulate the copy 11504 // full-expression. 11505 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11506 11507 // According to the blocks spec, the capture of a variable from 11508 // the stack requires a const copy constructor. This is not true 11509 // of the copy/move done to move a __block variable to the heap. 11510 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested, 11511 DeclRefType.withConst(), 11512 VK_LValue, Loc); 11513 11514 ExprResult Result 11515 = PerformCopyInitialization( 11516 InitializedEntity::InitializeBlock(Var->getLocation(), 11517 CaptureType, false), 11518 Loc, Owned(DeclRef)); 11519 11520 // Build a full-expression copy expression if initialization 11521 // succeeded and used a non-trivial constructor. Recover from 11522 // errors by pretending that the copy isn't necessary. 11523 if (!Result.isInvalid() && 11524 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11525 ->isTrivial()) { 11526 Result = MaybeCreateExprWithCleanups(Result); 11527 CopyExpr = Result.take(); 11528 } 11529 } 11530 } 11531 } 11532 11533 // Actually capture the variable. 11534 if (BuildAndDiagnose) 11535 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11536 SourceLocation(), CaptureType, CopyExpr); 11537 Nested = true; 11538 continue; 11539 } 11540 11541 if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11542 // By default, capture variables by reference. 11543 bool ByRef = true; 11544 // Using an LValue reference type is consistent with Lambdas (see below). 11545 CaptureType = Context.getLValueReferenceType(DeclRefType); 11546 11547 Expr *CopyExpr = 0; 11548 if (BuildAndDiagnose) { 11549 ExprResult Result = captureInCapturedRegion(*this, RSI, Var, 11550 CaptureType, DeclRefType, 11551 Loc, Nested); 11552 if (!Result.isInvalid()) 11553 CopyExpr = Result.take(); 11554 } 11555 11556 // Actually capture the variable. 11557 if (BuildAndDiagnose) 11558 CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc, 11559 SourceLocation(), CaptureType, CopyExpr); 11560 Nested = true; 11561 continue; 11562 } 11563 11564 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11565 11566 // Determine whether we are capturing by reference or by value. 11567 bool ByRef = false; 11568 if (I == N - 1 && Kind != TryCapture_Implicit) { 11569 ByRef = (Kind == TryCapture_ExplicitByRef); 11570 } else { 11571 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11572 } 11573 11574 // Compute the type of the field that will capture this variable. 11575 if (ByRef) { 11576 // C++11 [expr.prim.lambda]p15: 11577 // An entity is captured by reference if it is implicitly or 11578 // explicitly captured but not captured by copy. It is 11579 // unspecified whether additional unnamed non-static data 11580 // members are declared in the closure type for entities 11581 // captured by reference. 11582 // 11583 // FIXME: It is not clear whether we want to build an lvalue reference 11584 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11585 // to do the former, while EDG does the latter. Core issue 1249 will 11586 // clarify, but for now we follow GCC because it's a more permissive and 11587 // easily defensible position. 11588 CaptureType = Context.getLValueReferenceType(DeclRefType); 11589 } else { 11590 // C++11 [expr.prim.lambda]p14: 11591 // For each entity captured by copy, an unnamed non-static 11592 // data member is declared in the closure type. The 11593 // declaration order of these members is unspecified. The type 11594 // of such a data member is the type of the corresponding 11595 // captured entity if the entity is not a reference to an 11596 // object, or the referenced type otherwise. [Note: If the 11597 // captured entity is a reference to a function, the 11598 // corresponding data member is also a reference to a 11599 // function. - end note ] 11600 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11601 if (!RefType->getPointeeType()->isFunctionType()) 11602 CaptureType = RefType->getPointeeType(); 11603 } 11604 11605 // Forbid the lambda copy-capture of autoreleasing variables. 11606 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11607 if (BuildAndDiagnose) { 11608 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11609 Diag(Var->getLocation(), diag::note_previous_decl) 11610 << Var->getDeclName(); 11611 } 11612 return true; 11613 } 11614 } 11615 11616 // Capture this variable in the lambda. 11617 Expr *CopyExpr = 0; 11618 if (BuildAndDiagnose) { 11619 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 11620 DeclRefType, Loc, 11621 Nested); 11622 if (!Result.isInvalid()) 11623 CopyExpr = Result.take(); 11624 } 11625 11626 // Compute the type of a reference to this captured variable. 11627 if (ByRef) 11628 DeclRefType = CaptureType.getNonReferenceType(); 11629 else { 11630 // C++ [expr.prim.lambda]p5: 11631 // The closure type for a lambda-expression has a public inline 11632 // function call operator [...]. This function call operator is 11633 // declared const (9.3.1) if and only if the lambda-expression’s 11634 // parameter-declaration-clause is not followed by mutable. 11635 DeclRefType = CaptureType.getNonReferenceType(); 11636 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11637 DeclRefType.addConst(); 11638 } 11639 11640 // Add the capture. 11641 if (BuildAndDiagnose) 11642 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 11643 EllipsisLoc, CaptureType, CopyExpr); 11644 Nested = true; 11645 } 11646 11647 return false; 11648 } 11649 11650 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11651 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11652 QualType CaptureType; 11653 QualType DeclRefType; 11654 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11655 /*BuildAndDiagnose=*/true, CaptureType, 11656 DeclRefType); 11657 } 11658 11659 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11660 QualType CaptureType; 11661 QualType DeclRefType; 11662 11663 // Determine whether we can capture this variable. 11664 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11665 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 11666 return QualType(); 11667 11668 return DeclRefType; 11669 } 11670 11671 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 11672 SourceLocation Loc) { 11673 // Keep track of used but undefined variables. 11674 // FIXME: We shouldn't suppress this warning for static data members. 11675 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 11676 !Var->isExternallyVisible() && 11677 !(Var->isStaticDataMember() && Var->hasInit())) { 11678 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 11679 if (old.isInvalid()) old = Loc; 11680 } 11681 11682 SemaRef.tryCaptureVariable(Var, Loc); 11683 11684 Var->setUsed(true); 11685 } 11686 11687 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 11688 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 11689 // an object that satisfies the requirements for appearing in a 11690 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 11691 // is immediately applied." This function handles the lvalue-to-rvalue 11692 // conversion part. 11693 MaybeODRUseExprs.erase(E->IgnoreParens()); 11694 } 11695 11696 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11697 if (!Res.isUsable()) 11698 return Res; 11699 11700 // If a constant-expression is a reference to a variable where we delay 11701 // deciding whether it is an odr-use, just assume we will apply the 11702 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11703 // (a non-type template argument), we have special handling anyway. 11704 UpdateMarkingForLValueToRValue(Res.get()); 11705 return Res; 11706 } 11707 11708 void Sema::CleanupVarDeclMarking() { 11709 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11710 e = MaybeODRUseExprs.end(); 11711 i != e; ++i) { 11712 VarDecl *Var; 11713 SourceLocation Loc; 11714 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11715 Var = cast<VarDecl>(DRE->getDecl()); 11716 Loc = DRE->getLocation(); 11717 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11718 Var = cast<VarDecl>(ME->getMemberDecl()); 11719 Loc = ME->getMemberLoc(); 11720 } else { 11721 llvm_unreachable("Unexpcted expression"); 11722 } 11723 11724 MarkVarDeclODRUsed(*this, Var, Loc); 11725 } 11726 11727 MaybeODRUseExprs.clear(); 11728 } 11729 11730 // Mark a VarDecl referenced, and perform the necessary handling to compute 11731 // odr-uses. 11732 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11733 VarDecl *Var, Expr *E) { 11734 Var->setReferenced(); 11735 11736 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11737 return; 11738 11739 VarTemplateSpecializationDecl *VarSpec = 11740 dyn_cast<VarTemplateSpecializationDecl>(Var); 11741 11742 // Implicit instantiation of static data members, static data member 11743 // templates of class templates, and variable template specializations. 11744 // Delay instantiations of variable templates, except for those 11745 // that could be used in a constant expression. 11746 if (VarSpec || (Var->isStaticDataMember() && 11747 Var->getInstantiatedFromStaticDataMember())) { 11748 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 11749 if (VarSpec) 11750 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 11751 "Can't instantiate a partial template specialization."); 11752 if (Var->isStaticDataMember()) 11753 assert(MSInfo && "Missing member specialization information?"); 11754 11755 SourceLocation PointOfInstantiation; 11756 bool InstantiationIsOkay = true; 11757 if (MSInfo) { 11758 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 11759 TemplateSpecializationKind TSK = MSInfo->getTemplateSpecializationKind(); 11760 11761 if (TSK == TSK_ImplicitInstantiation && 11762 (!AlreadyInstantiated || 11763 Var->isUsableInConstantExpressions(SemaRef.Context))) { 11764 if (!AlreadyInstantiated) { 11765 // This is a modification of an existing AST node. Notify listeners. 11766 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11767 L->StaticDataMemberInstantiated(Var); 11768 MSInfo->setPointOfInstantiation(Loc); 11769 } 11770 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11771 } else 11772 InstantiationIsOkay = false; 11773 } else { 11774 if (VarSpec->getPointOfInstantiation().isInvalid()) 11775 VarSpec->setPointOfInstantiation(Loc); 11776 PointOfInstantiation = VarSpec->getPointOfInstantiation(); 11777 } 11778 11779 if (InstantiationIsOkay) { 11780 bool InstantiationDependent = false; 11781 bool IsNonDependent = 11782 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 11783 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 11784 : true; 11785 11786 // Do not instantiate specializations that are still type-dependent. 11787 if (IsNonDependent) { 11788 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 11789 // Do not defer instantiations of variables which could be used in a 11790 // constant expression. 11791 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 11792 } else { 11793 SemaRef.PendingInstantiations 11794 .push_back(std::make_pair(Var, PointOfInstantiation)); 11795 } 11796 } 11797 } 11798 } 11799 11800 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11801 // the requirements for appearing in a constant expression (5.19) and, if 11802 // it is an object, the lvalue-to-rvalue conversion (4.1) 11803 // is immediately applied." We check the first part here, and 11804 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11805 // Note that we use the C++11 definition everywhere because nothing in 11806 // C++03 depends on whether we get the C++03 version correct. The second 11807 // part does not apply to references, since they are not objects. 11808 const VarDecl *DefVD; 11809 if (E && !isa<ParmVarDecl>(Var) && 11810 Var->isUsableInConstantExpressions(SemaRef.Context) && 11811 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11812 if (!Var->getType()->isReferenceType()) 11813 SemaRef.MaybeODRUseExprs.insert(E); 11814 } else 11815 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11816 } 11817 11818 /// \brief Mark a variable referenced, and check whether it is odr-used 11819 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11820 /// used directly for normal expressions referring to VarDecl. 11821 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11822 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11823 } 11824 11825 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11826 Decl *D, Expr *E, bool OdrUse) { 11827 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11828 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11829 return; 11830 } 11831 11832 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 11833 11834 // If this is a call to a method via a cast, also mark the method in the 11835 // derived class used in case codegen can devirtualize the call. 11836 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11837 if (!ME) 11838 return; 11839 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 11840 if (!MD) 11841 return; 11842 const Expr *Base = ME->getBase(); 11843 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 11844 if (!MostDerivedClassDecl) 11845 return; 11846 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 11847 if (!DM || DM->isPure()) 11848 return; 11849 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 11850 } 11851 11852 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 11853 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 11854 // TODO: update this with DR# once a defect report is filed. 11855 // C++11 defect. The address of a pure member should not be an ODR use, even 11856 // if it's a qualified reference. 11857 bool OdrUse = true; 11858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 11859 if (Method->isVirtual()) 11860 OdrUse = false; 11861 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 11862 } 11863 11864 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 11865 void Sema::MarkMemberReferenced(MemberExpr *E) { 11866 // C++11 [basic.def.odr]p2: 11867 // A non-overloaded function whose name appears as a potentially-evaluated 11868 // expression or a member of a set of candidate functions, if selected by 11869 // overload resolution when referred to from a potentially-evaluated 11870 // expression, is odr-used, unless it is a pure virtual function and its 11871 // name is not explicitly qualified. 11872 bool OdrUse = true; 11873 if (!E->hasQualifier()) { 11874 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 11875 if (Method->isPure()) 11876 OdrUse = false; 11877 } 11878 SourceLocation Loc = E->getMemberLoc().isValid() ? 11879 E->getMemberLoc() : E->getLocStart(); 11880 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 11881 } 11882 11883 /// \brief Perform marking for a reference to an arbitrary declaration. It 11884 /// marks the declaration referenced, and performs odr-use checking for functions 11885 /// and variables. This method should not be used when building an normal 11886 /// expression which refers to a variable. 11887 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 11888 if (OdrUse) { 11889 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11890 MarkVariableReferenced(Loc, VD); 11891 return; 11892 } 11893 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 11894 MarkFunctionReferenced(Loc, FD); 11895 return; 11896 } 11897 } 11898 D->setReferenced(); 11899 } 11900 11901 namespace { 11902 // Mark all of the declarations referenced 11903 // FIXME: Not fully implemented yet! We need to have a better understanding 11904 // of when we're entering 11905 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 11906 Sema &S; 11907 SourceLocation Loc; 11908 11909 public: 11910 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 11911 11912 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 11913 11914 bool TraverseTemplateArgument(const TemplateArgument &Arg); 11915 bool TraverseRecordType(RecordType *T); 11916 }; 11917 } 11918 11919 bool MarkReferencedDecls::TraverseTemplateArgument( 11920 const TemplateArgument &Arg) { 11921 if (Arg.getKind() == TemplateArgument::Declaration) { 11922 if (Decl *D = Arg.getAsDecl()) 11923 S.MarkAnyDeclReferenced(Loc, D, true); 11924 } 11925 11926 return Inherited::TraverseTemplateArgument(Arg); 11927 } 11928 11929 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 11930 if (ClassTemplateSpecializationDecl *Spec 11931 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 11932 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 11933 return TraverseTemplateArguments(Args.data(), Args.size()); 11934 } 11935 11936 return true; 11937 } 11938 11939 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 11940 MarkReferencedDecls Marker(*this, Loc); 11941 Marker.TraverseType(Context.getCanonicalType(T)); 11942 } 11943 11944 namespace { 11945 /// \brief Helper class that marks all of the declarations referenced by 11946 /// potentially-evaluated subexpressions as "referenced". 11947 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 11948 Sema &S; 11949 bool SkipLocalVariables; 11950 11951 public: 11952 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 11953 11954 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 11955 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 11956 11957 void VisitDeclRefExpr(DeclRefExpr *E) { 11958 // If we were asked not to visit local variables, don't. 11959 if (SkipLocalVariables) { 11960 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 11961 if (VD->hasLocalStorage()) 11962 return; 11963 } 11964 11965 S.MarkDeclRefReferenced(E); 11966 } 11967 11968 void VisitMemberExpr(MemberExpr *E) { 11969 S.MarkMemberReferenced(E); 11970 Inherited::VisitMemberExpr(E); 11971 } 11972 11973 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 11974 S.MarkFunctionReferenced(E->getLocStart(), 11975 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 11976 Visit(E->getSubExpr()); 11977 } 11978 11979 void VisitCXXNewExpr(CXXNewExpr *E) { 11980 if (E->getOperatorNew()) 11981 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 11982 if (E->getOperatorDelete()) 11983 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11984 Inherited::VisitCXXNewExpr(E); 11985 } 11986 11987 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11988 if (E->getOperatorDelete()) 11989 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11990 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11991 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11992 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11993 S.MarkFunctionReferenced(E->getLocStart(), 11994 S.LookupDestructor(Record)); 11995 } 11996 11997 Inherited::VisitCXXDeleteExpr(E); 11998 } 11999 12000 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12001 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12002 Inherited::VisitCXXConstructExpr(E); 12003 } 12004 12005 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12006 Visit(E->getExpr()); 12007 } 12008 12009 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12010 Inherited::VisitImplicitCastExpr(E); 12011 12012 if (E->getCastKind() == CK_LValueToRValue) 12013 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12014 } 12015 }; 12016 } 12017 12018 /// \brief Mark any declarations that appear within this expression or any 12019 /// potentially-evaluated subexpressions as "referenced". 12020 /// 12021 /// \param SkipLocalVariables If true, don't mark local variables as 12022 /// 'referenced'. 12023 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12024 bool SkipLocalVariables) { 12025 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12026 } 12027 12028 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12029 /// of the program being compiled. 12030 /// 12031 /// This routine emits the given diagnostic when the code currently being 12032 /// type-checked is "potentially evaluated", meaning that there is a 12033 /// possibility that the code will actually be executable. Code in sizeof() 12034 /// expressions, code used only during overload resolution, etc., are not 12035 /// potentially evaluated. This routine will suppress such diagnostics or, 12036 /// in the absolutely nutty case of potentially potentially evaluated 12037 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12038 /// later. 12039 /// 12040 /// This routine should be used for all diagnostics that describe the run-time 12041 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12042 /// Failure to do so will likely result in spurious diagnostics or failures 12043 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12044 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12045 const PartialDiagnostic &PD) { 12046 switch (ExprEvalContexts.back().Context) { 12047 case Unevaluated: 12048 case UnevaluatedAbstract: 12049 // The argument will never be evaluated, so don't complain. 12050 break; 12051 12052 case ConstantEvaluated: 12053 // Relevant diagnostics should be produced by constant evaluation. 12054 break; 12055 12056 case PotentiallyEvaluated: 12057 case PotentiallyEvaluatedIfUsed: 12058 if (Statement && getCurFunctionOrMethodDecl()) { 12059 FunctionScopes.back()->PossiblyUnreachableDiags. 12060 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12061 } 12062 else 12063 Diag(Loc, PD); 12064 12065 return true; 12066 } 12067 12068 return false; 12069 } 12070 12071 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12072 CallExpr *CE, FunctionDecl *FD) { 12073 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12074 return false; 12075 12076 // If we're inside a decltype's expression, don't check for a valid return 12077 // type or construct temporaries until we know whether this is the last call. 12078 if (ExprEvalContexts.back().IsDecltype) { 12079 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12080 return false; 12081 } 12082 12083 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12084 FunctionDecl *FD; 12085 CallExpr *CE; 12086 12087 public: 12088 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12089 : FD(FD), CE(CE) { } 12090 12091 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 12092 if (!FD) { 12093 S.Diag(Loc, diag::err_call_incomplete_return) 12094 << T << CE->getSourceRange(); 12095 return; 12096 } 12097 12098 S.Diag(Loc, diag::err_call_function_incomplete_return) 12099 << CE->getSourceRange() << FD->getDeclName() << T; 12100 S.Diag(FD->getLocation(), 12101 diag::note_function_with_incomplete_return_type_declared_here) 12102 << FD->getDeclName(); 12103 } 12104 } Diagnoser(FD, CE); 12105 12106 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12107 return true; 12108 12109 return false; 12110 } 12111 12112 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12113 // will prevent this condition from triggering, which is what we want. 12114 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12115 SourceLocation Loc; 12116 12117 unsigned diagnostic = diag::warn_condition_is_assignment; 12118 bool IsOrAssign = false; 12119 12120 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12121 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12122 return; 12123 12124 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12125 12126 // Greylist some idioms by putting them into a warning subcategory. 12127 if (ObjCMessageExpr *ME 12128 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12129 Selector Sel = ME->getSelector(); 12130 12131 // self = [<foo> init...] 12132 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12133 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12134 12135 // <foo> = [<bar> nextObject] 12136 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12137 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12138 } 12139 12140 Loc = Op->getOperatorLoc(); 12141 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12142 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12143 return; 12144 12145 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12146 Loc = Op->getOperatorLoc(); 12147 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12148 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12149 else { 12150 // Not an assignment. 12151 return; 12152 } 12153 12154 Diag(Loc, diagnostic) << E->getSourceRange(); 12155 12156 SourceLocation Open = E->getLocStart(); 12157 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12158 Diag(Loc, diag::note_condition_assign_silence) 12159 << FixItHint::CreateInsertion(Open, "(") 12160 << FixItHint::CreateInsertion(Close, ")"); 12161 12162 if (IsOrAssign) 12163 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12164 << FixItHint::CreateReplacement(Loc, "!="); 12165 else 12166 Diag(Loc, diag::note_condition_assign_to_comparison) 12167 << FixItHint::CreateReplacement(Loc, "=="); 12168 } 12169 12170 /// \brief Redundant parentheses over an equality comparison can indicate 12171 /// that the user intended an assignment used as condition. 12172 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12173 // Don't warn if the parens came from a macro. 12174 SourceLocation parenLoc = ParenE->getLocStart(); 12175 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12176 return; 12177 // Don't warn for dependent expressions. 12178 if (ParenE->isTypeDependent()) 12179 return; 12180 12181 Expr *E = ParenE->IgnoreParens(); 12182 12183 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12184 if (opE->getOpcode() == BO_EQ && 12185 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12186 == Expr::MLV_Valid) { 12187 SourceLocation Loc = opE->getOperatorLoc(); 12188 12189 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12190 SourceRange ParenERange = ParenE->getSourceRange(); 12191 Diag(Loc, diag::note_equality_comparison_silence) 12192 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12193 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12194 Diag(Loc, diag::note_equality_comparison_to_assign) 12195 << FixItHint::CreateReplacement(Loc, "="); 12196 } 12197 } 12198 12199 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12200 DiagnoseAssignmentAsCondition(E); 12201 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12202 DiagnoseEqualityWithExtraParens(parenE); 12203 12204 ExprResult result = CheckPlaceholderExpr(E); 12205 if (result.isInvalid()) return ExprError(); 12206 E = result.take(); 12207 12208 if (!E->isTypeDependent()) { 12209 if (getLangOpts().CPlusPlus) 12210 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12211 12212 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12213 if (ERes.isInvalid()) 12214 return ExprError(); 12215 E = ERes.take(); 12216 12217 QualType T = E->getType(); 12218 if (!T->isScalarType()) { // C99 6.8.4.1p1 12219 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12220 << T << E->getSourceRange(); 12221 return ExprError(); 12222 } 12223 } 12224 12225 return Owned(E); 12226 } 12227 12228 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12229 Expr *SubExpr) { 12230 if (!SubExpr) 12231 return ExprError(); 12232 12233 return CheckBooleanCondition(SubExpr, Loc); 12234 } 12235 12236 namespace { 12237 /// A visitor for rebuilding a call to an __unknown_any expression 12238 /// to have an appropriate type. 12239 struct RebuildUnknownAnyFunction 12240 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12241 12242 Sema &S; 12243 12244 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12245 12246 ExprResult VisitStmt(Stmt *S) { 12247 llvm_unreachable("unexpected statement!"); 12248 } 12249 12250 ExprResult VisitExpr(Expr *E) { 12251 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12252 << E->getSourceRange(); 12253 return ExprError(); 12254 } 12255 12256 /// Rebuild an expression which simply semantically wraps another 12257 /// expression which it shares the type and value kind of. 12258 template <class T> ExprResult rebuildSugarExpr(T *E) { 12259 ExprResult SubResult = Visit(E->getSubExpr()); 12260 if (SubResult.isInvalid()) return ExprError(); 12261 12262 Expr *SubExpr = SubResult.take(); 12263 E->setSubExpr(SubExpr); 12264 E->setType(SubExpr->getType()); 12265 E->setValueKind(SubExpr->getValueKind()); 12266 assert(E->getObjectKind() == OK_Ordinary); 12267 return E; 12268 } 12269 12270 ExprResult VisitParenExpr(ParenExpr *E) { 12271 return rebuildSugarExpr(E); 12272 } 12273 12274 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12275 return rebuildSugarExpr(E); 12276 } 12277 12278 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12279 ExprResult SubResult = Visit(E->getSubExpr()); 12280 if (SubResult.isInvalid()) return ExprError(); 12281 12282 Expr *SubExpr = SubResult.take(); 12283 E->setSubExpr(SubExpr); 12284 E->setType(S.Context.getPointerType(SubExpr->getType())); 12285 assert(E->getValueKind() == VK_RValue); 12286 assert(E->getObjectKind() == OK_Ordinary); 12287 return E; 12288 } 12289 12290 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12291 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12292 12293 E->setType(VD->getType()); 12294 12295 assert(E->getValueKind() == VK_RValue); 12296 if (S.getLangOpts().CPlusPlus && 12297 !(isa<CXXMethodDecl>(VD) && 12298 cast<CXXMethodDecl>(VD)->isInstance())) 12299 E->setValueKind(VK_LValue); 12300 12301 return E; 12302 } 12303 12304 ExprResult VisitMemberExpr(MemberExpr *E) { 12305 return resolveDecl(E, E->getMemberDecl()); 12306 } 12307 12308 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12309 return resolveDecl(E, E->getDecl()); 12310 } 12311 }; 12312 } 12313 12314 /// Given a function expression of unknown-any type, try to rebuild it 12315 /// to have a function type. 12316 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12317 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12318 if (Result.isInvalid()) return ExprError(); 12319 return S.DefaultFunctionArrayConversion(Result.take()); 12320 } 12321 12322 namespace { 12323 /// A visitor for rebuilding an expression of type __unknown_anytype 12324 /// into one which resolves the type directly on the referring 12325 /// expression. Strict preservation of the original source 12326 /// structure is not a goal. 12327 struct RebuildUnknownAnyExpr 12328 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12329 12330 Sema &S; 12331 12332 /// The current destination type. 12333 QualType DestType; 12334 12335 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12336 : S(S), DestType(CastType) {} 12337 12338 ExprResult VisitStmt(Stmt *S) { 12339 llvm_unreachable("unexpected statement!"); 12340 } 12341 12342 ExprResult VisitExpr(Expr *E) { 12343 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12344 << E->getSourceRange(); 12345 return ExprError(); 12346 } 12347 12348 ExprResult VisitCallExpr(CallExpr *E); 12349 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12350 12351 /// Rebuild an expression which simply semantically wraps another 12352 /// expression which it shares the type and value kind of. 12353 template <class T> ExprResult rebuildSugarExpr(T *E) { 12354 ExprResult SubResult = Visit(E->getSubExpr()); 12355 if (SubResult.isInvalid()) return ExprError(); 12356 Expr *SubExpr = SubResult.take(); 12357 E->setSubExpr(SubExpr); 12358 E->setType(SubExpr->getType()); 12359 E->setValueKind(SubExpr->getValueKind()); 12360 assert(E->getObjectKind() == OK_Ordinary); 12361 return E; 12362 } 12363 12364 ExprResult VisitParenExpr(ParenExpr *E) { 12365 return rebuildSugarExpr(E); 12366 } 12367 12368 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12369 return rebuildSugarExpr(E); 12370 } 12371 12372 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12373 const PointerType *Ptr = DestType->getAs<PointerType>(); 12374 if (!Ptr) { 12375 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12376 << E->getSourceRange(); 12377 return ExprError(); 12378 } 12379 assert(E->getValueKind() == VK_RValue); 12380 assert(E->getObjectKind() == OK_Ordinary); 12381 E->setType(DestType); 12382 12383 // Build the sub-expression as if it were an object of the pointee type. 12384 DestType = Ptr->getPointeeType(); 12385 ExprResult SubResult = Visit(E->getSubExpr()); 12386 if (SubResult.isInvalid()) return ExprError(); 12387 E->setSubExpr(SubResult.take()); 12388 return E; 12389 } 12390 12391 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12392 12393 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12394 12395 ExprResult VisitMemberExpr(MemberExpr *E) { 12396 return resolveDecl(E, E->getMemberDecl()); 12397 } 12398 12399 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12400 return resolveDecl(E, E->getDecl()); 12401 } 12402 }; 12403 } 12404 12405 /// Rebuilds a call expression which yielded __unknown_anytype. 12406 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12407 Expr *CalleeExpr = E->getCallee(); 12408 12409 enum FnKind { 12410 FK_MemberFunction, 12411 FK_FunctionPointer, 12412 FK_BlockPointer 12413 }; 12414 12415 FnKind Kind; 12416 QualType CalleeType = CalleeExpr->getType(); 12417 if (CalleeType == S.Context.BoundMemberTy) { 12418 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12419 Kind = FK_MemberFunction; 12420 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12421 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12422 CalleeType = Ptr->getPointeeType(); 12423 Kind = FK_FunctionPointer; 12424 } else { 12425 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12426 Kind = FK_BlockPointer; 12427 } 12428 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12429 12430 // Verify that this is a legal result type of a function. 12431 if (DestType->isArrayType() || DestType->isFunctionType()) { 12432 unsigned diagID = diag::err_func_returning_array_function; 12433 if (Kind == FK_BlockPointer) 12434 diagID = diag::err_block_returning_array_function; 12435 12436 S.Diag(E->getExprLoc(), diagID) 12437 << DestType->isFunctionType() << DestType; 12438 return ExprError(); 12439 } 12440 12441 // Otherwise, go ahead and set DestType as the call's result. 12442 E->setType(DestType.getNonLValueExprType(S.Context)); 12443 E->setValueKind(Expr::getValueKindForType(DestType)); 12444 assert(E->getObjectKind() == OK_Ordinary); 12445 12446 // Rebuild the function type, replacing the result type with DestType. 12447 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12448 if (Proto) { 12449 // __unknown_anytype(...) is a special case used by the debugger when 12450 // it has no idea what a function's signature is. 12451 // 12452 // We want to build this call essentially under the K&R 12453 // unprototyped rules, but making a FunctionNoProtoType in C++ 12454 // would foul up all sorts of assumptions. However, we cannot 12455 // simply pass all arguments as variadic arguments, nor can we 12456 // portably just call the function under a non-variadic type; see 12457 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12458 // However, it turns out that in practice it is generally safe to 12459 // call a function declared as "A foo(B,C,D);" under the prototype 12460 // "A foo(B,C,D,...);". The only known exception is with the 12461 // Windows ABI, where any variadic function is implicitly cdecl 12462 // regardless of its normal CC. Therefore we change the parameter 12463 // types to match the types of the arguments. 12464 // 12465 // This is a hack, but it is far superior to moving the 12466 // corresponding target-specific code from IR-gen to Sema/AST. 12467 12468 ArrayRef<QualType> ParamTypes = Proto->getArgTypes(); 12469 SmallVector<QualType, 8> ArgTypes; 12470 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12471 ArgTypes.reserve(E->getNumArgs()); 12472 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12473 Expr *Arg = E->getArg(i); 12474 QualType ArgType = Arg->getType(); 12475 if (E->isLValue()) { 12476 ArgType = S.Context.getLValueReferenceType(ArgType); 12477 } else if (E->isXValue()) { 12478 ArgType = S.Context.getRValueReferenceType(ArgType); 12479 } 12480 ArgTypes.push_back(ArgType); 12481 } 12482 ParamTypes = ArgTypes; 12483 } 12484 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12485 Proto->getExtProtoInfo()); 12486 } else { 12487 DestType = S.Context.getFunctionNoProtoType(DestType, 12488 FnType->getExtInfo()); 12489 } 12490 12491 // Rebuild the appropriate pointer-to-function type. 12492 switch (Kind) { 12493 case FK_MemberFunction: 12494 // Nothing to do. 12495 break; 12496 12497 case FK_FunctionPointer: 12498 DestType = S.Context.getPointerType(DestType); 12499 break; 12500 12501 case FK_BlockPointer: 12502 DestType = S.Context.getBlockPointerType(DestType); 12503 break; 12504 } 12505 12506 // Finally, we can recurse. 12507 ExprResult CalleeResult = Visit(CalleeExpr); 12508 if (!CalleeResult.isUsable()) return ExprError(); 12509 E->setCallee(CalleeResult.take()); 12510 12511 // Bind a temporary if necessary. 12512 return S.MaybeBindToTemporary(E); 12513 } 12514 12515 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12516 // Verify that this is a legal result type of a call. 12517 if (DestType->isArrayType() || DestType->isFunctionType()) { 12518 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12519 << DestType->isFunctionType() << DestType; 12520 return ExprError(); 12521 } 12522 12523 // Rewrite the method result type if available. 12524 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12525 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12526 Method->setResultType(DestType); 12527 } 12528 12529 // Change the type of the message. 12530 E->setType(DestType.getNonReferenceType()); 12531 E->setValueKind(Expr::getValueKindForType(DestType)); 12532 12533 return S.MaybeBindToTemporary(E); 12534 } 12535 12536 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12537 // The only case we should ever see here is a function-to-pointer decay. 12538 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12539 assert(E->getValueKind() == VK_RValue); 12540 assert(E->getObjectKind() == OK_Ordinary); 12541 12542 E->setType(DestType); 12543 12544 // Rebuild the sub-expression as the pointee (function) type. 12545 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12546 12547 ExprResult Result = Visit(E->getSubExpr()); 12548 if (!Result.isUsable()) return ExprError(); 12549 12550 E->setSubExpr(Result.take()); 12551 return S.Owned(E); 12552 } else if (E->getCastKind() == CK_LValueToRValue) { 12553 assert(E->getValueKind() == VK_RValue); 12554 assert(E->getObjectKind() == OK_Ordinary); 12555 12556 assert(isa<BlockPointerType>(E->getType())); 12557 12558 E->setType(DestType); 12559 12560 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12561 DestType = S.Context.getLValueReferenceType(DestType); 12562 12563 ExprResult Result = Visit(E->getSubExpr()); 12564 if (!Result.isUsable()) return ExprError(); 12565 12566 E->setSubExpr(Result.take()); 12567 return S.Owned(E); 12568 } else { 12569 llvm_unreachable("Unhandled cast type!"); 12570 } 12571 } 12572 12573 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12574 ExprValueKind ValueKind = VK_LValue; 12575 QualType Type = DestType; 12576 12577 // We know how to make this work for certain kinds of decls: 12578 12579 // - functions 12580 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12581 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12582 DestType = Ptr->getPointeeType(); 12583 ExprResult Result = resolveDecl(E, VD); 12584 if (Result.isInvalid()) return ExprError(); 12585 return S.ImpCastExprToType(Result.take(), Type, 12586 CK_FunctionToPointerDecay, VK_RValue); 12587 } 12588 12589 if (!Type->isFunctionType()) { 12590 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12591 << VD << E->getSourceRange(); 12592 return ExprError(); 12593 } 12594 12595 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12596 if (MD->isInstance()) { 12597 ValueKind = VK_RValue; 12598 Type = S.Context.BoundMemberTy; 12599 } 12600 12601 // Function references aren't l-values in C. 12602 if (!S.getLangOpts().CPlusPlus) 12603 ValueKind = VK_RValue; 12604 12605 // - variables 12606 } else if (isa<VarDecl>(VD)) { 12607 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12608 Type = RefTy->getPointeeType(); 12609 } else if (Type->isFunctionType()) { 12610 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12611 << VD << E->getSourceRange(); 12612 return ExprError(); 12613 } 12614 12615 // - nothing else 12616 } else { 12617 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12618 << VD << E->getSourceRange(); 12619 return ExprError(); 12620 } 12621 12622 // Modifying the declaration like this is friendly to IR-gen but 12623 // also really dangerous. 12624 VD->setType(DestType); 12625 E->setType(Type); 12626 E->setValueKind(ValueKind); 12627 return S.Owned(E); 12628 } 12629 12630 /// Check a cast of an unknown-any type. We intentionally only 12631 /// trigger this for C-style casts. 12632 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12633 Expr *CastExpr, CastKind &CastKind, 12634 ExprValueKind &VK, CXXCastPath &Path) { 12635 // Rewrite the casted expression from scratch. 12636 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12637 if (!result.isUsable()) return ExprError(); 12638 12639 CastExpr = result.take(); 12640 VK = CastExpr->getValueKind(); 12641 CastKind = CK_NoOp; 12642 12643 return CastExpr; 12644 } 12645 12646 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 12647 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 12648 } 12649 12650 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 12651 Expr *arg, QualType ¶mType) { 12652 // If the syntactic form of the argument is not an explicit cast of 12653 // any sort, just do default argument promotion. 12654 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 12655 if (!castArg) { 12656 ExprResult result = DefaultArgumentPromotion(arg); 12657 if (result.isInvalid()) return ExprError(); 12658 paramType = result.get()->getType(); 12659 return result; 12660 } 12661 12662 // Otherwise, use the type that was written in the explicit cast. 12663 assert(!arg->hasPlaceholderType()); 12664 paramType = castArg->getTypeAsWritten(); 12665 12666 // Copy-initialize a parameter of that type. 12667 InitializedEntity entity = 12668 InitializedEntity::InitializeParameter(Context, paramType, 12669 /*consumed*/ false); 12670 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 12671 } 12672 12673 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 12674 Expr *orig = E; 12675 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 12676 while (true) { 12677 E = E->IgnoreParenImpCasts(); 12678 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 12679 E = call->getCallee(); 12680 diagID = diag::err_uncasted_call_of_unknown_any; 12681 } else { 12682 break; 12683 } 12684 } 12685 12686 SourceLocation loc; 12687 NamedDecl *d; 12688 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 12689 loc = ref->getLocation(); 12690 d = ref->getDecl(); 12691 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 12692 loc = mem->getMemberLoc(); 12693 d = mem->getMemberDecl(); 12694 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 12695 diagID = diag::err_uncasted_call_of_unknown_any; 12696 loc = msg->getSelectorStartLoc(); 12697 d = msg->getMethodDecl(); 12698 if (!d) { 12699 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 12700 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 12701 << orig->getSourceRange(); 12702 return ExprError(); 12703 } 12704 } else { 12705 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12706 << E->getSourceRange(); 12707 return ExprError(); 12708 } 12709 12710 S.Diag(loc, diagID) << d << orig->getSourceRange(); 12711 12712 // Never recoverable. 12713 return ExprError(); 12714 } 12715 12716 /// Check for operands with placeholder types and complain if found. 12717 /// Returns true if there was an error and no recovery was possible. 12718 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 12719 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 12720 if (!placeholderType) return Owned(E); 12721 12722 switch (placeholderType->getKind()) { 12723 12724 // Overloaded expressions. 12725 case BuiltinType::Overload: { 12726 // Try to resolve a single function template specialization. 12727 // This is obligatory. 12728 ExprResult result = Owned(E); 12729 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 12730 return result; 12731 12732 // If that failed, try to recover with a call. 12733 } else { 12734 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 12735 /*complain*/ true); 12736 return result; 12737 } 12738 } 12739 12740 // Bound member functions. 12741 case BuiltinType::BoundMember: { 12742 ExprResult result = Owned(E); 12743 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 12744 /*complain*/ true); 12745 return result; 12746 } 12747 12748 // ARC unbridged casts. 12749 case BuiltinType::ARCUnbridgedCast: { 12750 Expr *realCast = stripARCUnbridgedCast(E); 12751 diagnoseARCUnbridgedCast(realCast); 12752 return Owned(realCast); 12753 } 12754 12755 // Expressions of unknown type. 12756 case BuiltinType::UnknownAny: 12757 return diagnoseUnknownAnyExpr(*this, E); 12758 12759 // Pseudo-objects. 12760 case BuiltinType::PseudoObject: 12761 return checkPseudoObjectRValue(E); 12762 12763 case BuiltinType::BuiltinFn: 12764 Diag(E->getLocStart(), diag::err_builtin_fn_use); 12765 return ExprError(); 12766 12767 // Everything else should be impossible. 12768 #define BUILTIN_TYPE(Id, SingletonId) \ 12769 case BuiltinType::Id: 12770 #define PLACEHOLDER_TYPE(Id, SingletonId) 12771 #include "clang/AST/BuiltinTypes.def" 12772 break; 12773 } 12774 12775 llvm_unreachable("invalid placeholder type!"); 12776 } 12777 12778 bool Sema::CheckCaseExpression(Expr *E) { 12779 if (E->isTypeDependent()) 12780 return true; 12781 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 12782 return E->getType()->isIntegralOrEnumerationType(); 12783 return false; 12784 } 12785 12786 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 12787 ExprResult 12788 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 12789 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 12790 "Unknown Objective-C Boolean value!"); 12791 QualType BoolT = Context.ObjCBuiltinBoolTy; 12792 if (!Context.getBOOLDecl()) { 12793 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 12794 Sema::LookupOrdinaryName); 12795 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 12796 NamedDecl *ND = Result.getFoundDecl(); 12797 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 12798 Context.setBOOLDecl(TD); 12799 } 12800 } 12801 if (Context.getBOOLDecl()) 12802 BoolT = Context.getBOOLType(); 12803 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12804 BoolT, OpLoc)); 12805 } 12806