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 60 // See if this function is unavailable. 61 if (D->getAvailability() == AR_Unavailable && 62 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 63 return false; 64 65 return true; 66 } 67 68 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 69 // Warn if this is used but marked unused. 70 if (D->hasAttr<UnusedAttr>()) { 71 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 72 if (!DC->hasAttr<UnusedAttr>()) 73 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 74 } 75 } 76 77 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 78 NamedDecl *D, SourceLocation Loc, 79 const ObjCInterfaceDecl *UnknownObjCClass) { 80 // See if this declaration is unavailable or deprecated. 81 std::string Message; 82 AvailabilityResult Result = D->getAvailability(&Message); 83 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 84 if (Result == AR_Available) { 85 const DeclContext *DC = ECD->getDeclContext(); 86 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 87 Result = TheEnumDecl->getAvailability(&Message); 88 } 89 90 const ObjCPropertyDecl *ObjCPDecl = 0; 91 if (Result == AR_Deprecated || Result == AR_Unavailable) { 92 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 93 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 94 AvailabilityResult PDeclResult = PD->getAvailability(0); 95 if (PDeclResult == Result) 96 ObjCPDecl = PD; 97 } 98 } 99 } 100 101 switch (Result) { 102 case AR_Available: 103 case AR_NotYetIntroduced: 104 break; 105 106 case AR_Deprecated: 107 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 108 break; 109 110 case AR_Unavailable: 111 if (S.getCurContextAvailability() != AR_Unavailable) { 112 if (Message.empty()) { 113 if (!UnknownObjCClass) { 114 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 115 if (ObjCPDecl) 116 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 117 << ObjCPDecl->getDeclName() << 1; 118 } 119 else 120 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 121 << D->getDeclName(); 122 } 123 else 124 S.Diag(Loc, diag::err_unavailable_message) 125 << D->getDeclName() << Message; 126 S.Diag(D->getLocation(), diag::note_unavailable_here) 127 << isa<FunctionDecl>(D) << false; 128 if (ObjCPDecl) 129 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 130 << ObjCPDecl->getDeclName() << 1; 131 } 132 break; 133 } 134 return Result; 135 } 136 137 /// \brief Emit a note explaining that this function is deleted or unavailable. 138 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 139 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 140 141 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 142 // If the method was explicitly defaulted, point at that declaration. 143 if (!Method->isImplicit()) 144 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 145 146 // Try to diagnose why this special member function was implicitly 147 // deleted. This might fail, if that reason no longer applies. 148 CXXSpecialMember CSM = getSpecialMember(Method); 149 if (CSM != CXXInvalid) 150 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 151 152 return; 153 } 154 155 Diag(Decl->getLocation(), diag::note_unavailable_here) 156 << 1 << Decl->isDeleted(); 157 } 158 159 /// \brief Determine whether a FunctionDecl was ever declared with an 160 /// explicit storage class. 161 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 162 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 163 E = D->redecls_end(); 164 I != E; ++I) { 165 if (I->getStorageClass() != SC_None) 166 return true; 167 } 168 return false; 169 } 170 171 /// \brief Check whether we're in an extern inline function and referring to a 172 /// variable or function with internal linkage (C11 6.7.4p3). 173 /// 174 /// This is only a warning because we used to silently accept this code, but 175 /// in many cases it will not behave correctly. This is not enabled in C++ mode 176 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 177 /// and so while there may still be user mistakes, most of the time we can't 178 /// prove that there are errors. 179 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 180 const NamedDecl *D, 181 SourceLocation Loc) { 182 // This is disabled under C++; there are too many ways for this to fire in 183 // contexts where the warning is a false positive, or where it is technically 184 // correct but benign. 185 if (S.getLangOpts().CPlusPlus) 186 return; 187 188 // Check if this is an inlined function or method. 189 FunctionDecl *Current = S.getCurFunctionDecl(); 190 if (!Current) 191 return; 192 if (!Current->isInlined()) 193 return; 194 if (Current->getLinkage() != ExternalLinkage) 195 return; 196 197 // Check if the decl has internal linkage. 198 if (D->getLinkage() != InternalLinkage) 199 return; 200 201 // Downgrade from ExtWarn to Extension if 202 // (1) the supposedly external inline function is in the main file, 203 // and probably won't be included anywhere else. 204 // (2) the thing we're referencing is a pure function. 205 // (3) the thing we're referencing is another inline function. 206 // This last can give us false negatives, but it's better than warning on 207 // wrappers for simple C library functions. 208 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 209 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 210 if (!DowngradeWarning && UsedFn) 211 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 212 213 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 214 : diag::warn_internal_in_extern_inline) 215 << /*IsVar=*/!UsedFn << D; 216 217 S.MaybeSuggestAddingStaticToDecl(Current); 218 219 S.Diag(D->getCanonicalDecl()->getLocation(), 220 diag::note_internal_decl_declared_here) 221 << D; 222 } 223 224 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 225 const FunctionDecl *First = Cur->getFirstDeclaration(); 226 227 // Suggest "static" on the function, if possible. 228 if (!hasAnyExplicitStorageClass(First)) { 229 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 230 Diag(DeclBegin, diag::note_convert_inline_to_static) 231 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 232 } 233 } 234 235 /// \brief Determine whether the use of this declaration is valid, and 236 /// emit any corresponding diagnostics. 237 /// 238 /// This routine diagnoses various problems with referencing 239 /// declarations that can occur when using a declaration. For example, 240 /// it might warn if a deprecated or unavailable declaration is being 241 /// used, or produce an error (and return true) if a C++0x deleted 242 /// function is being used. 243 /// 244 /// \returns true if there was an error (this declaration cannot be 245 /// referenced), false otherwise. 246 /// 247 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 248 const ObjCInterfaceDecl *UnknownObjCClass) { 249 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 250 // If there were any diagnostics suppressed by template argument deduction, 251 // emit them now. 252 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 253 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 254 if (Pos != SuppressedDiagnostics.end()) { 255 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 256 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 257 Diag(Suppressed[I].first, Suppressed[I].second); 258 259 // Clear out the list of suppressed diagnostics, so that we don't emit 260 // them again for this specialization. However, we don't obsolete this 261 // entry from the table, because we want to avoid ever emitting these 262 // diagnostics again. 263 Suppressed.clear(); 264 } 265 } 266 267 // See if this is an auto-typed variable whose initializer we are parsing. 268 if (ParsingInitForAutoVars.count(D)) { 269 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 270 << D->getDeclName(); 271 return true; 272 } 273 274 // See if this is a deleted function. 275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 276 if (FD->isDeleted()) { 277 Diag(Loc, diag::err_deleted_function_use); 278 NoteDeletedFunction(FD); 279 return true; 280 } 281 } 282 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 283 284 DiagnoseUnusedOfDecl(*this, D, Loc); 285 286 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 287 288 return false; 289 } 290 291 /// \brief Retrieve the message suffix that should be added to a 292 /// diagnostic complaining about the given function being deleted or 293 /// unavailable. 294 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 295 std::string Message; 296 if (FD->getAvailability(&Message)) 297 return ": " + Message; 298 299 return std::string(); 300 } 301 302 /// DiagnoseSentinelCalls - This routine checks whether a call or 303 /// message-send is to a declaration with the sentinel attribute, and 304 /// if so, it checks that the requirements of the sentinel are 305 /// satisfied. 306 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 307 Expr **args, unsigned numArgs) { 308 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 309 if (!attr) 310 return; 311 312 // The number of formal parameters of the declaration. 313 unsigned numFormalParams; 314 315 // The kind of declaration. This is also an index into a %select in 316 // the diagnostic. 317 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 318 319 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 320 numFormalParams = MD->param_size(); 321 calleeType = CT_Method; 322 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 323 numFormalParams = FD->param_size(); 324 calleeType = CT_Function; 325 } else if (isa<VarDecl>(D)) { 326 QualType type = cast<ValueDecl>(D)->getType(); 327 const FunctionType *fn = 0; 328 if (const PointerType *ptr = type->getAs<PointerType>()) { 329 fn = ptr->getPointeeType()->getAs<FunctionType>(); 330 if (!fn) return; 331 calleeType = CT_Function; 332 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 333 fn = ptr->getPointeeType()->castAs<FunctionType>(); 334 calleeType = CT_Block; 335 } else { 336 return; 337 } 338 339 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 340 numFormalParams = proto->getNumArgs(); 341 } else { 342 numFormalParams = 0; 343 } 344 } else { 345 return; 346 } 347 348 // "nullPos" is the number of formal parameters at the end which 349 // effectively count as part of the variadic arguments. This is 350 // useful if you would prefer to not have *any* formal parameters, 351 // but the language forces you to have at least one. 352 unsigned nullPos = attr->getNullPos(); 353 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 354 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 355 356 // The number of arguments which should follow the sentinel. 357 unsigned numArgsAfterSentinel = attr->getSentinel(); 358 359 // If there aren't enough arguments for all the formal parameters, 360 // the sentinel, and the args after the sentinel, complain. 361 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 362 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 363 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 364 return; 365 } 366 367 // Otherwise, find the sentinel expression. 368 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 369 if (!sentinelExpr) return; 370 if (sentinelExpr->isValueDependent()) return; 371 if (Context.isSentinelNullExpr(sentinelExpr)) return; 372 373 // Pick a reasonable string to insert. Optimistically use 'nil' or 374 // 'NULL' if those are actually defined in the context. Only use 375 // 'nil' for ObjC methods, where it's much more likely that the 376 // variadic arguments form a list of object pointers. 377 SourceLocation MissingNilLoc 378 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 379 std::string NullValue; 380 if (calleeType == CT_Method && 381 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 382 NullValue = "nil"; 383 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 384 NullValue = "NULL"; 385 else 386 NullValue = "(void*) 0"; 387 388 if (MissingNilLoc.isInvalid()) 389 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 390 else 391 Diag(MissingNilLoc, diag::warn_missing_sentinel) 392 << calleeType 393 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 394 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 395 } 396 397 SourceRange Sema::getExprRange(Expr *E) const { 398 return E ? E->getSourceRange() : SourceRange(); 399 } 400 401 //===----------------------------------------------------------------------===// 402 // Standard Promotions and Conversions 403 //===----------------------------------------------------------------------===// 404 405 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 406 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 407 // Handle any placeholder expressions which made it here. 408 if (E->getType()->isPlaceholderType()) { 409 ExprResult result = CheckPlaceholderExpr(E); 410 if (result.isInvalid()) return ExprError(); 411 E = result.take(); 412 } 413 414 QualType Ty = E->getType(); 415 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 416 417 if (Ty->isFunctionType()) 418 E = ImpCastExprToType(E, Context.getPointerType(Ty), 419 CK_FunctionToPointerDecay).take(); 420 else if (Ty->isArrayType()) { 421 // In C90 mode, arrays only promote to pointers if the array expression is 422 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 423 // type 'array of type' is converted to an expression that has type 'pointer 424 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 425 // that has type 'array of type' ...". The relevant change is "an lvalue" 426 // (C90) to "an expression" (C99). 427 // 428 // C++ 4.2p1: 429 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 430 // T" can be converted to an rvalue of type "pointer to T". 431 // 432 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 433 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 434 CK_ArrayToPointerDecay).take(); 435 } 436 return Owned(E); 437 } 438 439 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 440 // Check to see if we are dereferencing a null pointer. If so, 441 // and if not volatile-qualified, this is undefined behavior that the 442 // optimizer will delete, so warn about it. People sometimes try to use this 443 // to get a deterministic trap and are surprised by clang's behavior. This 444 // only handles the pattern "*null", which is a very syntactic check. 445 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 446 if (UO->getOpcode() == UO_Deref && 447 UO->getSubExpr()->IgnoreParenCasts()-> 448 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 449 !UO->getType().isVolatileQualified()) { 450 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 451 S.PDiag(diag::warn_indirection_through_null) 452 << UO->getSubExpr()->getSourceRange()); 453 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 454 S.PDiag(diag::note_indirection_through_null)); 455 } 456 } 457 458 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 459 SourceLocation AssignLoc, 460 const Expr* RHS) { 461 const ObjCIvarDecl *IV = OIRE->getDecl(); 462 if (!IV) 463 return; 464 465 DeclarationName MemberName = IV->getDeclName(); 466 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 467 if (!Member || !Member->isStr("isa")) 468 return; 469 470 const Expr *Base = OIRE->getBase(); 471 QualType BaseType = Base->getType(); 472 if (OIRE->isArrow()) 473 BaseType = BaseType->getPointeeType(); 474 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 475 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 476 ObjCInterfaceDecl *ClassDeclared = 0; 477 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 478 if (!ClassDeclared->getSuperClass() 479 && (*ClassDeclared->ivar_begin()) == IV) { 480 if (RHS) { 481 NamedDecl *ObjectSetClass = 482 S.LookupSingleName(S.TUScope, 483 &S.Context.Idents.get("object_setClass"), 484 SourceLocation(), S.LookupOrdinaryName); 485 if (ObjectSetClass) { 486 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 487 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 488 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 489 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 490 AssignLoc), ",") << 491 FixItHint::CreateInsertion(RHSLocEnd, ")"); 492 } 493 else 494 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 495 } else { 496 NamedDecl *ObjectGetClass = 497 S.LookupSingleName(S.TUScope, 498 &S.Context.Idents.get("object_getClass"), 499 SourceLocation(), S.LookupOrdinaryName); 500 if (ObjectGetClass) 501 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 502 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 503 FixItHint::CreateReplacement( 504 SourceRange(OIRE->getOpLoc(), 505 OIRE->getLocEnd()), ")"); 506 else 507 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 508 } 509 S.Diag(IV->getLocation(), diag::note_ivar_decl); 510 } 511 } 512 } 513 514 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 515 // Handle any placeholder expressions which made it here. 516 if (E->getType()->isPlaceholderType()) { 517 ExprResult result = CheckPlaceholderExpr(E); 518 if (result.isInvalid()) return ExprError(); 519 E = result.take(); 520 } 521 522 // C++ [conv.lval]p1: 523 // A glvalue of a non-function, non-array type T can be 524 // converted to a prvalue. 525 if (!E->isGLValue()) return Owned(E); 526 527 QualType T = E->getType(); 528 assert(!T.isNull() && "r-value conversion on typeless expression?"); 529 530 // We don't want to throw lvalue-to-rvalue casts on top of 531 // expressions of certain types in C++. 532 if (getLangOpts().CPlusPlus && 533 (E->getType() == Context.OverloadTy || 534 T->isDependentType() || 535 T->isRecordType())) 536 return Owned(E); 537 538 // The C standard is actually really unclear on this point, and 539 // DR106 tells us what the result should be but not why. It's 540 // generally best to say that void types just doesn't undergo 541 // lvalue-to-rvalue at all. Note that expressions of unqualified 542 // 'void' type are never l-values, but qualified void can be. 543 if (T->isVoidType()) 544 return Owned(E); 545 546 // OpenCL usually rejects direct accesses to values of 'half' type. 547 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 548 T->isHalfType()) { 549 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 550 << 0 << T; 551 return ExprError(); 552 } 553 554 CheckForNullPointerDereference(*this, E); 555 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 556 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 557 &Context.Idents.get("object_getClass"), 558 SourceLocation(), LookupOrdinaryName); 559 if (ObjectGetClass) 560 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 561 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 562 FixItHint::CreateReplacement( 563 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 564 else 565 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 566 } 567 else if (const ObjCIvarRefExpr *OIRE = 568 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 569 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 570 571 // C++ [conv.lval]p1: 572 // [...] If T is a non-class type, the type of the prvalue is the 573 // cv-unqualified version of T. Otherwise, the type of the 574 // rvalue is T. 575 // 576 // C99 6.3.2.1p2: 577 // If the lvalue has qualified type, the value has the unqualified 578 // version of the type of the lvalue; otherwise, the value has the 579 // type of the lvalue. 580 if (T.hasQualifiers()) 581 T = T.getUnqualifiedType(); 582 583 UpdateMarkingForLValueToRValue(E); 584 585 // Loading a __weak object implicitly retains the value, so we need a cleanup to 586 // balance that. 587 if (getLangOpts().ObjCAutoRefCount && 588 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 589 ExprNeedsCleanups = true; 590 591 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 592 E, 0, VK_RValue)); 593 594 // C11 6.3.2.1p2: 595 // ... if the lvalue has atomic type, the value has the non-atomic version 596 // of the type of the lvalue ... 597 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 598 T = Atomic->getValueType().getUnqualifiedType(); 599 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 600 Res.get(), 0, VK_RValue)); 601 } 602 603 return Res; 604 } 605 606 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 607 ExprResult Res = DefaultFunctionArrayConversion(E); 608 if (Res.isInvalid()) 609 return ExprError(); 610 Res = DefaultLvalueConversion(Res.take()); 611 if (Res.isInvalid()) 612 return ExprError(); 613 return Res; 614 } 615 616 617 /// UsualUnaryConversions - Performs various conversions that are common to most 618 /// operators (C99 6.3). The conversions of array and function types are 619 /// sometimes suppressed. For example, the array->pointer conversion doesn't 620 /// apply if the array is an argument to the sizeof or address (&) operators. 621 /// In these instances, this routine should *not* be called. 622 ExprResult Sema::UsualUnaryConversions(Expr *E) { 623 // First, convert to an r-value. 624 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 625 if (Res.isInvalid()) 626 return ExprError(); 627 E = Res.take(); 628 629 QualType Ty = E->getType(); 630 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 631 632 // Half FP have to be promoted to float unless it is natively supported 633 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 634 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 635 636 // Try to perform integral promotions if the object has a theoretically 637 // promotable type. 638 if (Ty->isIntegralOrUnscopedEnumerationType()) { 639 // C99 6.3.1.1p2: 640 // 641 // The following may be used in an expression wherever an int or 642 // unsigned int may be used: 643 // - an object or expression with an integer type whose integer 644 // conversion rank is less than or equal to the rank of int 645 // and unsigned int. 646 // - A bit-field of type _Bool, int, signed int, or unsigned int. 647 // 648 // If an int can represent all values of the original type, the 649 // value is converted to an int; otherwise, it is converted to an 650 // unsigned int. These are called the integer promotions. All 651 // other types are unchanged by the integer promotions. 652 653 QualType PTy = Context.isPromotableBitField(E); 654 if (!PTy.isNull()) { 655 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 656 return Owned(E); 657 } 658 if (Ty->isPromotableIntegerType()) { 659 QualType PT = Context.getPromotedIntegerType(Ty); 660 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 661 return Owned(E); 662 } 663 } 664 return Owned(E); 665 } 666 667 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 668 /// do not have a prototype. Arguments that have type float or __fp16 669 /// are promoted to double. All other argument types are converted by 670 /// UsualUnaryConversions(). 671 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 672 QualType Ty = E->getType(); 673 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 674 675 ExprResult Res = UsualUnaryConversions(E); 676 if (Res.isInvalid()) 677 return ExprError(); 678 E = Res.take(); 679 680 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 681 // double. 682 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 683 if (BTy && (BTy->getKind() == BuiltinType::Half || 684 BTy->getKind() == BuiltinType::Float)) 685 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 686 687 // C++ performs lvalue-to-rvalue conversion as a default argument 688 // promotion, even on class types, but note: 689 // C++11 [conv.lval]p2: 690 // When an lvalue-to-rvalue conversion occurs in an unevaluated 691 // operand or a subexpression thereof the value contained in the 692 // referenced object is not accessed. Otherwise, if the glvalue 693 // has a class type, the conversion copy-initializes a temporary 694 // of type T from the glvalue and the result of the conversion 695 // is a prvalue for the temporary. 696 // FIXME: add some way to gate this entire thing for correctness in 697 // potentially potentially evaluated contexts. 698 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 699 ExprResult Temp = PerformCopyInitialization( 700 InitializedEntity::InitializeTemporary(E->getType()), 701 E->getExprLoc(), 702 Owned(E)); 703 if (Temp.isInvalid()) 704 return ExprError(); 705 E = Temp.get(); 706 } 707 708 return Owned(E); 709 } 710 711 /// Determine the degree of POD-ness for an expression. 712 /// Incomplete types are considered POD, since this check can be performed 713 /// when we're in an unevaluated context. 714 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 715 if (Ty->isIncompleteType()) { 716 if (Ty->isObjCObjectType()) 717 return VAK_Invalid; 718 return VAK_Valid; 719 } 720 721 if (Ty.isCXX98PODType(Context)) 722 return VAK_Valid; 723 724 // C++11 [expr.call]p7: 725 // Passing a potentially-evaluated argument of class type (Clause 9) 726 // having a non-trivial copy constructor, a non-trivial move constructor, 727 // or a non-trivial destructor, with no corresponding parameter, 728 // is conditionally-supported with implementation-defined semantics. 729 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 730 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 731 if (!Record->hasNonTrivialCopyConstructor() && 732 !Record->hasNonTrivialMoveConstructor() && 733 !Record->hasNonTrivialDestructor()) 734 return VAK_ValidInCXX11; 735 736 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 737 return VAK_Valid; 738 return VAK_Invalid; 739 } 740 741 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) { 742 // Don't allow one to pass an Objective-C interface to a vararg. 743 const QualType & Ty = E->getType(); 744 745 // Complain about passing non-POD types through varargs. 746 switch (isValidVarArgType(Ty)) { 747 case VAK_Valid: 748 break; 749 case VAK_ValidInCXX11: 750 DiagRuntimeBehavior(E->getLocStart(), 0, 751 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 752 << E->getType() << CT); 753 break; 754 case VAK_Invalid: { 755 if (Ty->isObjCObjectType()) 756 return DiagRuntimeBehavior(E->getLocStart(), 0, 757 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 758 << Ty << CT); 759 760 return DiagRuntimeBehavior(E->getLocStart(), 0, 761 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 762 << getLangOpts().CPlusPlus11 << Ty << CT); 763 } 764 } 765 // c++ rules are enforced elsewhere. 766 return false; 767 } 768 769 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 770 /// will create a trap if the resulting type is not a POD type. 771 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 772 FunctionDecl *FDecl) { 773 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 774 // Strip the unbridged-cast placeholder expression off, if applicable. 775 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 776 (CT == VariadicMethod || 777 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 778 E = stripARCUnbridgedCast(E); 779 780 // Otherwise, do normal placeholder checking. 781 } else { 782 ExprResult ExprRes = CheckPlaceholderExpr(E); 783 if (ExprRes.isInvalid()) 784 return ExprError(); 785 E = ExprRes.take(); 786 } 787 } 788 789 ExprResult ExprRes = DefaultArgumentPromotion(E); 790 if (ExprRes.isInvalid()) 791 return ExprError(); 792 E = ExprRes.take(); 793 794 // Diagnostics regarding non-POD argument types are 795 // emitted along with format string checking in Sema::CheckFunctionCall(). 796 if (isValidVarArgType(E->getType()) == VAK_Invalid) { 797 // Turn this into a trap. 798 CXXScopeSpec SS; 799 SourceLocation TemplateKWLoc; 800 UnqualifiedId Name; 801 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 802 E->getLocStart()); 803 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 804 Name, true, false); 805 if (TrapFn.isInvalid()) 806 return ExprError(); 807 808 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 809 E->getLocStart(), MultiExprArg(), 810 E->getLocEnd()); 811 if (Call.isInvalid()) 812 return ExprError(); 813 814 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 815 Call.get(), E); 816 if (Comma.isInvalid()) 817 return ExprError(); 818 return Comma.get(); 819 } 820 821 if (!getLangOpts().CPlusPlus && 822 RequireCompleteType(E->getExprLoc(), E->getType(), 823 diag::err_call_incomplete_argument)) 824 return ExprError(); 825 826 return Owned(E); 827 } 828 829 /// \brief Converts an integer to complex float type. Helper function of 830 /// UsualArithmeticConversions() 831 /// 832 /// \return false if the integer expression is an integer type and is 833 /// successfully converted to the complex type. 834 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 835 ExprResult &ComplexExpr, 836 QualType IntTy, 837 QualType ComplexTy, 838 bool SkipCast) { 839 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 840 if (SkipCast) return false; 841 if (IntTy->isIntegerType()) { 842 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 843 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 844 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 845 CK_FloatingRealToComplex); 846 } else { 847 assert(IntTy->isComplexIntegerType()); 848 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 849 CK_IntegralComplexToFloatingComplex); 850 } 851 return false; 852 } 853 854 /// \brief Takes two complex float types and converts them to the same type. 855 /// Helper function of UsualArithmeticConversions() 856 static QualType 857 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 858 ExprResult &RHS, QualType LHSType, 859 QualType RHSType, 860 bool IsCompAssign) { 861 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 862 863 if (order < 0) { 864 // _Complex float -> _Complex double 865 if (!IsCompAssign) 866 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 867 return RHSType; 868 } 869 if (order > 0) 870 // _Complex float -> _Complex double 871 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 872 return LHSType; 873 } 874 875 /// \brief Converts otherExpr to complex float and promotes complexExpr if 876 /// necessary. Helper function of UsualArithmeticConversions() 877 static QualType handleOtherComplexFloatConversion(Sema &S, 878 ExprResult &ComplexExpr, 879 ExprResult &OtherExpr, 880 QualType ComplexTy, 881 QualType OtherTy, 882 bool ConvertComplexExpr, 883 bool ConvertOtherExpr) { 884 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 885 886 // If just the complexExpr is complex, the otherExpr needs to be converted, 887 // and the complexExpr might need to be promoted. 888 if (order > 0) { // complexExpr is wider 889 // float -> _Complex double 890 if (ConvertOtherExpr) { 891 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 892 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 893 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 894 CK_FloatingRealToComplex); 895 } 896 return ComplexTy; 897 } 898 899 // otherTy is at least as wide. Find its corresponding complex type. 900 QualType result = (order == 0 ? ComplexTy : 901 S.Context.getComplexType(OtherTy)); 902 903 // double -> _Complex double 904 if (ConvertOtherExpr) 905 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 906 CK_FloatingRealToComplex); 907 908 // _Complex float -> _Complex double 909 if (ConvertComplexExpr && order < 0) 910 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 911 CK_FloatingComplexCast); 912 913 return result; 914 } 915 916 /// \brief Handle arithmetic conversion with complex types. Helper function of 917 /// UsualArithmeticConversions() 918 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 919 ExprResult &RHS, QualType LHSType, 920 QualType RHSType, 921 bool IsCompAssign) { 922 // if we have an integer operand, the result is the complex type. 923 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 924 /*skipCast*/false)) 925 return LHSType; 926 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 927 /*skipCast*/IsCompAssign)) 928 return RHSType; 929 930 // This handles complex/complex, complex/float, or float/complex. 931 // When both operands are complex, the shorter operand is converted to the 932 // type of the longer, and that is the type of the result. This corresponds 933 // to what is done when combining two real floating-point operands. 934 // The fun begins when size promotion occur across type domains. 935 // From H&S 6.3.4: When one operand is complex and the other is a real 936 // floating-point type, the less precise type is converted, within it's 937 // real or complex domain, to the precision of the other type. For example, 938 // when combining a "long double" with a "double _Complex", the 939 // "double _Complex" is promoted to "long double _Complex". 940 941 bool LHSComplexFloat = LHSType->isComplexType(); 942 bool RHSComplexFloat = RHSType->isComplexType(); 943 944 // If both are complex, just cast to the more precise type. 945 if (LHSComplexFloat && RHSComplexFloat) 946 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 947 LHSType, RHSType, 948 IsCompAssign); 949 950 // If only one operand is complex, promote it if necessary and convert the 951 // other operand to complex. 952 if (LHSComplexFloat) 953 return handleOtherComplexFloatConversion( 954 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 955 /*convertOtherExpr*/ true); 956 957 assert(RHSComplexFloat); 958 return handleOtherComplexFloatConversion( 959 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 960 /*convertOtherExpr*/ !IsCompAssign); 961 } 962 963 /// \brief Hande arithmetic conversion from integer to float. Helper function 964 /// of UsualArithmeticConversions() 965 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 966 ExprResult &IntExpr, 967 QualType FloatTy, QualType IntTy, 968 bool ConvertFloat, bool ConvertInt) { 969 if (IntTy->isIntegerType()) { 970 if (ConvertInt) 971 // Convert intExpr to the lhs floating point type. 972 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 973 CK_IntegralToFloating); 974 return FloatTy; 975 } 976 977 // Convert both sides to the appropriate complex float. 978 assert(IntTy->isComplexIntegerType()); 979 QualType result = S.Context.getComplexType(FloatTy); 980 981 // _Complex int -> _Complex float 982 if (ConvertInt) 983 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 984 CK_IntegralComplexToFloatingComplex); 985 986 // float -> _Complex float 987 if (ConvertFloat) 988 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 989 CK_FloatingRealToComplex); 990 991 return result; 992 } 993 994 /// \brief Handle arithmethic conversion with floating point types. Helper 995 /// function of UsualArithmeticConversions() 996 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 997 ExprResult &RHS, QualType LHSType, 998 QualType RHSType, bool IsCompAssign) { 999 bool LHSFloat = LHSType->isRealFloatingType(); 1000 bool RHSFloat = RHSType->isRealFloatingType(); 1001 1002 // If we have two real floating types, convert the smaller operand 1003 // to the bigger result. 1004 if (LHSFloat && RHSFloat) { 1005 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1006 if (order > 0) { 1007 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1008 return LHSType; 1009 } 1010 1011 assert(order < 0 && "illegal float comparison"); 1012 if (!IsCompAssign) 1013 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1014 return RHSType; 1015 } 1016 1017 if (LHSFloat) 1018 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1019 /*convertFloat=*/!IsCompAssign, 1020 /*convertInt=*/ true); 1021 assert(RHSFloat); 1022 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1023 /*convertInt=*/ true, 1024 /*convertFloat=*/!IsCompAssign); 1025 } 1026 1027 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1028 1029 namespace { 1030 /// These helper callbacks are placed in an anonymous namespace to 1031 /// permit their use as function template parameters. 1032 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1033 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1034 } 1035 1036 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1037 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1038 CK_IntegralComplexCast); 1039 } 1040 } 1041 1042 /// \brief Handle integer arithmetic conversions. Helper function of 1043 /// UsualArithmeticConversions() 1044 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1045 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1046 ExprResult &RHS, QualType LHSType, 1047 QualType RHSType, bool IsCompAssign) { 1048 // The rules for this case are in C99 6.3.1.8 1049 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1050 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1051 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1052 if (LHSSigned == RHSSigned) { 1053 // Same signedness; use the higher-ranked type 1054 if (order >= 0) { 1055 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1056 return LHSType; 1057 } else if (!IsCompAssign) 1058 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1059 return RHSType; 1060 } else if (order != (LHSSigned ? 1 : -1)) { 1061 // The unsigned type has greater than or equal rank to the 1062 // signed type, so use the unsigned type 1063 if (RHSSigned) { 1064 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1065 return LHSType; 1066 } else if (!IsCompAssign) 1067 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1068 return RHSType; 1069 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1070 // The two types are different widths; if we are here, that 1071 // means the signed type is larger than the unsigned type, so 1072 // use the signed type. 1073 if (LHSSigned) { 1074 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1075 return LHSType; 1076 } else if (!IsCompAssign) 1077 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1078 return RHSType; 1079 } else { 1080 // The signed type is higher-ranked than the unsigned type, 1081 // but isn't actually any bigger (like unsigned int and long 1082 // on most 32-bit systems). Use the unsigned type corresponding 1083 // to the signed type. 1084 QualType result = 1085 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1086 RHS = (*doRHSCast)(S, RHS.take(), result); 1087 if (!IsCompAssign) 1088 LHS = (*doLHSCast)(S, LHS.take(), result); 1089 return result; 1090 } 1091 } 1092 1093 /// \brief Handle conversions with GCC complex int extension. Helper function 1094 /// of UsualArithmeticConversions() 1095 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1096 ExprResult &RHS, QualType LHSType, 1097 QualType RHSType, 1098 bool IsCompAssign) { 1099 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1100 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1101 1102 if (LHSComplexInt && RHSComplexInt) { 1103 QualType LHSEltType = LHSComplexInt->getElementType(); 1104 QualType RHSEltType = RHSComplexInt->getElementType(); 1105 QualType ScalarType = 1106 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1107 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1108 1109 return S.Context.getComplexType(ScalarType); 1110 } 1111 1112 if (LHSComplexInt) { 1113 QualType LHSEltType = LHSComplexInt->getElementType(); 1114 QualType ScalarType = 1115 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1116 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1117 QualType ComplexType = S.Context.getComplexType(ScalarType); 1118 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1119 CK_IntegralRealToComplex); 1120 1121 return ComplexType; 1122 } 1123 1124 assert(RHSComplexInt); 1125 1126 QualType RHSEltType = RHSComplexInt->getElementType(); 1127 QualType ScalarType = 1128 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1129 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1130 QualType ComplexType = S.Context.getComplexType(ScalarType); 1131 1132 if (!IsCompAssign) 1133 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1134 CK_IntegralRealToComplex); 1135 return ComplexType; 1136 } 1137 1138 /// UsualArithmeticConversions - Performs various conversions that are common to 1139 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1140 /// routine returns the first non-arithmetic type found. The client is 1141 /// responsible for emitting appropriate error diagnostics. 1142 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1143 bool IsCompAssign) { 1144 if (!IsCompAssign) { 1145 LHS = UsualUnaryConversions(LHS.take()); 1146 if (LHS.isInvalid()) 1147 return QualType(); 1148 } 1149 1150 RHS = UsualUnaryConversions(RHS.take()); 1151 if (RHS.isInvalid()) 1152 return QualType(); 1153 1154 // For conversion purposes, we ignore any qualifiers. 1155 // For example, "const float" and "float" are equivalent. 1156 QualType LHSType = 1157 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1158 QualType RHSType = 1159 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1160 1161 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1162 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1163 LHSType = AtomicLHS->getValueType(); 1164 1165 // If both types are identical, no conversion is needed. 1166 if (LHSType == RHSType) 1167 return LHSType; 1168 1169 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1170 // The caller can deal with this (e.g. pointer + int). 1171 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1172 return QualType(); 1173 1174 // Apply unary and bitfield promotions to the LHS's type. 1175 QualType LHSUnpromotedType = LHSType; 1176 if (LHSType->isPromotableIntegerType()) 1177 LHSType = Context.getPromotedIntegerType(LHSType); 1178 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1179 if (!LHSBitfieldPromoteTy.isNull()) 1180 LHSType = LHSBitfieldPromoteTy; 1181 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1182 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1183 1184 // If both types are identical, no conversion is needed. 1185 if (LHSType == RHSType) 1186 return LHSType; 1187 1188 // At this point, we have two different arithmetic types. 1189 1190 // Handle complex types first (C99 6.3.1.8p1). 1191 if (LHSType->isComplexType() || RHSType->isComplexType()) 1192 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1193 IsCompAssign); 1194 1195 // Now handle "real" floating types (i.e. float, double, long double). 1196 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1197 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1198 IsCompAssign); 1199 1200 // Handle GCC complex int extension. 1201 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1202 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1203 IsCompAssign); 1204 1205 // Finally, we have two differing integer types. 1206 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1207 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1208 } 1209 1210 1211 //===----------------------------------------------------------------------===// 1212 // Semantic Analysis for various Expression Types 1213 //===----------------------------------------------------------------------===// 1214 1215 1216 ExprResult 1217 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1218 SourceLocation DefaultLoc, 1219 SourceLocation RParenLoc, 1220 Expr *ControllingExpr, 1221 MultiTypeArg ArgTypes, 1222 MultiExprArg ArgExprs) { 1223 unsigned NumAssocs = ArgTypes.size(); 1224 assert(NumAssocs == ArgExprs.size()); 1225 1226 ParsedType *ParsedTypes = ArgTypes.data(); 1227 Expr **Exprs = ArgExprs.data(); 1228 1229 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1230 for (unsigned i = 0; i < NumAssocs; ++i) { 1231 if (ParsedTypes[i]) 1232 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 1233 else 1234 Types[i] = 0; 1235 } 1236 1237 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1238 ControllingExpr, Types, Exprs, 1239 NumAssocs); 1240 delete [] Types; 1241 return ER; 1242 } 1243 1244 ExprResult 1245 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1246 SourceLocation DefaultLoc, 1247 SourceLocation RParenLoc, 1248 Expr *ControllingExpr, 1249 TypeSourceInfo **Types, 1250 Expr **Exprs, 1251 unsigned NumAssocs) { 1252 if (ControllingExpr->getType()->isPlaceholderType()) { 1253 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1254 if (result.isInvalid()) return ExprError(); 1255 ControllingExpr = result.take(); 1256 } 1257 1258 bool TypeErrorFound = false, 1259 IsResultDependent = ControllingExpr->isTypeDependent(), 1260 ContainsUnexpandedParameterPack 1261 = ControllingExpr->containsUnexpandedParameterPack(); 1262 1263 for (unsigned i = 0; i < NumAssocs; ++i) { 1264 if (Exprs[i]->containsUnexpandedParameterPack()) 1265 ContainsUnexpandedParameterPack = true; 1266 1267 if (Types[i]) { 1268 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1269 ContainsUnexpandedParameterPack = true; 1270 1271 if (Types[i]->getType()->isDependentType()) { 1272 IsResultDependent = true; 1273 } else { 1274 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1275 // complete object type other than a variably modified type." 1276 unsigned D = 0; 1277 if (Types[i]->getType()->isIncompleteType()) 1278 D = diag::err_assoc_type_incomplete; 1279 else if (!Types[i]->getType()->isObjectType()) 1280 D = diag::err_assoc_type_nonobject; 1281 else if (Types[i]->getType()->isVariablyModifiedType()) 1282 D = diag::err_assoc_type_variably_modified; 1283 1284 if (D != 0) { 1285 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1286 << Types[i]->getTypeLoc().getSourceRange() 1287 << Types[i]->getType(); 1288 TypeErrorFound = true; 1289 } 1290 1291 // C11 6.5.1.1p2 "No two generic associations in the same generic 1292 // selection shall specify compatible types." 1293 for (unsigned j = i+1; j < NumAssocs; ++j) 1294 if (Types[j] && !Types[j]->getType()->isDependentType() && 1295 Context.typesAreCompatible(Types[i]->getType(), 1296 Types[j]->getType())) { 1297 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1298 diag::err_assoc_compatible_types) 1299 << Types[j]->getTypeLoc().getSourceRange() 1300 << Types[j]->getType() 1301 << Types[i]->getType(); 1302 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1303 diag::note_compat_assoc) 1304 << Types[i]->getTypeLoc().getSourceRange() 1305 << Types[i]->getType(); 1306 TypeErrorFound = true; 1307 } 1308 } 1309 } 1310 } 1311 if (TypeErrorFound) 1312 return ExprError(); 1313 1314 // If we determined that the generic selection is result-dependent, don't 1315 // try to compute the result expression. 1316 if (IsResultDependent) 1317 return Owned(new (Context) GenericSelectionExpr( 1318 Context, KeyLoc, ControllingExpr, 1319 llvm::makeArrayRef(Types, NumAssocs), 1320 llvm::makeArrayRef(Exprs, NumAssocs), 1321 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1322 1323 SmallVector<unsigned, 1> CompatIndices; 1324 unsigned DefaultIndex = -1U; 1325 for (unsigned i = 0; i < NumAssocs; ++i) { 1326 if (!Types[i]) 1327 DefaultIndex = i; 1328 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1329 Types[i]->getType())) 1330 CompatIndices.push_back(i); 1331 } 1332 1333 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1334 // type compatible with at most one of the types named in its generic 1335 // association list." 1336 if (CompatIndices.size() > 1) { 1337 // We strip parens here because the controlling expression is typically 1338 // parenthesized in macro definitions. 1339 ControllingExpr = ControllingExpr->IgnoreParens(); 1340 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1341 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1342 << (unsigned) CompatIndices.size(); 1343 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1344 E = CompatIndices.end(); I != E; ++I) { 1345 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1346 diag::note_compat_assoc) 1347 << Types[*I]->getTypeLoc().getSourceRange() 1348 << Types[*I]->getType(); 1349 } 1350 return ExprError(); 1351 } 1352 1353 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1354 // its controlling expression shall have type compatible with exactly one of 1355 // the types named in its generic association list." 1356 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1357 // We strip parens here because the controlling expression is typically 1358 // parenthesized in macro definitions. 1359 ControllingExpr = ControllingExpr->IgnoreParens(); 1360 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1361 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1362 return ExprError(); 1363 } 1364 1365 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1366 // type name that is compatible with the type of the controlling expression, 1367 // then the result expression of the generic selection is the expression 1368 // in that generic association. Otherwise, the result expression of the 1369 // generic selection is the expression in the default generic association." 1370 unsigned ResultIndex = 1371 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1372 1373 return Owned(new (Context) GenericSelectionExpr( 1374 Context, KeyLoc, ControllingExpr, 1375 llvm::makeArrayRef(Types, NumAssocs), 1376 llvm::makeArrayRef(Exprs, NumAssocs), 1377 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1378 ResultIndex)); 1379 } 1380 1381 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1382 /// location of the token and the offset of the ud-suffix within it. 1383 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1384 unsigned Offset) { 1385 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1386 S.getLangOpts()); 1387 } 1388 1389 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1390 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1391 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1392 IdentifierInfo *UDSuffix, 1393 SourceLocation UDSuffixLoc, 1394 ArrayRef<Expr*> Args, 1395 SourceLocation LitEndLoc) { 1396 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1397 1398 QualType ArgTy[2]; 1399 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1400 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1401 if (ArgTy[ArgIdx]->isArrayType()) 1402 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1403 } 1404 1405 DeclarationName OpName = 1406 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1407 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1408 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1409 1410 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1411 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1412 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1413 return ExprError(); 1414 1415 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1416 } 1417 1418 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1419 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1420 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1421 /// multiple tokens. However, the common case is that StringToks points to one 1422 /// string. 1423 /// 1424 ExprResult 1425 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1426 Scope *UDLScope) { 1427 assert(NumStringToks && "Must have at least one string!"); 1428 1429 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1430 if (Literal.hadError) 1431 return ExprError(); 1432 1433 SmallVector<SourceLocation, 4> StringTokLocs; 1434 for (unsigned i = 0; i != NumStringToks; ++i) 1435 StringTokLocs.push_back(StringToks[i].getLocation()); 1436 1437 QualType StrTy = Context.CharTy; 1438 if (Literal.isWide()) 1439 StrTy = Context.getWCharType(); 1440 else if (Literal.isUTF16()) 1441 StrTy = Context.Char16Ty; 1442 else if (Literal.isUTF32()) 1443 StrTy = Context.Char32Ty; 1444 else if (Literal.isPascal()) 1445 StrTy = Context.UnsignedCharTy; 1446 1447 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1448 if (Literal.isWide()) 1449 Kind = StringLiteral::Wide; 1450 else if (Literal.isUTF8()) 1451 Kind = StringLiteral::UTF8; 1452 else if (Literal.isUTF16()) 1453 Kind = StringLiteral::UTF16; 1454 else if (Literal.isUTF32()) 1455 Kind = StringLiteral::UTF32; 1456 1457 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1458 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1459 StrTy.addConst(); 1460 1461 // Get an array type for the string, according to C99 6.4.5. This includes 1462 // the nul terminator character as well as the string length for pascal 1463 // strings. 1464 StrTy = Context.getConstantArrayType(StrTy, 1465 llvm::APInt(32, Literal.GetNumStringChars()+1), 1466 ArrayType::Normal, 0); 1467 1468 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1469 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1470 Kind, Literal.Pascal, StrTy, 1471 &StringTokLocs[0], 1472 StringTokLocs.size()); 1473 if (Literal.getUDSuffix().empty()) 1474 return Owned(Lit); 1475 1476 // We're building a user-defined literal. 1477 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1478 SourceLocation UDSuffixLoc = 1479 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1480 Literal.getUDSuffixOffset()); 1481 1482 // Make sure we're allowed user-defined literals here. 1483 if (!UDLScope) 1484 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1485 1486 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1487 // operator "" X (str, len) 1488 QualType SizeType = Context.getSizeType(); 1489 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1490 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1491 StringTokLocs[0]); 1492 Expr *Args[] = { Lit, LenArg }; 1493 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1494 Args, StringTokLocs.back()); 1495 } 1496 1497 ExprResult 1498 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1499 SourceLocation Loc, 1500 const CXXScopeSpec *SS) { 1501 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1502 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1503 } 1504 1505 /// BuildDeclRefExpr - Build an expression that references a 1506 /// declaration that does not require a closure capture. 1507 ExprResult 1508 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1509 const DeclarationNameInfo &NameInfo, 1510 const CXXScopeSpec *SS, NamedDecl *FoundD) { 1511 if (getLangOpts().CUDA) 1512 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1513 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1514 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1515 CalleeTarget = IdentifyCUDATarget(Callee); 1516 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1517 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1518 << CalleeTarget << D->getIdentifier() << CallerTarget; 1519 Diag(D->getLocation(), diag::note_previous_decl) 1520 << D->getIdentifier(); 1521 return ExprError(); 1522 } 1523 } 1524 1525 bool refersToEnclosingScope = 1526 (CurContext != D->getDeclContext() && 1527 D->getDeclContext()->isFunctionOrMethod()); 1528 1529 DeclRefExpr *E = DeclRefExpr::Create(Context, 1530 SS ? SS->getWithLocInContext(Context) 1531 : NestedNameSpecifierLoc(), 1532 SourceLocation(), 1533 D, refersToEnclosingScope, 1534 NameInfo, Ty, VK, FoundD); 1535 1536 MarkDeclRefReferenced(E); 1537 1538 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1539 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1540 DiagnosticsEngine::Level Level = 1541 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1542 E->getLocStart()); 1543 if (Level != DiagnosticsEngine::Ignored) 1544 getCurFunction()->recordUseOfWeak(E); 1545 } 1546 1547 // Just in case we're building an illegal pointer-to-member. 1548 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1549 if (FD && FD->isBitField()) 1550 E->setObjectKind(OK_BitField); 1551 1552 return Owned(E); 1553 } 1554 1555 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1556 /// possibly a list of template arguments. 1557 /// 1558 /// If this produces template arguments, it is permitted to call 1559 /// DecomposeTemplateName. 1560 /// 1561 /// This actually loses a lot of source location information for 1562 /// non-standard name kinds; we should consider preserving that in 1563 /// some way. 1564 void 1565 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1566 TemplateArgumentListInfo &Buffer, 1567 DeclarationNameInfo &NameInfo, 1568 const TemplateArgumentListInfo *&TemplateArgs) { 1569 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1570 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1571 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1572 1573 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1574 Id.TemplateId->NumArgs); 1575 translateTemplateArguments(TemplateArgsPtr, Buffer); 1576 1577 TemplateName TName = Id.TemplateId->Template.get(); 1578 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1579 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1580 TemplateArgs = &Buffer; 1581 } else { 1582 NameInfo = GetNameFromUnqualifiedId(Id); 1583 TemplateArgs = 0; 1584 } 1585 } 1586 1587 /// Diagnose an empty lookup. 1588 /// 1589 /// \return false if new lookup candidates were found 1590 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1591 CorrectionCandidateCallback &CCC, 1592 TemplateArgumentListInfo *ExplicitTemplateArgs, 1593 llvm::ArrayRef<Expr *> Args) { 1594 DeclarationName Name = R.getLookupName(); 1595 1596 unsigned diagnostic = diag::err_undeclared_var_use; 1597 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1598 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1599 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1600 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1601 diagnostic = diag::err_undeclared_use; 1602 diagnostic_suggest = diag::err_undeclared_use_suggest; 1603 } 1604 1605 // If the original lookup was an unqualified lookup, fake an 1606 // unqualified lookup. This is useful when (for example) the 1607 // original lookup would not have found something because it was a 1608 // dependent name. 1609 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1610 ? CurContext : 0; 1611 while (DC) { 1612 if (isa<CXXRecordDecl>(DC)) { 1613 LookupQualifiedName(R, DC); 1614 1615 if (!R.empty()) { 1616 // Don't give errors about ambiguities in this lookup. 1617 R.suppressDiagnostics(); 1618 1619 // During a default argument instantiation the CurContext points 1620 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1621 // function parameter list, hence add an explicit check. 1622 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1623 ActiveTemplateInstantiations.back().Kind == 1624 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1625 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1626 bool isInstance = CurMethod && 1627 CurMethod->isInstance() && 1628 DC == CurMethod->getParent() && !isDefaultArgument; 1629 1630 1631 // Give a code modification hint to insert 'this->'. 1632 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1633 // Actually quite difficult! 1634 if (getLangOpts().MicrosoftMode) 1635 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1636 if (isInstance) { 1637 Diag(R.getNameLoc(), diagnostic) << Name 1638 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1639 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1640 CallsUndergoingInstantiation.back()->getCallee()); 1641 1642 CXXMethodDecl *DepMethod; 1643 if (CurMethod->isDependentContext()) 1644 DepMethod = CurMethod; 1645 else if (CurMethod->getTemplatedKind() == 1646 FunctionDecl::TK_FunctionTemplateSpecialization) 1647 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1648 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1649 else 1650 DepMethod = cast<CXXMethodDecl>( 1651 CurMethod->getInstantiatedFromMemberFunction()); 1652 assert(DepMethod && "No template pattern found"); 1653 1654 QualType DepThisType = DepMethod->getThisType(Context); 1655 CheckCXXThisCapture(R.getNameLoc()); 1656 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1657 R.getNameLoc(), DepThisType, false); 1658 TemplateArgumentListInfo TList; 1659 if (ULE->hasExplicitTemplateArgs()) 1660 ULE->copyTemplateArgumentsInto(TList); 1661 1662 CXXScopeSpec SS; 1663 SS.Adopt(ULE->getQualifierLoc()); 1664 CXXDependentScopeMemberExpr *DepExpr = 1665 CXXDependentScopeMemberExpr::Create( 1666 Context, DepThis, DepThisType, true, SourceLocation(), 1667 SS.getWithLocInContext(Context), 1668 ULE->getTemplateKeywordLoc(), 0, 1669 R.getLookupNameInfo(), 1670 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1671 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1672 } else { 1673 Diag(R.getNameLoc(), diagnostic) << Name; 1674 } 1675 1676 // Do we really want to note all of these? 1677 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1678 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1679 1680 // Return true if we are inside a default argument instantiation 1681 // and the found name refers to an instance member function, otherwise 1682 // the function calling DiagnoseEmptyLookup will try to create an 1683 // implicit member call and this is wrong for default argument. 1684 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1685 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1686 return true; 1687 } 1688 1689 // Tell the callee to try to recover. 1690 return false; 1691 } 1692 1693 R.clear(); 1694 } 1695 1696 // In Microsoft mode, if we are performing lookup from within a friend 1697 // function definition declared at class scope then we must set 1698 // DC to the lexical parent to be able to search into the parent 1699 // class. 1700 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1701 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1702 DC->getLexicalParent()->isRecord()) 1703 DC = DC->getLexicalParent(); 1704 else 1705 DC = DC->getParent(); 1706 } 1707 1708 // We didn't find anything, so try to correct for a typo. 1709 TypoCorrection Corrected; 1710 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1711 S, &SS, CCC))) { 1712 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1713 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1714 R.setLookupName(Corrected.getCorrection()); 1715 1716 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1717 if (Corrected.isOverloaded()) { 1718 OverloadCandidateSet OCS(R.getNameLoc()); 1719 OverloadCandidateSet::iterator Best; 1720 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1721 CDEnd = Corrected.end(); 1722 CD != CDEnd; ++CD) { 1723 if (FunctionTemplateDecl *FTD = 1724 dyn_cast<FunctionTemplateDecl>(*CD)) 1725 AddTemplateOverloadCandidate( 1726 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1727 Args, OCS); 1728 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1729 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1730 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1731 Args, OCS); 1732 } 1733 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1734 case OR_Success: 1735 ND = Best->Function; 1736 break; 1737 default: 1738 break; 1739 } 1740 } 1741 R.addDecl(ND); 1742 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1743 if (SS.isEmpty()) 1744 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1745 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1746 else 1747 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1748 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1749 << SS.getRange() 1750 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1751 CorrectedStr); 1752 1753 unsigned diag = isa<ImplicitParamDecl>(ND) 1754 ? diag::note_implicit_param_decl 1755 : diag::note_previous_decl; 1756 1757 Diag(ND->getLocation(), diag) 1758 << CorrectedQuotedStr; 1759 1760 // Tell the callee to try to recover. 1761 return false; 1762 } 1763 1764 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1765 // FIXME: If we ended up with a typo for a type name or 1766 // Objective-C class name, we're in trouble because the parser 1767 // is in the wrong place to recover. Suggest the typo 1768 // correction, but don't make it a fix-it since we're not going 1769 // to recover well anyway. 1770 if (SS.isEmpty()) 1771 Diag(R.getNameLoc(), diagnostic_suggest) 1772 << Name << CorrectedQuotedStr; 1773 else 1774 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1775 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1776 << SS.getRange(); 1777 1778 // Don't try to recover; it won't work. 1779 return true; 1780 } 1781 } else { 1782 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1783 // because we aren't able to recover. 1784 if (SS.isEmpty()) 1785 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1786 else 1787 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1788 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1789 << SS.getRange(); 1790 return true; 1791 } 1792 } 1793 R.clear(); 1794 1795 // Emit a special diagnostic for failed member lookups. 1796 // FIXME: computing the declaration context might fail here (?) 1797 if (!SS.isEmpty()) { 1798 Diag(R.getNameLoc(), diag::err_no_member) 1799 << Name << computeDeclContext(SS, false) 1800 << SS.getRange(); 1801 return true; 1802 } 1803 1804 // Give up, we can't recover. 1805 Diag(R.getNameLoc(), diagnostic) << Name; 1806 return true; 1807 } 1808 1809 ExprResult Sema::ActOnIdExpression(Scope *S, 1810 CXXScopeSpec &SS, 1811 SourceLocation TemplateKWLoc, 1812 UnqualifiedId &Id, 1813 bool HasTrailingLParen, 1814 bool IsAddressOfOperand, 1815 CorrectionCandidateCallback *CCC) { 1816 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1817 "cannot be direct & operand and have a trailing lparen"); 1818 1819 if (SS.isInvalid()) 1820 return ExprError(); 1821 1822 TemplateArgumentListInfo TemplateArgsBuffer; 1823 1824 // Decompose the UnqualifiedId into the following data. 1825 DeclarationNameInfo NameInfo; 1826 const TemplateArgumentListInfo *TemplateArgs; 1827 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1828 1829 DeclarationName Name = NameInfo.getName(); 1830 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1831 SourceLocation NameLoc = NameInfo.getLoc(); 1832 1833 // C++ [temp.dep.expr]p3: 1834 // An id-expression is type-dependent if it contains: 1835 // -- an identifier that was declared with a dependent type, 1836 // (note: handled after lookup) 1837 // -- a template-id that is dependent, 1838 // (note: handled in BuildTemplateIdExpr) 1839 // -- a conversion-function-id that specifies a dependent type, 1840 // -- a nested-name-specifier that contains a class-name that 1841 // names a dependent type. 1842 // Determine whether this is a member of an unknown specialization; 1843 // we need to handle these differently. 1844 bool DependentID = false; 1845 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1846 Name.getCXXNameType()->isDependentType()) { 1847 DependentID = true; 1848 } else if (SS.isSet()) { 1849 if (DeclContext *DC = computeDeclContext(SS, false)) { 1850 if (RequireCompleteDeclContext(SS, DC)) 1851 return ExprError(); 1852 } else { 1853 DependentID = true; 1854 } 1855 } 1856 1857 if (DependentID) 1858 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1859 IsAddressOfOperand, TemplateArgs); 1860 1861 // Perform the required lookup. 1862 LookupResult R(*this, NameInfo, 1863 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1864 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1865 if (TemplateArgs) { 1866 // Lookup the template name again to correctly establish the context in 1867 // which it was found. This is really unfortunate as we already did the 1868 // lookup to determine that it was a template name in the first place. If 1869 // this becomes a performance hit, we can work harder to preserve those 1870 // results until we get here but it's likely not worth it. 1871 bool MemberOfUnknownSpecialization; 1872 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1873 MemberOfUnknownSpecialization); 1874 1875 if (MemberOfUnknownSpecialization || 1876 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1877 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1878 IsAddressOfOperand, TemplateArgs); 1879 } else { 1880 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1881 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1882 1883 // If the result might be in a dependent base class, this is a dependent 1884 // id-expression. 1885 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1886 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1887 IsAddressOfOperand, TemplateArgs); 1888 1889 // If this reference is in an Objective-C method, then we need to do 1890 // some special Objective-C lookup, too. 1891 if (IvarLookupFollowUp) { 1892 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1893 if (E.isInvalid()) 1894 return ExprError(); 1895 1896 if (Expr *Ex = E.takeAs<Expr>()) 1897 return Owned(Ex); 1898 } 1899 } 1900 1901 if (R.isAmbiguous()) 1902 return ExprError(); 1903 1904 // Determine whether this name might be a candidate for 1905 // argument-dependent lookup. 1906 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1907 1908 if (R.empty() && !ADL) { 1909 // Otherwise, this could be an implicitly declared function reference (legal 1910 // in C90, extension in C99, forbidden in C++). 1911 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1912 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1913 if (D) R.addDecl(D); 1914 } 1915 1916 // If this name wasn't predeclared and if this is not a function 1917 // call, diagnose the problem. 1918 if (R.empty()) { 1919 1920 // In Microsoft mode, if we are inside a template class member function 1921 // and we can't resolve an identifier then assume the identifier is type 1922 // dependent. The goal is to postpone name lookup to instantiation time 1923 // to be able to search into type dependent base classes. 1924 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 1925 isa<CXXMethodDecl>(CurContext)) 1926 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1927 IsAddressOfOperand, TemplateArgs); 1928 1929 CorrectionCandidateCallback DefaultValidator; 1930 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1931 return ExprError(); 1932 1933 assert(!R.empty() && 1934 "DiagnoseEmptyLookup returned false but added no results"); 1935 1936 // If we found an Objective-C instance variable, let 1937 // LookupInObjCMethod build the appropriate expression to 1938 // reference the ivar. 1939 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1940 R.clear(); 1941 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1942 // In a hopelessly buggy code, Objective-C instance variable 1943 // lookup fails and no expression will be built to reference it. 1944 if (!E.isInvalid() && !E.get()) 1945 return ExprError(); 1946 return E; 1947 } 1948 } 1949 } 1950 1951 // This is guaranteed from this point on. 1952 assert(!R.empty() || ADL); 1953 1954 // Check whether this might be a C++ implicit instance member access. 1955 // C++ [class.mfct.non-static]p3: 1956 // When an id-expression that is not part of a class member access 1957 // syntax and not used to form a pointer to member is used in the 1958 // body of a non-static member function of class X, if name lookup 1959 // resolves the name in the id-expression to a non-static non-type 1960 // member of some class C, the id-expression is transformed into a 1961 // class member access expression using (*this) as the 1962 // postfix-expression to the left of the . operator. 1963 // 1964 // But we don't actually need to do this for '&' operands if R 1965 // resolved to a function or overloaded function set, because the 1966 // expression is ill-formed if it actually works out to be a 1967 // non-static member function: 1968 // 1969 // C++ [expr.ref]p4: 1970 // Otherwise, if E1.E2 refers to a non-static member function. . . 1971 // [t]he expression can be used only as the left-hand operand of a 1972 // member function call. 1973 // 1974 // There are other safeguards against such uses, but it's important 1975 // to get this right here so that we don't end up making a 1976 // spuriously dependent expression if we're inside a dependent 1977 // instance method. 1978 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1979 bool MightBeImplicitMember; 1980 if (!IsAddressOfOperand) 1981 MightBeImplicitMember = true; 1982 else if (!SS.isEmpty()) 1983 MightBeImplicitMember = false; 1984 else if (R.isOverloadedResult()) 1985 MightBeImplicitMember = false; 1986 else if (R.isUnresolvableResult()) 1987 MightBeImplicitMember = true; 1988 else 1989 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1990 isa<IndirectFieldDecl>(R.getFoundDecl()); 1991 1992 if (MightBeImplicitMember) 1993 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 1994 R, TemplateArgs); 1995 } 1996 1997 if (TemplateArgs || TemplateKWLoc.isValid()) 1998 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 1999 2000 return BuildDeclarationNameExpr(SS, R, ADL); 2001 } 2002 2003 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2004 /// declaration name, generally during template instantiation. 2005 /// There's a large number of things which don't need to be done along 2006 /// this path. 2007 ExprResult 2008 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2009 const DeclarationNameInfo &NameInfo, 2010 bool IsAddressOfOperand) { 2011 DeclContext *DC = computeDeclContext(SS, false); 2012 if (!DC) 2013 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2014 NameInfo, /*TemplateArgs=*/0); 2015 2016 if (RequireCompleteDeclContext(SS, DC)) 2017 return ExprError(); 2018 2019 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2020 LookupQualifiedName(R, DC); 2021 2022 if (R.isAmbiguous()) 2023 return ExprError(); 2024 2025 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2026 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2027 NameInfo, /*TemplateArgs=*/0); 2028 2029 if (R.empty()) { 2030 Diag(NameInfo.getLoc(), diag::err_no_member) 2031 << NameInfo.getName() << DC << SS.getRange(); 2032 return ExprError(); 2033 } 2034 2035 // Defend against this resolving to an implicit member access. We usually 2036 // won't get here if this might be a legitimate a class member (we end up in 2037 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2038 // a pointer-to-member or in an unevaluated context in C++11. 2039 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2040 return BuildPossibleImplicitMemberExpr(SS, 2041 /*TemplateKWLoc=*/SourceLocation(), 2042 R, /*TemplateArgs=*/0); 2043 2044 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2045 } 2046 2047 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2048 /// detected that we're currently inside an ObjC method. Perform some 2049 /// additional lookup. 2050 /// 2051 /// Ideally, most of this would be done by lookup, but there's 2052 /// actually quite a lot of extra work involved. 2053 /// 2054 /// Returns a null sentinel to indicate trivial success. 2055 ExprResult 2056 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2057 IdentifierInfo *II, bool AllowBuiltinCreation) { 2058 SourceLocation Loc = Lookup.getNameLoc(); 2059 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2060 2061 // Check for error condition which is already reported. 2062 if (!CurMethod) 2063 return ExprError(); 2064 2065 // There are two cases to handle here. 1) scoped lookup could have failed, 2066 // in which case we should look for an ivar. 2) scoped lookup could have 2067 // found a decl, but that decl is outside the current instance method (i.e. 2068 // a global variable). In these two cases, we do a lookup for an ivar with 2069 // this name, if the lookup sucedes, we replace it our current decl. 2070 2071 // If we're in a class method, we don't normally want to look for 2072 // ivars. But if we don't find anything else, and there's an 2073 // ivar, that's an error. 2074 bool IsClassMethod = CurMethod->isClassMethod(); 2075 2076 bool LookForIvars; 2077 if (Lookup.empty()) 2078 LookForIvars = true; 2079 else if (IsClassMethod) 2080 LookForIvars = false; 2081 else 2082 LookForIvars = (Lookup.isSingleResult() && 2083 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2084 ObjCInterfaceDecl *IFace = 0; 2085 if (LookForIvars) { 2086 IFace = CurMethod->getClassInterface(); 2087 ObjCInterfaceDecl *ClassDeclared; 2088 ObjCIvarDecl *IV = 0; 2089 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2090 // Diagnose using an ivar in a class method. 2091 if (IsClassMethod) 2092 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2093 << IV->getDeclName()); 2094 2095 // If we're referencing an invalid decl, just return this as a silent 2096 // error node. The error diagnostic was already emitted on the decl. 2097 if (IV->isInvalidDecl()) 2098 return ExprError(); 2099 2100 // Check if referencing a field with __attribute__((deprecated)). 2101 if (DiagnoseUseOfDecl(IV, Loc)) 2102 return ExprError(); 2103 2104 // Diagnose the use of an ivar outside of the declaring class. 2105 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2106 !declaresSameEntity(ClassDeclared, IFace) && 2107 !getLangOpts().DebuggerSupport) 2108 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2109 2110 // FIXME: This should use a new expr for a direct reference, don't 2111 // turn this into Self->ivar, just return a BareIVarExpr or something. 2112 IdentifierInfo &II = Context.Idents.get("self"); 2113 UnqualifiedId SelfName; 2114 SelfName.setIdentifier(&II, SourceLocation()); 2115 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2116 CXXScopeSpec SelfScopeSpec; 2117 SourceLocation TemplateKWLoc; 2118 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2119 SelfName, false, false); 2120 if (SelfExpr.isInvalid()) 2121 return ExprError(); 2122 2123 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2124 if (SelfExpr.isInvalid()) 2125 return ExprError(); 2126 2127 MarkAnyDeclReferenced(Loc, IV, true); 2128 2129 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2130 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2131 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2132 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2133 2134 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2135 Loc, IV->getLocation(), 2136 SelfExpr.take(), 2137 true, true); 2138 2139 if (getLangOpts().ObjCAutoRefCount) { 2140 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2141 DiagnosticsEngine::Level Level = 2142 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2143 if (Level != DiagnosticsEngine::Ignored) 2144 getCurFunction()->recordUseOfWeak(Result); 2145 } 2146 if (CurContext->isClosure()) 2147 Diag(Loc, diag::warn_implicitly_retains_self) 2148 << FixItHint::CreateInsertion(Loc, "self->"); 2149 } 2150 2151 return Owned(Result); 2152 } 2153 } else if (CurMethod->isInstanceMethod()) { 2154 // We should warn if a local variable hides an ivar. 2155 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2156 ObjCInterfaceDecl *ClassDeclared; 2157 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2158 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2159 declaresSameEntity(IFace, ClassDeclared)) 2160 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2161 } 2162 } 2163 } else if (Lookup.isSingleResult() && 2164 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2165 // If accessing a stand-alone ivar in a class method, this is an error. 2166 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2167 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2168 << IV->getDeclName()); 2169 } 2170 2171 if (Lookup.empty() && II && AllowBuiltinCreation) { 2172 // FIXME. Consolidate this with similar code in LookupName. 2173 if (unsigned BuiltinID = II->getBuiltinID()) { 2174 if (!(getLangOpts().CPlusPlus && 2175 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2176 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2177 S, Lookup.isForRedeclaration(), 2178 Lookup.getNameLoc()); 2179 if (D) Lookup.addDecl(D); 2180 } 2181 } 2182 } 2183 // Sentinel value saying that we didn't do anything special. 2184 return Owned((Expr*) 0); 2185 } 2186 2187 /// \brief Cast a base object to a member's actual type. 2188 /// 2189 /// Logically this happens in three phases: 2190 /// 2191 /// * First we cast from the base type to the naming class. 2192 /// The naming class is the class into which we were looking 2193 /// when we found the member; it's the qualifier type if a 2194 /// qualifier was provided, and otherwise it's the base type. 2195 /// 2196 /// * Next we cast from the naming class to the declaring class. 2197 /// If the member we found was brought into a class's scope by 2198 /// a using declaration, this is that class; otherwise it's 2199 /// the class declaring the member. 2200 /// 2201 /// * Finally we cast from the declaring class to the "true" 2202 /// declaring class of the member. This conversion does not 2203 /// obey access control. 2204 ExprResult 2205 Sema::PerformObjectMemberConversion(Expr *From, 2206 NestedNameSpecifier *Qualifier, 2207 NamedDecl *FoundDecl, 2208 NamedDecl *Member) { 2209 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2210 if (!RD) 2211 return Owned(From); 2212 2213 QualType DestRecordType; 2214 QualType DestType; 2215 QualType FromRecordType; 2216 QualType FromType = From->getType(); 2217 bool PointerConversions = false; 2218 if (isa<FieldDecl>(Member)) { 2219 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2220 2221 if (FromType->getAs<PointerType>()) { 2222 DestType = Context.getPointerType(DestRecordType); 2223 FromRecordType = FromType->getPointeeType(); 2224 PointerConversions = true; 2225 } else { 2226 DestType = DestRecordType; 2227 FromRecordType = FromType; 2228 } 2229 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2230 if (Method->isStatic()) 2231 return Owned(From); 2232 2233 DestType = Method->getThisType(Context); 2234 DestRecordType = DestType->getPointeeType(); 2235 2236 if (FromType->getAs<PointerType>()) { 2237 FromRecordType = FromType->getPointeeType(); 2238 PointerConversions = true; 2239 } else { 2240 FromRecordType = FromType; 2241 DestType = DestRecordType; 2242 } 2243 } else { 2244 // No conversion necessary. 2245 return Owned(From); 2246 } 2247 2248 if (DestType->isDependentType() || FromType->isDependentType()) 2249 return Owned(From); 2250 2251 // If the unqualified types are the same, no conversion is necessary. 2252 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2253 return Owned(From); 2254 2255 SourceRange FromRange = From->getSourceRange(); 2256 SourceLocation FromLoc = FromRange.getBegin(); 2257 2258 ExprValueKind VK = From->getValueKind(); 2259 2260 // C++ [class.member.lookup]p8: 2261 // [...] Ambiguities can often be resolved by qualifying a name with its 2262 // class name. 2263 // 2264 // If the member was a qualified name and the qualified referred to a 2265 // specific base subobject type, we'll cast to that intermediate type 2266 // first and then to the object in which the member is declared. That allows 2267 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2268 // 2269 // class Base { public: int x; }; 2270 // class Derived1 : public Base { }; 2271 // class Derived2 : public Base { }; 2272 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2273 // 2274 // void VeryDerived::f() { 2275 // x = 17; // error: ambiguous base subobjects 2276 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2277 // } 2278 if (Qualifier) { 2279 QualType QType = QualType(Qualifier->getAsType(), 0); 2280 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2281 assert(QType->isRecordType() && "lookup done with non-record type"); 2282 2283 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2284 2285 // In C++98, the qualifier type doesn't actually have to be a base 2286 // type of the object type, in which case we just ignore it. 2287 // Otherwise build the appropriate casts. 2288 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2289 CXXCastPath BasePath; 2290 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2291 FromLoc, FromRange, &BasePath)) 2292 return ExprError(); 2293 2294 if (PointerConversions) 2295 QType = Context.getPointerType(QType); 2296 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2297 VK, &BasePath).take(); 2298 2299 FromType = QType; 2300 FromRecordType = QRecordType; 2301 2302 // If the qualifier type was the same as the destination type, 2303 // we're done. 2304 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2305 return Owned(From); 2306 } 2307 } 2308 2309 bool IgnoreAccess = false; 2310 2311 // If we actually found the member through a using declaration, cast 2312 // down to the using declaration's type. 2313 // 2314 // Pointer equality is fine here because only one declaration of a 2315 // class ever has member declarations. 2316 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2317 assert(isa<UsingShadowDecl>(FoundDecl)); 2318 QualType URecordType = Context.getTypeDeclType( 2319 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2320 2321 // We only need to do this if the naming-class to declaring-class 2322 // conversion is non-trivial. 2323 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2324 assert(IsDerivedFrom(FromRecordType, URecordType)); 2325 CXXCastPath BasePath; 2326 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2327 FromLoc, FromRange, &BasePath)) 2328 return ExprError(); 2329 2330 QualType UType = URecordType; 2331 if (PointerConversions) 2332 UType = Context.getPointerType(UType); 2333 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2334 VK, &BasePath).take(); 2335 FromType = UType; 2336 FromRecordType = URecordType; 2337 } 2338 2339 // We don't do access control for the conversion from the 2340 // declaring class to the true declaring class. 2341 IgnoreAccess = true; 2342 } 2343 2344 CXXCastPath BasePath; 2345 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2346 FromLoc, FromRange, &BasePath, 2347 IgnoreAccess)) 2348 return ExprError(); 2349 2350 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2351 VK, &BasePath); 2352 } 2353 2354 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2355 const LookupResult &R, 2356 bool HasTrailingLParen) { 2357 // Only when used directly as the postfix-expression of a call. 2358 if (!HasTrailingLParen) 2359 return false; 2360 2361 // Never if a scope specifier was provided. 2362 if (SS.isSet()) 2363 return false; 2364 2365 // Only in C++ or ObjC++. 2366 if (!getLangOpts().CPlusPlus) 2367 return false; 2368 2369 // Turn off ADL when we find certain kinds of declarations during 2370 // normal lookup: 2371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2372 NamedDecl *D = *I; 2373 2374 // C++0x [basic.lookup.argdep]p3: 2375 // -- a declaration of a class member 2376 // Since using decls preserve this property, we check this on the 2377 // original decl. 2378 if (D->isCXXClassMember()) 2379 return false; 2380 2381 // C++0x [basic.lookup.argdep]p3: 2382 // -- a block-scope function declaration that is not a 2383 // using-declaration 2384 // NOTE: we also trigger this for function templates (in fact, we 2385 // don't check the decl type at all, since all other decl types 2386 // turn off ADL anyway). 2387 if (isa<UsingShadowDecl>(D)) 2388 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2389 else if (D->getDeclContext()->isFunctionOrMethod()) 2390 return false; 2391 2392 // C++0x [basic.lookup.argdep]p3: 2393 // -- a declaration that is neither a function or a function 2394 // template 2395 // And also for builtin functions. 2396 if (isa<FunctionDecl>(D)) { 2397 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2398 2399 // But also builtin functions. 2400 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2401 return false; 2402 } else if (!isa<FunctionTemplateDecl>(D)) 2403 return false; 2404 } 2405 2406 return true; 2407 } 2408 2409 2410 /// Diagnoses obvious problems with the use of the given declaration 2411 /// as an expression. This is only actually called for lookups that 2412 /// were not overloaded, and it doesn't promise that the declaration 2413 /// will in fact be used. 2414 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2415 if (isa<TypedefNameDecl>(D)) { 2416 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2417 return true; 2418 } 2419 2420 if (isa<ObjCInterfaceDecl>(D)) { 2421 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2422 return true; 2423 } 2424 2425 if (isa<NamespaceDecl>(D)) { 2426 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2427 return true; 2428 } 2429 2430 return false; 2431 } 2432 2433 ExprResult 2434 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2435 LookupResult &R, 2436 bool NeedsADL) { 2437 // If this is a single, fully-resolved result and we don't need ADL, 2438 // just build an ordinary singleton decl ref. 2439 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2440 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2441 R.getRepresentativeDecl()); 2442 2443 // We only need to check the declaration if there's exactly one 2444 // result, because in the overloaded case the results can only be 2445 // functions and function templates. 2446 if (R.isSingleResult() && 2447 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2448 return ExprError(); 2449 2450 // Otherwise, just build an unresolved lookup expression. Suppress 2451 // any lookup-related diagnostics; we'll hash these out later, when 2452 // we've picked a target. 2453 R.suppressDiagnostics(); 2454 2455 UnresolvedLookupExpr *ULE 2456 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2457 SS.getWithLocInContext(Context), 2458 R.getLookupNameInfo(), 2459 NeedsADL, R.isOverloadedResult(), 2460 R.begin(), R.end()); 2461 2462 return Owned(ULE); 2463 } 2464 2465 /// \brief Complete semantic analysis for a reference to the given declaration. 2466 ExprResult 2467 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2468 const DeclarationNameInfo &NameInfo, 2469 NamedDecl *D, NamedDecl *FoundD) { 2470 assert(D && "Cannot refer to a NULL declaration"); 2471 assert(!isa<FunctionTemplateDecl>(D) && 2472 "Cannot refer unambiguously to a function template"); 2473 2474 SourceLocation Loc = NameInfo.getLoc(); 2475 if (CheckDeclInExpr(*this, Loc, D)) 2476 return ExprError(); 2477 2478 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2479 // Specifically diagnose references to class templates that are missing 2480 // a template argument list. 2481 Diag(Loc, diag::err_template_decl_ref) 2482 << Template << SS.getRange(); 2483 Diag(Template->getLocation(), diag::note_template_decl_here); 2484 return ExprError(); 2485 } 2486 2487 // Make sure that we're referring to a value. 2488 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2489 if (!VD) { 2490 Diag(Loc, diag::err_ref_non_value) 2491 << D << SS.getRange(); 2492 Diag(D->getLocation(), diag::note_declared_at); 2493 return ExprError(); 2494 } 2495 2496 // Check whether this declaration can be used. Note that we suppress 2497 // this check when we're going to perform argument-dependent lookup 2498 // on this function name, because this might not be the function 2499 // that overload resolution actually selects. 2500 if (DiagnoseUseOfDecl(VD, Loc)) 2501 return ExprError(); 2502 2503 // Only create DeclRefExpr's for valid Decl's. 2504 if (VD->isInvalidDecl()) 2505 return ExprError(); 2506 2507 // Handle members of anonymous structs and unions. If we got here, 2508 // and the reference is to a class member indirect field, then this 2509 // must be the subject of a pointer-to-member expression. 2510 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2511 if (!indirectField->isCXXClassMember()) 2512 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2513 indirectField); 2514 2515 { 2516 QualType type = VD->getType(); 2517 ExprValueKind valueKind = VK_RValue; 2518 2519 switch (D->getKind()) { 2520 // Ignore all the non-ValueDecl kinds. 2521 #define ABSTRACT_DECL(kind) 2522 #define VALUE(type, base) 2523 #define DECL(type, base) \ 2524 case Decl::type: 2525 #include "clang/AST/DeclNodes.inc" 2526 llvm_unreachable("invalid value decl kind"); 2527 2528 // These shouldn't make it here. 2529 case Decl::ObjCAtDefsField: 2530 case Decl::ObjCIvar: 2531 llvm_unreachable("forming non-member reference to ivar?"); 2532 2533 // Enum constants are always r-values and never references. 2534 // Unresolved using declarations are dependent. 2535 case Decl::EnumConstant: 2536 case Decl::UnresolvedUsingValue: 2537 valueKind = VK_RValue; 2538 break; 2539 2540 // Fields and indirect fields that got here must be for 2541 // pointer-to-member expressions; we just call them l-values for 2542 // internal consistency, because this subexpression doesn't really 2543 // exist in the high-level semantics. 2544 case Decl::Field: 2545 case Decl::IndirectField: 2546 assert(getLangOpts().CPlusPlus && 2547 "building reference to field in C?"); 2548 2549 // These can't have reference type in well-formed programs, but 2550 // for internal consistency we do this anyway. 2551 type = type.getNonReferenceType(); 2552 valueKind = VK_LValue; 2553 break; 2554 2555 // Non-type template parameters are either l-values or r-values 2556 // depending on the type. 2557 case Decl::NonTypeTemplateParm: { 2558 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2559 type = reftype->getPointeeType(); 2560 valueKind = VK_LValue; // even if the parameter is an r-value reference 2561 break; 2562 } 2563 2564 // For non-references, we need to strip qualifiers just in case 2565 // the template parameter was declared as 'const int' or whatever. 2566 valueKind = VK_RValue; 2567 type = type.getUnqualifiedType(); 2568 break; 2569 } 2570 2571 case Decl::Var: 2572 // In C, "extern void blah;" is valid and is an r-value. 2573 if (!getLangOpts().CPlusPlus && 2574 !type.hasQualifiers() && 2575 type->isVoidType()) { 2576 valueKind = VK_RValue; 2577 break; 2578 } 2579 // fallthrough 2580 2581 case Decl::ImplicitParam: 2582 case Decl::ParmVar: { 2583 // These are always l-values. 2584 valueKind = VK_LValue; 2585 type = type.getNonReferenceType(); 2586 2587 // FIXME: Does the addition of const really only apply in 2588 // potentially-evaluated contexts? Since the variable isn't actually 2589 // captured in an unevaluated context, it seems that the answer is no. 2590 if (!isUnevaluatedContext()) { 2591 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2592 if (!CapturedType.isNull()) 2593 type = CapturedType; 2594 } 2595 2596 break; 2597 } 2598 2599 case Decl::Function: { 2600 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2601 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2602 type = Context.BuiltinFnTy; 2603 valueKind = VK_RValue; 2604 break; 2605 } 2606 } 2607 2608 const FunctionType *fty = type->castAs<FunctionType>(); 2609 2610 // If we're referring to a function with an __unknown_anytype 2611 // result type, make the entire expression __unknown_anytype. 2612 if (fty->getResultType() == Context.UnknownAnyTy) { 2613 type = Context.UnknownAnyTy; 2614 valueKind = VK_RValue; 2615 break; 2616 } 2617 2618 // Functions are l-values in C++. 2619 if (getLangOpts().CPlusPlus) { 2620 valueKind = VK_LValue; 2621 break; 2622 } 2623 2624 // C99 DR 316 says that, if a function type comes from a 2625 // function definition (without a prototype), that type is only 2626 // used for checking compatibility. Therefore, when referencing 2627 // the function, we pretend that we don't have the full function 2628 // type. 2629 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2630 isa<FunctionProtoType>(fty)) 2631 type = Context.getFunctionNoProtoType(fty->getResultType(), 2632 fty->getExtInfo()); 2633 2634 // Functions are r-values in C. 2635 valueKind = VK_RValue; 2636 break; 2637 } 2638 2639 case Decl::MSProperty: 2640 valueKind = VK_LValue; 2641 break; 2642 2643 case Decl::CXXMethod: 2644 // If we're referring to a method with an __unknown_anytype 2645 // result type, make the entire expression __unknown_anytype. 2646 // This should only be possible with a type written directly. 2647 if (const FunctionProtoType *proto 2648 = dyn_cast<FunctionProtoType>(VD->getType())) 2649 if (proto->getResultType() == Context.UnknownAnyTy) { 2650 type = Context.UnknownAnyTy; 2651 valueKind = VK_RValue; 2652 break; 2653 } 2654 2655 // C++ methods are l-values if static, r-values if non-static. 2656 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2657 valueKind = VK_LValue; 2658 break; 2659 } 2660 // fallthrough 2661 2662 case Decl::CXXConversion: 2663 case Decl::CXXDestructor: 2664 case Decl::CXXConstructor: 2665 valueKind = VK_RValue; 2666 break; 2667 } 2668 2669 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD); 2670 } 2671 } 2672 2673 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2674 PredefinedExpr::IdentType IT; 2675 2676 switch (Kind) { 2677 default: llvm_unreachable("Unknown simple primary expr!"); 2678 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2679 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2680 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2681 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2682 } 2683 2684 // Pre-defined identifiers are of type char[x], where x is the length of the 2685 // string. 2686 2687 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2688 // Blocks and lambdas can occur at global scope. Don't emit a warning. 2689 if (!currentDecl) { 2690 if (const BlockScopeInfo *BSI = getCurBlock()) 2691 currentDecl = BSI->TheDecl; 2692 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2693 currentDecl = LSI->CallOperator; 2694 } 2695 2696 if (!currentDecl) { 2697 Diag(Loc, diag::ext_predef_outside_function); 2698 currentDecl = Context.getTranslationUnitDecl(); 2699 } 2700 2701 QualType ResTy; 2702 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2703 ResTy = Context.DependentTy; 2704 } else { 2705 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2706 2707 llvm::APInt LengthI(32, Length + 1); 2708 if (IT == PredefinedExpr::LFunction) 2709 ResTy = Context.WCharTy.withConst(); 2710 else 2711 ResTy = Context.CharTy.withConst(); 2712 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2713 } 2714 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2715 } 2716 2717 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2718 SmallString<16> CharBuffer; 2719 bool Invalid = false; 2720 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2721 if (Invalid) 2722 return ExprError(); 2723 2724 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2725 PP, Tok.getKind()); 2726 if (Literal.hadError()) 2727 return ExprError(); 2728 2729 QualType Ty; 2730 if (Literal.isWide()) 2731 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++. 2732 else if (Literal.isUTF16()) 2733 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2734 else if (Literal.isUTF32()) 2735 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2736 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2737 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2738 else 2739 Ty = Context.CharTy; // 'x' -> char in C++ 2740 2741 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2742 if (Literal.isWide()) 2743 Kind = CharacterLiteral::Wide; 2744 else if (Literal.isUTF16()) 2745 Kind = CharacterLiteral::UTF16; 2746 else if (Literal.isUTF32()) 2747 Kind = CharacterLiteral::UTF32; 2748 2749 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2750 Tok.getLocation()); 2751 2752 if (Literal.getUDSuffix().empty()) 2753 return Owned(Lit); 2754 2755 // We're building a user-defined literal. 2756 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2757 SourceLocation UDSuffixLoc = 2758 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2759 2760 // Make sure we're allowed user-defined literals here. 2761 if (!UDLScope) 2762 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2763 2764 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2765 // operator "" X (ch) 2766 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2767 llvm::makeArrayRef(&Lit, 1), 2768 Tok.getLocation()); 2769 } 2770 2771 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2772 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2773 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2774 Context.IntTy, Loc)); 2775 } 2776 2777 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2778 QualType Ty, SourceLocation Loc) { 2779 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2780 2781 using llvm::APFloat; 2782 APFloat Val(Format); 2783 2784 APFloat::opStatus result = Literal.GetFloatValue(Val); 2785 2786 // Overflow is always an error, but underflow is only an error if 2787 // we underflowed to zero (APFloat reports denormals as underflow). 2788 if ((result & APFloat::opOverflow) || 2789 ((result & APFloat::opUnderflow) && Val.isZero())) { 2790 unsigned diagnostic; 2791 SmallString<20> buffer; 2792 if (result & APFloat::opOverflow) { 2793 diagnostic = diag::warn_float_overflow; 2794 APFloat::getLargest(Format).toString(buffer); 2795 } else { 2796 diagnostic = diag::warn_float_underflow; 2797 APFloat::getSmallest(Format).toString(buffer); 2798 } 2799 2800 S.Diag(Loc, diagnostic) 2801 << Ty 2802 << StringRef(buffer.data(), buffer.size()); 2803 } 2804 2805 bool isExact = (result == APFloat::opOK); 2806 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2807 } 2808 2809 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2810 // Fast path for a single digit (which is quite common). A single digit 2811 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2812 if (Tok.getLength() == 1) { 2813 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2814 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2815 } 2816 2817 SmallString<128> SpellingBuffer; 2818 // NumericLiteralParser wants to overread by one character. Add padding to 2819 // the buffer in case the token is copied to the buffer. If getSpelling() 2820 // returns a StringRef to the memory buffer, it should have a null char at 2821 // the EOF, so it is also safe. 2822 SpellingBuffer.resize(Tok.getLength() + 1); 2823 2824 // Get the spelling of the token, which eliminates trigraphs, etc. 2825 bool Invalid = false; 2826 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2827 if (Invalid) 2828 return ExprError(); 2829 2830 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2831 if (Literal.hadError) 2832 return ExprError(); 2833 2834 if (Literal.hasUDSuffix()) { 2835 // We're building a user-defined literal. 2836 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2837 SourceLocation UDSuffixLoc = 2838 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2839 2840 // Make sure we're allowed user-defined literals here. 2841 if (!UDLScope) 2842 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2843 2844 QualType CookedTy; 2845 if (Literal.isFloatingLiteral()) { 2846 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2847 // long double, the literal is treated as a call of the form 2848 // operator "" X (f L) 2849 CookedTy = Context.LongDoubleTy; 2850 } else { 2851 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2852 // unsigned long long, the literal is treated as a call of the form 2853 // operator "" X (n ULL) 2854 CookedTy = Context.UnsignedLongLongTy; 2855 } 2856 2857 DeclarationName OpName = 2858 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2859 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2860 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2861 2862 // Perform literal operator lookup to determine if we're building a raw 2863 // literal or a cooked one. 2864 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2865 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1), 2866 /*AllowRawAndTemplate*/true)) { 2867 case LOLR_Error: 2868 return ExprError(); 2869 2870 case LOLR_Cooked: { 2871 Expr *Lit; 2872 if (Literal.isFloatingLiteral()) { 2873 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2874 } else { 2875 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2876 if (Literal.GetIntegerValue(ResultVal)) 2877 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2878 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2879 Tok.getLocation()); 2880 } 2881 return BuildLiteralOperatorCall(R, OpNameInfo, 2882 llvm::makeArrayRef(&Lit, 1), 2883 Tok.getLocation()); 2884 } 2885 2886 case LOLR_Raw: { 2887 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2888 // literal is treated as a call of the form 2889 // operator "" X ("n") 2890 SourceLocation TokLoc = Tok.getLocation(); 2891 unsigned Length = Literal.getUDSuffixOffset(); 2892 QualType StrTy = Context.getConstantArrayType( 2893 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 2894 ArrayType::Normal, 0); 2895 Expr *Lit = StringLiteral::Create( 2896 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2897 /*Pascal*/false, StrTy, &TokLoc, 1); 2898 return BuildLiteralOperatorCall(R, OpNameInfo, 2899 llvm::makeArrayRef(&Lit, 1), TokLoc); 2900 } 2901 2902 case LOLR_Template: 2903 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2904 // template), L is treated as a call fo the form 2905 // operator "" X <'c1', 'c2', ... 'ck'>() 2906 // where n is the source character sequence c1 c2 ... ck. 2907 TemplateArgumentListInfo ExplicitArgs; 2908 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2909 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2910 llvm::APSInt Value(CharBits, CharIsUnsigned); 2911 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2912 Value = TokSpelling[I]; 2913 TemplateArgument Arg(Context, Value, Context.CharTy); 2914 TemplateArgumentLocInfo ArgInfo; 2915 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2916 } 2917 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(), 2918 Tok.getLocation(), &ExplicitArgs); 2919 } 2920 2921 llvm_unreachable("unexpected literal operator lookup result"); 2922 } 2923 2924 Expr *Res; 2925 2926 if (Literal.isFloatingLiteral()) { 2927 QualType Ty; 2928 if (Literal.isFloat) 2929 Ty = Context.FloatTy; 2930 else if (!Literal.isLong) 2931 Ty = Context.DoubleTy; 2932 else 2933 Ty = Context.LongDoubleTy; 2934 2935 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2936 2937 if (Ty == Context.DoubleTy) { 2938 if (getLangOpts().SinglePrecisionConstants) { 2939 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2940 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2941 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2942 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2943 } 2944 } 2945 } else if (!Literal.isIntegerLiteral()) { 2946 return ExprError(); 2947 } else { 2948 QualType Ty; 2949 2950 // 'long long' is a C99 or C++11 feature. 2951 if (!getLangOpts().C99 && Literal.isLongLong) { 2952 if (getLangOpts().CPlusPlus) 2953 Diag(Tok.getLocation(), 2954 getLangOpts().CPlusPlus11 ? 2955 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 2956 else 2957 Diag(Tok.getLocation(), diag::ext_c99_longlong); 2958 } 2959 2960 // Get the value in the widest-possible width. 2961 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2962 // The microsoft literal suffix extensions support 128-bit literals, which 2963 // may be wider than [u]intmax_t. 2964 // FIXME: Actually, they don't. We seem to have accidentally invented the 2965 // i128 suffix. 2966 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 2967 PP.getTargetInfo().hasInt128Type()) 2968 MaxWidth = 128; 2969 llvm::APInt ResultVal(MaxWidth, 0); 2970 2971 if (Literal.GetIntegerValue(ResultVal)) { 2972 // If this value didn't fit into uintmax_t, warn and force to ull. 2973 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2974 Ty = Context.UnsignedLongLongTy; 2975 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2976 "long long is not intmax_t?"); 2977 } else { 2978 // If this value fits into a ULL, try to figure out what else it fits into 2979 // according to the rules of C99 6.4.4.1p5. 2980 2981 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2982 // be an unsigned int. 2983 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2984 2985 // Check from smallest to largest, picking the smallest type we can. 2986 unsigned Width = 0; 2987 if (!Literal.isLong && !Literal.isLongLong) { 2988 // Are int/unsigned possibilities? 2989 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2990 2991 // Does it fit in a unsigned int? 2992 if (ResultVal.isIntN(IntSize)) { 2993 // Does it fit in a signed int? 2994 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2995 Ty = Context.IntTy; 2996 else if (AllowUnsigned) 2997 Ty = Context.UnsignedIntTy; 2998 Width = IntSize; 2999 } 3000 } 3001 3002 // Are long/unsigned long possibilities? 3003 if (Ty.isNull() && !Literal.isLongLong) { 3004 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3005 3006 // Does it fit in a unsigned long? 3007 if (ResultVal.isIntN(LongSize)) { 3008 // Does it fit in a signed long? 3009 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3010 Ty = Context.LongTy; 3011 else if (AllowUnsigned) 3012 Ty = Context.UnsignedLongTy; 3013 Width = LongSize; 3014 } 3015 } 3016 3017 // Check long long if needed. 3018 if (Ty.isNull()) { 3019 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3020 3021 // Does it fit in a unsigned long long? 3022 if (ResultVal.isIntN(LongLongSize)) { 3023 // Does it fit in a signed long long? 3024 // To be compatible with MSVC, hex integer literals ending with the 3025 // LL or i64 suffix are always signed in Microsoft mode. 3026 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3027 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3028 Ty = Context.LongLongTy; 3029 else if (AllowUnsigned) 3030 Ty = Context.UnsignedLongLongTy; 3031 Width = LongLongSize; 3032 } 3033 } 3034 3035 // If it doesn't fit in unsigned long long, and we're using Microsoft 3036 // extensions, then its a 128-bit integer literal. 3037 if (Ty.isNull() && Literal.isMicrosoftInteger && 3038 PP.getTargetInfo().hasInt128Type()) { 3039 if (Literal.isUnsigned) 3040 Ty = Context.UnsignedInt128Ty; 3041 else 3042 Ty = Context.Int128Ty; 3043 Width = 128; 3044 } 3045 3046 // If we still couldn't decide a type, we probably have something that 3047 // does not fit in a signed long long, but has no U suffix. 3048 if (Ty.isNull()) { 3049 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3050 Ty = Context.UnsignedLongLongTy; 3051 Width = Context.getTargetInfo().getLongLongWidth(); 3052 } 3053 3054 if (ResultVal.getBitWidth() != Width) 3055 ResultVal = ResultVal.trunc(Width); 3056 } 3057 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3058 } 3059 3060 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3061 if (Literal.isImaginary) 3062 Res = new (Context) ImaginaryLiteral(Res, 3063 Context.getComplexType(Res->getType())); 3064 3065 return Owned(Res); 3066 } 3067 3068 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3069 assert((E != 0) && "ActOnParenExpr() missing expr"); 3070 return Owned(new (Context) ParenExpr(L, R, E)); 3071 } 3072 3073 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3074 SourceLocation Loc, 3075 SourceRange ArgRange) { 3076 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3077 // scalar or vector data type argument..." 3078 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3079 // type (C99 6.2.5p18) or void. 3080 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3081 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3082 << T << ArgRange; 3083 return true; 3084 } 3085 3086 assert((T->isVoidType() || !T->isIncompleteType()) && 3087 "Scalar types should always be complete"); 3088 return false; 3089 } 3090 3091 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3092 SourceLocation Loc, 3093 SourceRange ArgRange, 3094 UnaryExprOrTypeTrait TraitKind) { 3095 // C99 6.5.3.4p1: 3096 if (T->isFunctionType() && 3097 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3098 // sizeof(function)/alignof(function) is allowed as an extension. 3099 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3100 << TraitKind << ArgRange; 3101 return false; 3102 } 3103 3104 // Allow sizeof(void)/alignof(void) as an extension. 3105 if (T->isVoidType()) { 3106 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3107 return false; 3108 } 3109 3110 return true; 3111 } 3112 3113 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3114 SourceLocation Loc, 3115 SourceRange ArgRange, 3116 UnaryExprOrTypeTrait TraitKind) { 3117 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3118 // runtime doesn't allow it. 3119 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3120 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3121 << T << (TraitKind == UETT_SizeOf) 3122 << ArgRange; 3123 return true; 3124 } 3125 3126 return false; 3127 } 3128 3129 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3130 /// pointer type is equal to T) and emit a warning if it is. 3131 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3132 Expr *E) { 3133 // Don't warn if the operation changed the type. 3134 if (T != E->getType()) 3135 return; 3136 3137 // Now look for array decays. 3138 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3139 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3140 return; 3141 3142 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3143 << ICE->getType() 3144 << ICE->getSubExpr()->getType(); 3145 } 3146 3147 /// \brief Check the constrains on expression operands to unary type expression 3148 /// and type traits. 3149 /// 3150 /// Completes any types necessary and validates the constraints on the operand 3151 /// expression. The logic mostly mirrors the type-based overload, but may modify 3152 /// the expression as it completes the type for that expression through template 3153 /// instantiation, etc. 3154 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3155 UnaryExprOrTypeTrait ExprKind) { 3156 QualType ExprTy = E->getType(); 3157 3158 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3159 // the result is the size of the referenced type." 3160 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3161 // result shall be the alignment of the referenced type." 3162 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 3163 ExprTy = Ref->getPointeeType(); 3164 3165 if (ExprKind == UETT_VecStep) 3166 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3167 E->getSourceRange()); 3168 3169 // Whitelist some types as extensions 3170 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3171 E->getSourceRange(), ExprKind)) 3172 return false; 3173 3174 if (RequireCompleteExprType(E, 3175 diag::err_sizeof_alignof_incomplete_type, 3176 ExprKind, E->getSourceRange())) 3177 return true; 3178 3179 // Completeing the expression's type may have changed it. 3180 ExprTy = E->getType(); 3181 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 3182 ExprTy = Ref->getPointeeType(); 3183 3184 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3185 E->getSourceRange(), ExprKind)) 3186 return true; 3187 3188 if (ExprKind == UETT_SizeOf) { 3189 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3190 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3191 QualType OType = PVD->getOriginalType(); 3192 QualType Type = PVD->getType(); 3193 if (Type->isPointerType() && OType->isArrayType()) { 3194 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3195 << Type << OType; 3196 Diag(PVD->getLocation(), diag::note_declared_at); 3197 } 3198 } 3199 } 3200 3201 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3202 // decays into a pointer and returns an unintended result. This is most 3203 // likely a typo for "sizeof(array) op x". 3204 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3205 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3206 BO->getLHS()); 3207 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3208 BO->getRHS()); 3209 } 3210 } 3211 3212 return false; 3213 } 3214 3215 /// \brief Check the constraints on operands to unary expression and type 3216 /// traits. 3217 /// 3218 /// This will complete any types necessary, and validate the various constraints 3219 /// on those operands. 3220 /// 3221 /// The UsualUnaryConversions() function is *not* called by this routine. 3222 /// C99 6.3.2.1p[2-4] all state: 3223 /// Except when it is the operand of the sizeof operator ... 3224 /// 3225 /// C++ [expr.sizeof]p4 3226 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3227 /// standard conversions are not applied to the operand of sizeof. 3228 /// 3229 /// This policy is followed for all of the unary trait expressions. 3230 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3231 SourceLocation OpLoc, 3232 SourceRange ExprRange, 3233 UnaryExprOrTypeTrait ExprKind) { 3234 if (ExprType->isDependentType()) 3235 return false; 3236 3237 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3238 // the result is the size of the referenced type." 3239 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3240 // result shall be the alignment of the referenced type." 3241 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3242 ExprType = Ref->getPointeeType(); 3243 3244 if (ExprKind == UETT_VecStep) 3245 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3246 3247 // Whitelist some types as extensions 3248 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3249 ExprKind)) 3250 return false; 3251 3252 if (RequireCompleteType(OpLoc, ExprType, 3253 diag::err_sizeof_alignof_incomplete_type, 3254 ExprKind, ExprRange)) 3255 return true; 3256 3257 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3258 ExprKind)) 3259 return true; 3260 3261 return false; 3262 } 3263 3264 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3265 E = E->IgnoreParens(); 3266 3267 // alignof decl is always ok. 3268 if (isa<DeclRefExpr>(E)) 3269 return false; 3270 3271 // Cannot know anything else if the expression is dependent. 3272 if (E->isTypeDependent()) 3273 return false; 3274 3275 if (E->getBitField()) { 3276 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3277 << 1 << E->getSourceRange(); 3278 return true; 3279 } 3280 3281 // Alignment of a field access is always okay, so long as it isn't a 3282 // bit-field. 3283 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 3284 if (isa<FieldDecl>(ME->getMemberDecl())) 3285 return false; 3286 3287 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3288 } 3289 3290 bool Sema::CheckVecStepExpr(Expr *E) { 3291 E = E->IgnoreParens(); 3292 3293 // Cannot know anything else if the expression is dependent. 3294 if (E->isTypeDependent()) 3295 return false; 3296 3297 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3298 } 3299 3300 /// \brief Build a sizeof or alignof expression given a type operand. 3301 ExprResult 3302 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3303 SourceLocation OpLoc, 3304 UnaryExprOrTypeTrait ExprKind, 3305 SourceRange R) { 3306 if (!TInfo) 3307 return ExprError(); 3308 3309 QualType T = TInfo->getType(); 3310 3311 if (!T->isDependentType() && 3312 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3313 return ExprError(); 3314 3315 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3316 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3317 Context.getSizeType(), 3318 OpLoc, R.getEnd())); 3319 } 3320 3321 /// \brief Build a sizeof or alignof expression given an expression 3322 /// operand. 3323 ExprResult 3324 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3325 UnaryExprOrTypeTrait ExprKind) { 3326 ExprResult PE = CheckPlaceholderExpr(E); 3327 if (PE.isInvalid()) 3328 return ExprError(); 3329 3330 E = PE.get(); 3331 3332 // Verify that the operand is valid. 3333 bool isInvalid = false; 3334 if (E->isTypeDependent()) { 3335 // Delay type-checking for type-dependent expressions. 3336 } else if (ExprKind == UETT_AlignOf) { 3337 isInvalid = CheckAlignOfExpr(*this, E); 3338 } else if (ExprKind == UETT_VecStep) { 3339 isInvalid = CheckVecStepExpr(E); 3340 } else if (E->getBitField()) { // C99 6.5.3.4p1. 3341 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3342 isInvalid = true; 3343 } else { 3344 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3345 } 3346 3347 if (isInvalid) 3348 return ExprError(); 3349 3350 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3351 PE = TransformToPotentiallyEvaluated(E); 3352 if (PE.isInvalid()) return ExprError(); 3353 E = PE.take(); 3354 } 3355 3356 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3357 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3358 ExprKind, E, Context.getSizeType(), OpLoc, 3359 E->getSourceRange().getEnd())); 3360 } 3361 3362 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3363 /// expr and the same for @c alignof and @c __alignof 3364 /// Note that the ArgRange is invalid if isType is false. 3365 ExprResult 3366 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3367 UnaryExprOrTypeTrait ExprKind, bool IsType, 3368 void *TyOrEx, const SourceRange &ArgRange) { 3369 // If error parsing type, ignore. 3370 if (TyOrEx == 0) return ExprError(); 3371 3372 if (IsType) { 3373 TypeSourceInfo *TInfo; 3374 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3375 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3376 } 3377 3378 Expr *ArgEx = (Expr *)TyOrEx; 3379 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3380 return Result; 3381 } 3382 3383 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3384 bool IsReal) { 3385 if (V.get()->isTypeDependent()) 3386 return S.Context.DependentTy; 3387 3388 // _Real and _Imag are only l-values for normal l-values. 3389 if (V.get()->getObjectKind() != OK_Ordinary) { 3390 V = S.DefaultLvalueConversion(V.take()); 3391 if (V.isInvalid()) 3392 return QualType(); 3393 } 3394 3395 // These operators return the element type of a complex type. 3396 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3397 return CT->getElementType(); 3398 3399 // Otherwise they pass through real integer and floating point types here. 3400 if (V.get()->getType()->isArithmeticType()) 3401 return V.get()->getType(); 3402 3403 // Test for placeholders. 3404 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3405 if (PR.isInvalid()) return QualType(); 3406 if (PR.get() != V.get()) { 3407 V = PR; 3408 return CheckRealImagOperand(S, V, Loc, IsReal); 3409 } 3410 3411 // Reject anything else. 3412 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3413 << (IsReal ? "__real" : "__imag"); 3414 return QualType(); 3415 } 3416 3417 3418 3419 ExprResult 3420 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3421 tok::TokenKind Kind, Expr *Input) { 3422 UnaryOperatorKind Opc; 3423 switch (Kind) { 3424 default: llvm_unreachable("Unknown unary op!"); 3425 case tok::plusplus: Opc = UO_PostInc; break; 3426 case tok::minusminus: Opc = UO_PostDec; break; 3427 } 3428 3429 // Since this might is a postfix expression, get rid of ParenListExprs. 3430 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3431 if (Result.isInvalid()) return ExprError(); 3432 Input = Result.take(); 3433 3434 return BuildUnaryOp(S, OpLoc, Opc, Input); 3435 } 3436 3437 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3438 /// 3439 /// \return true on error 3440 static bool checkArithmeticOnObjCPointer(Sema &S, 3441 SourceLocation opLoc, 3442 Expr *op) { 3443 assert(op->getType()->isObjCObjectPointerType()); 3444 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3445 return false; 3446 3447 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3448 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3449 << op->getSourceRange(); 3450 return true; 3451 } 3452 3453 ExprResult 3454 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3455 Expr *idx, SourceLocation rbLoc) { 3456 // Since this might be a postfix expression, get rid of ParenListExprs. 3457 if (isa<ParenListExpr>(base)) { 3458 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3459 if (result.isInvalid()) return ExprError(); 3460 base = result.take(); 3461 } 3462 3463 // Handle any non-overload placeholder types in the base and index 3464 // expressions. We can't handle overloads here because the other 3465 // operand might be an overloadable type, in which case the overload 3466 // resolution for the operator overload should get the first crack 3467 // at the overload. 3468 if (base->getType()->isNonOverloadPlaceholderType()) { 3469 ExprResult result = CheckPlaceholderExpr(base); 3470 if (result.isInvalid()) return ExprError(); 3471 base = result.take(); 3472 } 3473 if (idx->getType()->isNonOverloadPlaceholderType()) { 3474 ExprResult result = CheckPlaceholderExpr(idx); 3475 if (result.isInvalid()) return ExprError(); 3476 idx = result.take(); 3477 } 3478 3479 // Build an unanalyzed expression if either operand is type-dependent. 3480 if (getLangOpts().CPlusPlus && 3481 (base->isTypeDependent() || idx->isTypeDependent())) { 3482 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3483 Context.DependentTy, 3484 VK_LValue, OK_Ordinary, 3485 rbLoc)); 3486 } 3487 3488 // Use C++ overloaded-operator rules if either operand has record 3489 // type. The spec says to do this if either type is *overloadable*, 3490 // but enum types can't declare subscript operators or conversion 3491 // operators, so there's nothing interesting for overload resolution 3492 // to do if there aren't any record types involved. 3493 // 3494 // ObjC pointers have their own subscripting logic that is not tied 3495 // to overload resolution and so should not take this path. 3496 if (getLangOpts().CPlusPlus && 3497 (base->getType()->isRecordType() || 3498 (!base->getType()->isObjCObjectPointerType() && 3499 idx->getType()->isRecordType()))) { 3500 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3501 } 3502 3503 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3504 } 3505 3506 ExprResult 3507 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3508 Expr *Idx, SourceLocation RLoc) { 3509 Expr *LHSExp = Base; 3510 Expr *RHSExp = Idx; 3511 3512 // Perform default conversions. 3513 if (!LHSExp->getType()->getAs<VectorType>()) { 3514 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3515 if (Result.isInvalid()) 3516 return ExprError(); 3517 LHSExp = Result.take(); 3518 } 3519 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3520 if (Result.isInvalid()) 3521 return ExprError(); 3522 RHSExp = Result.take(); 3523 3524 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3525 ExprValueKind VK = VK_LValue; 3526 ExprObjectKind OK = OK_Ordinary; 3527 3528 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3529 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3530 // in the subscript position. As a result, we need to derive the array base 3531 // and index from the expression types. 3532 Expr *BaseExpr, *IndexExpr; 3533 QualType ResultType; 3534 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3535 BaseExpr = LHSExp; 3536 IndexExpr = RHSExp; 3537 ResultType = Context.DependentTy; 3538 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3539 BaseExpr = LHSExp; 3540 IndexExpr = RHSExp; 3541 ResultType = PTy->getPointeeType(); 3542 } else if (const ObjCObjectPointerType *PTy = 3543 LHSTy->getAs<ObjCObjectPointerType>()) { 3544 BaseExpr = LHSExp; 3545 IndexExpr = RHSExp; 3546 3547 // Use custom logic if this should be the pseudo-object subscript 3548 // expression. 3549 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3550 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3551 3552 ResultType = PTy->getPointeeType(); 3553 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3554 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3555 << ResultType << BaseExpr->getSourceRange(); 3556 return ExprError(); 3557 } 3558 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3559 // Handle the uncommon case of "123[Ptr]". 3560 BaseExpr = RHSExp; 3561 IndexExpr = LHSExp; 3562 ResultType = PTy->getPointeeType(); 3563 } else if (const ObjCObjectPointerType *PTy = 3564 RHSTy->getAs<ObjCObjectPointerType>()) { 3565 // Handle the uncommon case of "123[Ptr]". 3566 BaseExpr = RHSExp; 3567 IndexExpr = LHSExp; 3568 ResultType = PTy->getPointeeType(); 3569 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3570 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3571 << ResultType << BaseExpr->getSourceRange(); 3572 return ExprError(); 3573 } 3574 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3575 BaseExpr = LHSExp; // vectors: V[123] 3576 IndexExpr = RHSExp; 3577 VK = LHSExp->getValueKind(); 3578 if (VK != VK_RValue) 3579 OK = OK_VectorComponent; 3580 3581 // FIXME: need to deal with const... 3582 ResultType = VTy->getElementType(); 3583 } else if (LHSTy->isArrayType()) { 3584 // If we see an array that wasn't promoted by 3585 // DefaultFunctionArrayLvalueConversion, it must be an array that 3586 // wasn't promoted because of the C90 rule that doesn't 3587 // allow promoting non-lvalue arrays. Warn, then 3588 // force the promotion here. 3589 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3590 LHSExp->getSourceRange(); 3591 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3592 CK_ArrayToPointerDecay).take(); 3593 LHSTy = LHSExp->getType(); 3594 3595 BaseExpr = LHSExp; 3596 IndexExpr = RHSExp; 3597 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3598 } else if (RHSTy->isArrayType()) { 3599 // Same as previous, except for 123[f().a] case 3600 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3601 RHSExp->getSourceRange(); 3602 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3603 CK_ArrayToPointerDecay).take(); 3604 RHSTy = RHSExp->getType(); 3605 3606 BaseExpr = RHSExp; 3607 IndexExpr = LHSExp; 3608 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3609 } else { 3610 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3611 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3612 } 3613 // C99 6.5.2.1p1 3614 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3615 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3616 << IndexExpr->getSourceRange()); 3617 3618 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3619 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3620 && !IndexExpr->isTypeDependent()) 3621 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3622 3623 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3624 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3625 // type. Note that Functions are not objects, and that (in C99 parlance) 3626 // incomplete types are not object types. 3627 if (ResultType->isFunctionType()) { 3628 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3629 << ResultType << BaseExpr->getSourceRange(); 3630 return ExprError(); 3631 } 3632 3633 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3634 // GNU extension: subscripting on pointer to void 3635 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3636 << BaseExpr->getSourceRange(); 3637 3638 // C forbids expressions of unqualified void type from being l-values. 3639 // See IsCForbiddenLValueType. 3640 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3641 } else if (!ResultType->isDependentType() && 3642 RequireCompleteType(LLoc, ResultType, 3643 diag::err_subscript_incomplete_type, BaseExpr)) 3644 return ExprError(); 3645 3646 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3647 !ResultType.isCForbiddenLValueType()); 3648 3649 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3650 ResultType, VK, OK, RLoc)); 3651 } 3652 3653 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3654 FunctionDecl *FD, 3655 ParmVarDecl *Param) { 3656 if (Param->hasUnparsedDefaultArg()) { 3657 Diag(CallLoc, 3658 diag::err_use_of_default_argument_to_function_declared_later) << 3659 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3660 Diag(UnparsedDefaultArgLocs[Param], 3661 diag::note_default_argument_declared_here); 3662 return ExprError(); 3663 } 3664 3665 if (Param->hasUninstantiatedDefaultArg()) { 3666 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3667 3668 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3669 Param); 3670 3671 // Instantiate the expression. 3672 MultiLevelTemplateArgumentList ArgList 3673 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3674 3675 std::pair<const TemplateArgument *, unsigned> Innermost 3676 = ArgList.getInnermost(); 3677 InstantiatingTemplate Inst(*this, CallLoc, Param, 3678 ArrayRef<TemplateArgument>(Innermost.first, 3679 Innermost.second)); 3680 if (Inst) 3681 return ExprError(); 3682 3683 ExprResult Result; 3684 { 3685 // C++ [dcl.fct.default]p5: 3686 // The names in the [default argument] expression are bound, and 3687 // the semantic constraints are checked, at the point where the 3688 // default argument expression appears. 3689 ContextRAII SavedContext(*this, FD); 3690 LocalInstantiationScope Local(*this); 3691 Result = SubstExpr(UninstExpr, ArgList); 3692 } 3693 if (Result.isInvalid()) 3694 return ExprError(); 3695 3696 // Check the expression as an initializer for the parameter. 3697 InitializedEntity Entity 3698 = InitializedEntity::InitializeParameter(Context, Param); 3699 InitializationKind Kind 3700 = InitializationKind::CreateCopy(Param->getLocation(), 3701 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3702 Expr *ResultE = Result.takeAs<Expr>(); 3703 3704 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3705 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3706 if (Result.isInvalid()) 3707 return ExprError(); 3708 3709 Expr *Arg = Result.takeAs<Expr>(); 3710 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3711 // Build the default argument expression. 3712 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3713 } 3714 3715 // If the default expression creates temporaries, we need to 3716 // push them to the current stack of expression temporaries so they'll 3717 // be properly destroyed. 3718 // FIXME: We should really be rebuilding the default argument with new 3719 // bound temporaries; see the comment in PR5810. 3720 // We don't need to do that with block decls, though, because 3721 // blocks in default argument expression can never capture anything. 3722 if (isa<ExprWithCleanups>(Param->getInit())) { 3723 // Set the "needs cleanups" bit regardless of whether there are 3724 // any explicit objects. 3725 ExprNeedsCleanups = true; 3726 3727 // Append all the objects to the cleanup list. Right now, this 3728 // should always be a no-op, because blocks in default argument 3729 // expressions should never be able to capture anything. 3730 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3731 "default argument expression has capturing blocks?"); 3732 } 3733 3734 // We already type-checked the argument, so we know it works. 3735 // Just mark all of the declarations in this potentially-evaluated expression 3736 // as being "referenced". 3737 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3738 /*SkipLocalVariables=*/true); 3739 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3740 } 3741 3742 3743 Sema::VariadicCallType 3744 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3745 Expr *Fn) { 3746 if (Proto && Proto->isVariadic()) { 3747 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3748 return VariadicConstructor; 3749 else if (Fn && Fn->getType()->isBlockPointerType()) 3750 return VariadicBlock; 3751 else if (FDecl) { 3752 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3753 if (Method->isInstance()) 3754 return VariadicMethod; 3755 } 3756 return VariadicFunction; 3757 } 3758 return VariadicDoesNotApply; 3759 } 3760 3761 /// ConvertArgumentsForCall - Converts the arguments specified in 3762 /// Args/NumArgs to the parameter types of the function FDecl with 3763 /// function prototype Proto. Call is the call expression itself, and 3764 /// Fn is the function expression. For a C++ member function, this 3765 /// routine does not attempt to convert the object argument. Returns 3766 /// true if the call is ill-formed. 3767 bool 3768 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3769 FunctionDecl *FDecl, 3770 const FunctionProtoType *Proto, 3771 Expr **Args, unsigned NumArgs, 3772 SourceLocation RParenLoc, 3773 bool IsExecConfig) { 3774 // Bail out early if calling a builtin with custom typechecking. 3775 // We don't need to do this in the 3776 if (FDecl) 3777 if (unsigned ID = FDecl->getBuiltinID()) 3778 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3779 return false; 3780 3781 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3782 // assignment, to the types of the corresponding parameter, ... 3783 unsigned NumArgsInProto = Proto->getNumArgs(); 3784 bool Invalid = false; 3785 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3786 unsigned FnKind = Fn->getType()->isBlockPointerType() 3787 ? 1 /* block */ 3788 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3789 : 0 /* function */); 3790 3791 // If too few arguments are available (and we don't have default 3792 // arguments for the remaining parameters), don't make the call. 3793 if (NumArgs < NumArgsInProto) { 3794 if (NumArgs < MinArgs) { 3795 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3796 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3797 ? diag::err_typecheck_call_too_few_args_one 3798 : diag::err_typecheck_call_too_few_args_at_least_one) 3799 << FnKind 3800 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 3801 else 3802 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3803 ? diag::err_typecheck_call_too_few_args 3804 : diag::err_typecheck_call_too_few_args_at_least) 3805 << FnKind 3806 << MinArgs << NumArgs << Fn->getSourceRange(); 3807 3808 // Emit the location of the prototype. 3809 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3810 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3811 << FDecl; 3812 3813 return true; 3814 } 3815 Call->setNumArgs(Context, NumArgsInProto); 3816 } 3817 3818 // If too many are passed and not variadic, error on the extras and drop 3819 // them. 3820 if (NumArgs > NumArgsInProto) { 3821 if (!Proto->isVariadic()) { 3822 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3823 Diag(Args[NumArgsInProto]->getLocStart(), 3824 MinArgs == NumArgsInProto 3825 ? diag::err_typecheck_call_too_many_args_one 3826 : diag::err_typecheck_call_too_many_args_at_most_one) 3827 << FnKind 3828 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange() 3829 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3830 Args[NumArgs-1]->getLocEnd()); 3831 else 3832 Diag(Args[NumArgsInProto]->getLocStart(), 3833 MinArgs == NumArgsInProto 3834 ? diag::err_typecheck_call_too_many_args 3835 : diag::err_typecheck_call_too_many_args_at_most) 3836 << FnKind 3837 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3838 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3839 Args[NumArgs-1]->getLocEnd()); 3840 3841 // Emit the location of the prototype. 3842 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3843 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3844 << FDecl; 3845 3846 // This deletes the extra arguments. 3847 Call->setNumArgs(Context, NumArgsInProto); 3848 return true; 3849 } 3850 } 3851 SmallVector<Expr *, 8> AllArgs; 3852 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 3853 3854 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3855 Proto, 0, Args, NumArgs, AllArgs, CallType); 3856 if (Invalid) 3857 return true; 3858 unsigned TotalNumArgs = AllArgs.size(); 3859 for (unsigned i = 0; i < TotalNumArgs; ++i) 3860 Call->setArg(i, AllArgs[i]); 3861 3862 return false; 3863 } 3864 3865 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3866 FunctionDecl *FDecl, 3867 const FunctionProtoType *Proto, 3868 unsigned FirstProtoArg, 3869 Expr **Args, unsigned NumArgs, 3870 SmallVector<Expr *, 8> &AllArgs, 3871 VariadicCallType CallType, 3872 bool AllowExplicit, 3873 bool IsListInitialization) { 3874 unsigned NumArgsInProto = Proto->getNumArgs(); 3875 unsigned NumArgsToCheck = NumArgs; 3876 bool Invalid = false; 3877 if (NumArgs != NumArgsInProto) 3878 // Use default arguments for missing arguments 3879 NumArgsToCheck = NumArgsInProto; 3880 unsigned ArgIx = 0; 3881 // Continue to check argument types (even if we have too few/many args). 3882 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3883 QualType ProtoArgType = Proto->getArgType(i); 3884 3885 Expr *Arg; 3886 ParmVarDecl *Param; 3887 if (ArgIx < NumArgs) { 3888 Arg = Args[ArgIx++]; 3889 3890 if (RequireCompleteType(Arg->getLocStart(), 3891 ProtoArgType, 3892 diag::err_call_incomplete_argument, Arg)) 3893 return true; 3894 3895 // Pass the argument 3896 Param = 0; 3897 if (FDecl && i < FDecl->getNumParams()) 3898 Param = FDecl->getParamDecl(i); 3899 3900 // Strip the unbridged-cast placeholder expression off, if applicable. 3901 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3902 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3903 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3904 Arg = stripARCUnbridgedCast(Arg); 3905 3906 InitializedEntity Entity = Param ? 3907 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 3908 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3909 Proto->isArgConsumed(i)); 3910 ExprResult ArgE = PerformCopyInitialization(Entity, 3911 SourceLocation(), 3912 Owned(Arg), 3913 IsListInitialization, 3914 AllowExplicit); 3915 if (ArgE.isInvalid()) 3916 return true; 3917 3918 Arg = ArgE.takeAs<Expr>(); 3919 } else { 3920 assert(FDecl && "can't use default arguments without a known callee"); 3921 Param = FDecl->getParamDecl(i); 3922 3923 ExprResult ArgExpr = 3924 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3925 if (ArgExpr.isInvalid()) 3926 return true; 3927 3928 Arg = ArgExpr.takeAs<Expr>(); 3929 } 3930 3931 // Check for array bounds violations for each argument to the call. This 3932 // check only triggers warnings when the argument isn't a more complex Expr 3933 // with its own checking, such as a BinaryOperator. 3934 CheckArrayAccess(Arg); 3935 3936 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3937 CheckStaticArrayArgument(CallLoc, Param, Arg); 3938 3939 AllArgs.push_back(Arg); 3940 } 3941 3942 // If this is a variadic call, handle args passed through "...". 3943 if (CallType != VariadicDoesNotApply) { 3944 // Assume that extern "C" functions with variadic arguments that 3945 // return __unknown_anytype aren't *really* variadic. 3946 if (Proto->getResultType() == Context.UnknownAnyTy && 3947 FDecl && FDecl->isExternC()) { 3948 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3949 QualType paramType; // ignored 3950 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 3951 Invalid |= arg.isInvalid(); 3952 AllArgs.push_back(arg.take()); 3953 } 3954 3955 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3956 } else { 3957 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3958 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3959 FDecl); 3960 Invalid |= Arg.isInvalid(); 3961 AllArgs.push_back(Arg.take()); 3962 } 3963 } 3964 3965 // Check for array bounds violations. 3966 for (unsigned i = ArgIx; i != NumArgs; ++i) 3967 CheckArrayAccess(Args[i]); 3968 } 3969 return Invalid; 3970 } 3971 3972 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 3973 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 3974 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 3975 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 3976 << ATL.getLocalSourceRange(); 3977 } 3978 3979 /// CheckStaticArrayArgument - If the given argument corresponds to a static 3980 /// array parameter, check that it is non-null, and that if it is formed by 3981 /// array-to-pointer decay, the underlying array is sufficiently large. 3982 /// 3983 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 3984 /// array type derivation, then for each call to the function, the value of the 3985 /// corresponding actual argument shall provide access to the first element of 3986 /// an array with at least as many elements as specified by the size expression. 3987 void 3988 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 3989 ParmVarDecl *Param, 3990 const Expr *ArgExpr) { 3991 // Static array parameters are not supported in C++. 3992 if (!Param || getLangOpts().CPlusPlus) 3993 return; 3994 3995 QualType OrigTy = Param->getOriginalType(); 3996 3997 const ArrayType *AT = Context.getAsArrayType(OrigTy); 3998 if (!AT || AT->getSizeModifier() != ArrayType::Static) 3999 return; 4000 4001 if (ArgExpr->isNullPointerConstant(Context, 4002 Expr::NPC_NeverValueDependent)) { 4003 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4004 DiagnoseCalleeStaticArrayParam(*this, Param); 4005 return; 4006 } 4007 4008 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4009 if (!CAT) 4010 return; 4011 4012 const ConstantArrayType *ArgCAT = 4013 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4014 if (!ArgCAT) 4015 return; 4016 4017 if (ArgCAT->getSize().ult(CAT->getSize())) { 4018 Diag(CallLoc, diag::warn_static_array_too_small) 4019 << ArgExpr->getSourceRange() 4020 << (unsigned) ArgCAT->getSize().getZExtValue() 4021 << (unsigned) CAT->getSize().getZExtValue(); 4022 DiagnoseCalleeStaticArrayParam(*this, Param); 4023 } 4024 } 4025 4026 /// Given a function expression of unknown-any type, try to rebuild it 4027 /// to have a function type. 4028 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4029 4030 /// Is the given type a placeholder that we need to lower out 4031 /// immediately during argument processing? 4032 static bool isPlaceholderToRemoveAsArg(QualType type) { 4033 // Placeholders are never sugared. 4034 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4035 if (!placeholder) return false; 4036 4037 switch (placeholder->getKind()) { 4038 // Ignore all the non-placeholder types. 4039 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4040 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4041 #include "clang/AST/BuiltinTypes.def" 4042 return false; 4043 4044 // We cannot lower out overload sets; they might validly be resolved 4045 // by the call machinery. 4046 case BuiltinType::Overload: 4047 return false; 4048 4049 // Unbridged casts in ARC can be handled in some call positions and 4050 // should be left in place. 4051 case BuiltinType::ARCUnbridgedCast: 4052 return false; 4053 4054 // Pseudo-objects should be converted as soon as possible. 4055 case BuiltinType::PseudoObject: 4056 return true; 4057 4058 // The debugger mode could theoretically but currently does not try 4059 // to resolve unknown-typed arguments based on known parameter types. 4060 case BuiltinType::UnknownAny: 4061 return true; 4062 4063 // These are always invalid as call arguments and should be reported. 4064 case BuiltinType::BoundMember: 4065 case BuiltinType::BuiltinFn: 4066 return true; 4067 } 4068 llvm_unreachable("bad builtin type kind"); 4069 } 4070 4071 /// Check an argument list for placeholders that we won't try to 4072 /// handle later. 4073 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4074 // Apply this processing to all the arguments at once instead of 4075 // dying at the first failure. 4076 bool hasInvalid = false; 4077 for (size_t i = 0, e = args.size(); i != e; i++) { 4078 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4079 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4080 if (result.isInvalid()) hasInvalid = true; 4081 else args[i] = result.take(); 4082 } 4083 } 4084 return hasInvalid; 4085 } 4086 4087 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4088 /// This provides the location of the left/right parens and a list of comma 4089 /// locations. 4090 ExprResult 4091 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4092 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4093 Expr *ExecConfig, bool IsExecConfig) { 4094 // Since this might be a postfix expression, get rid of ParenListExprs. 4095 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4096 if (Result.isInvalid()) return ExprError(); 4097 Fn = Result.take(); 4098 4099 if (checkArgsForPlaceholders(*this, ArgExprs)) 4100 return ExprError(); 4101 4102 if (getLangOpts().CPlusPlus) { 4103 // If this is a pseudo-destructor expression, build the call immediately. 4104 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4105 if (!ArgExprs.empty()) { 4106 // Pseudo-destructor calls should not have any arguments. 4107 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4108 << FixItHint::CreateRemoval( 4109 SourceRange(ArgExprs[0]->getLocStart(), 4110 ArgExprs.back()->getLocEnd())); 4111 } 4112 4113 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(), 4114 Context.VoidTy, VK_RValue, 4115 RParenLoc)); 4116 } 4117 if (Fn->getType() == Context.PseudoObjectTy) { 4118 ExprResult result = CheckPlaceholderExpr(Fn); 4119 if (result.isInvalid()) return ExprError(); 4120 Fn = result.take(); 4121 } 4122 4123 // Determine whether this is a dependent call inside a C++ template, 4124 // in which case we won't do any semantic analysis now. 4125 // FIXME: Will need to cache the results of name lookup (including ADL) in 4126 // Fn. 4127 bool Dependent = false; 4128 if (Fn->isTypeDependent()) 4129 Dependent = true; 4130 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4131 Dependent = true; 4132 4133 if (Dependent) { 4134 if (ExecConfig) { 4135 return Owned(new (Context) CUDAKernelCallExpr( 4136 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4137 Context.DependentTy, VK_RValue, RParenLoc)); 4138 } else { 4139 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4140 Context.DependentTy, VK_RValue, 4141 RParenLoc)); 4142 } 4143 } 4144 4145 // Determine whether this is a call to an object (C++ [over.call.object]). 4146 if (Fn->getType()->isRecordType()) 4147 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4148 ArgExprs.data(), 4149 ArgExprs.size(), RParenLoc)); 4150 4151 if (Fn->getType() == Context.UnknownAnyTy) { 4152 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4153 if (result.isInvalid()) return ExprError(); 4154 Fn = result.take(); 4155 } 4156 4157 if (Fn->getType() == Context.BoundMemberTy) { 4158 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 4159 ArgExprs.size(), RParenLoc); 4160 } 4161 } 4162 4163 // Check for overloaded calls. This can happen even in C due to extensions. 4164 if (Fn->getType() == Context.OverloadTy) { 4165 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4166 4167 // We aren't supposed to apply this logic for if there's an '&' involved. 4168 if (!find.HasFormOfMemberPointer) { 4169 OverloadExpr *ovl = find.Expression; 4170 if (isa<UnresolvedLookupExpr>(ovl)) { 4171 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4172 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(), 4173 ArgExprs.size(), RParenLoc, ExecConfig); 4174 } else { 4175 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 4176 ArgExprs.size(), RParenLoc); 4177 } 4178 } 4179 } 4180 4181 // If we're directly calling a function, get the appropriate declaration. 4182 if (Fn->getType() == Context.UnknownAnyTy) { 4183 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4184 if (result.isInvalid()) return ExprError(); 4185 Fn = result.take(); 4186 } 4187 4188 Expr *NakedFn = Fn->IgnoreParens(); 4189 4190 NamedDecl *NDecl = 0; 4191 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4192 if (UnOp->getOpcode() == UO_AddrOf) 4193 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4194 4195 if (isa<DeclRefExpr>(NakedFn)) 4196 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4197 else if (isa<MemberExpr>(NakedFn)) 4198 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4199 4200 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(), 4201 ArgExprs.size(), RParenLoc, ExecConfig, 4202 IsExecConfig); 4203 } 4204 4205 ExprResult 4206 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4207 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4208 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4209 if (!ConfigDecl) 4210 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4211 << "cudaConfigureCall"); 4212 QualType ConfigQTy = ConfigDecl->getType(); 4213 4214 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4215 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4216 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4217 4218 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4219 /*IsExecConfig=*/true); 4220 } 4221 4222 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4223 /// 4224 /// __builtin_astype( value, dst type ) 4225 /// 4226 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4227 SourceLocation BuiltinLoc, 4228 SourceLocation RParenLoc) { 4229 ExprValueKind VK = VK_RValue; 4230 ExprObjectKind OK = OK_Ordinary; 4231 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4232 QualType SrcTy = E->getType(); 4233 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4234 return ExprError(Diag(BuiltinLoc, 4235 diag::err_invalid_astype_of_different_size) 4236 << DstTy 4237 << SrcTy 4238 << E->getSourceRange()); 4239 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4240 RParenLoc)); 4241 } 4242 4243 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4244 /// i.e. an expression not of \p OverloadTy. The expression should 4245 /// unary-convert to an expression of function-pointer or 4246 /// block-pointer type. 4247 /// 4248 /// \param NDecl the declaration being called, if available 4249 ExprResult 4250 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4251 SourceLocation LParenLoc, 4252 Expr **Args, unsigned NumArgs, 4253 SourceLocation RParenLoc, 4254 Expr *Config, bool IsExecConfig) { 4255 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4256 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4257 4258 // Promote the function operand. 4259 // We special-case function promotion here because we only allow promoting 4260 // builtin functions to function pointers in the callee of a call. 4261 ExprResult Result; 4262 if (BuiltinID && 4263 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4264 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4265 CK_BuiltinFnToFnPtr).take(); 4266 } else { 4267 Result = UsualUnaryConversions(Fn); 4268 } 4269 if (Result.isInvalid()) 4270 return ExprError(); 4271 Fn = Result.take(); 4272 4273 // Make the call expr early, before semantic checks. This guarantees cleanup 4274 // of arguments and function on error. 4275 CallExpr *TheCall; 4276 if (Config) 4277 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4278 cast<CallExpr>(Config), 4279 llvm::makeArrayRef(Args,NumArgs), 4280 Context.BoolTy, 4281 VK_RValue, 4282 RParenLoc); 4283 else 4284 TheCall = new (Context) CallExpr(Context, Fn, 4285 llvm::makeArrayRef(Args, NumArgs), 4286 Context.BoolTy, 4287 VK_RValue, 4288 RParenLoc); 4289 4290 // Bail out early if calling a builtin with custom typechecking. 4291 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4292 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4293 4294 retry: 4295 const FunctionType *FuncT; 4296 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4297 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4298 // have type pointer to function". 4299 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4300 if (FuncT == 0) 4301 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4302 << Fn->getType() << Fn->getSourceRange()); 4303 } else if (const BlockPointerType *BPT = 4304 Fn->getType()->getAs<BlockPointerType>()) { 4305 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4306 } else { 4307 // Handle calls to expressions of unknown-any type. 4308 if (Fn->getType() == Context.UnknownAnyTy) { 4309 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4310 if (rewrite.isInvalid()) return ExprError(); 4311 Fn = rewrite.take(); 4312 TheCall->setCallee(Fn); 4313 goto retry; 4314 } 4315 4316 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4317 << Fn->getType() << Fn->getSourceRange()); 4318 } 4319 4320 if (getLangOpts().CUDA) { 4321 if (Config) { 4322 // CUDA: Kernel calls must be to global functions 4323 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4324 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4325 << FDecl->getName() << Fn->getSourceRange()); 4326 4327 // CUDA: Kernel function must have 'void' return type 4328 if (!FuncT->getResultType()->isVoidType()) 4329 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4330 << Fn->getType() << Fn->getSourceRange()); 4331 } else { 4332 // CUDA: Calls to global functions must be configured 4333 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4334 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4335 << FDecl->getName() << Fn->getSourceRange()); 4336 } 4337 } 4338 4339 // Check for a valid return type 4340 if (CheckCallReturnType(FuncT->getResultType(), 4341 Fn->getLocStart(), TheCall, 4342 FDecl)) 4343 return ExprError(); 4344 4345 // We know the result type of the call, set it. 4346 TheCall->setType(FuncT->getCallResultType(Context)); 4347 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4348 4349 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4350 if (Proto) { 4351 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 4352 RParenLoc, IsExecConfig)) 4353 return ExprError(); 4354 } else { 4355 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4356 4357 if (FDecl) { 4358 // Check if we have too few/too many template arguments, based 4359 // on our knowledge of the function definition. 4360 const FunctionDecl *Def = 0; 4361 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 4362 Proto = Def->getType()->getAs<FunctionProtoType>(); 4363 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 4364 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4365 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 4366 } 4367 4368 // If the function we're calling isn't a function prototype, but we have 4369 // a function prototype from a prior declaratiom, use that prototype. 4370 if (!FDecl->hasPrototype()) 4371 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4372 } 4373 4374 // Promote the arguments (C99 6.5.2.2p6). 4375 for (unsigned i = 0; i != NumArgs; i++) { 4376 Expr *Arg = Args[i]; 4377 4378 if (Proto && i < Proto->getNumArgs()) { 4379 InitializedEntity Entity 4380 = InitializedEntity::InitializeParameter(Context, 4381 Proto->getArgType(i), 4382 Proto->isArgConsumed(i)); 4383 ExprResult ArgE = PerformCopyInitialization(Entity, 4384 SourceLocation(), 4385 Owned(Arg)); 4386 if (ArgE.isInvalid()) 4387 return true; 4388 4389 Arg = ArgE.takeAs<Expr>(); 4390 4391 } else { 4392 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4393 4394 if (ArgE.isInvalid()) 4395 return true; 4396 4397 Arg = ArgE.takeAs<Expr>(); 4398 } 4399 4400 if (RequireCompleteType(Arg->getLocStart(), 4401 Arg->getType(), 4402 diag::err_call_incomplete_argument, Arg)) 4403 return ExprError(); 4404 4405 TheCall->setArg(i, Arg); 4406 } 4407 } 4408 4409 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4410 if (!Method->isStatic()) 4411 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4412 << Fn->getSourceRange()); 4413 4414 // Check for sentinels 4415 if (NDecl) 4416 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 4417 4418 // Do special checking on direct calls to functions. 4419 if (FDecl) { 4420 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4421 return ExprError(); 4422 4423 if (BuiltinID) 4424 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4425 } else if (NDecl) { 4426 if (CheckBlockCall(NDecl, TheCall, Proto)) 4427 return ExprError(); 4428 } 4429 4430 return MaybeBindToTemporary(TheCall); 4431 } 4432 4433 ExprResult 4434 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4435 SourceLocation RParenLoc, Expr *InitExpr) { 4436 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 4437 // FIXME: put back this assert when initializers are worked out. 4438 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4439 4440 TypeSourceInfo *TInfo; 4441 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4442 if (!TInfo) 4443 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4444 4445 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4446 } 4447 4448 ExprResult 4449 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4450 SourceLocation RParenLoc, Expr *LiteralExpr) { 4451 QualType literalType = TInfo->getType(); 4452 4453 if (literalType->isArrayType()) { 4454 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4455 diag::err_illegal_decl_array_incomplete_type, 4456 SourceRange(LParenLoc, 4457 LiteralExpr->getSourceRange().getEnd()))) 4458 return ExprError(); 4459 if (literalType->isVariableArrayType()) 4460 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4461 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4462 } else if (!literalType->isDependentType() && 4463 RequireCompleteType(LParenLoc, literalType, 4464 diag::err_typecheck_decl_incomplete_type, 4465 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4466 return ExprError(); 4467 4468 InitializedEntity Entity 4469 = InitializedEntity::InitializeTemporary(literalType); 4470 InitializationKind Kind 4471 = InitializationKind::CreateCStyleCast(LParenLoc, 4472 SourceRange(LParenLoc, RParenLoc), 4473 /*InitList=*/true); 4474 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1); 4475 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4476 &literalType); 4477 if (Result.isInvalid()) 4478 return ExprError(); 4479 LiteralExpr = Result.get(); 4480 4481 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4482 if (isFileScope) { // 6.5.2.5p3 4483 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4484 return ExprError(); 4485 } 4486 4487 // In C, compound literals are l-values for some reason. 4488 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4489 4490 return MaybeBindToTemporary( 4491 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4492 VK, LiteralExpr, isFileScope)); 4493 } 4494 4495 ExprResult 4496 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4497 SourceLocation RBraceLoc) { 4498 // Immediately handle non-overload placeholders. Overloads can be 4499 // resolved contextually, but everything else here can't. 4500 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4501 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4502 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4503 4504 // Ignore failures; dropping the entire initializer list because 4505 // of one failure would be terrible for indexing/etc. 4506 if (result.isInvalid()) continue; 4507 4508 InitArgList[I] = result.take(); 4509 } 4510 } 4511 4512 // Semantic analysis for initializers is done by ActOnDeclarator() and 4513 // CheckInitializer() - it requires knowledge of the object being intialized. 4514 4515 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4516 RBraceLoc); 4517 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4518 return Owned(E); 4519 } 4520 4521 /// Do an explicit extend of the given block pointer if we're in ARC. 4522 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4523 assert(E.get()->getType()->isBlockPointerType()); 4524 assert(E.get()->isRValue()); 4525 4526 // Only do this in an r-value context. 4527 if (!S.getLangOpts().ObjCAutoRefCount) return; 4528 4529 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4530 CK_ARCExtendBlockObject, E.get(), 4531 /*base path*/ 0, VK_RValue); 4532 S.ExprNeedsCleanups = true; 4533 } 4534 4535 /// Prepare a conversion of the given expression to an ObjC object 4536 /// pointer type. 4537 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4538 QualType type = E.get()->getType(); 4539 if (type->isObjCObjectPointerType()) { 4540 return CK_BitCast; 4541 } else if (type->isBlockPointerType()) { 4542 maybeExtendBlockObject(*this, E); 4543 return CK_BlockPointerToObjCPointerCast; 4544 } else { 4545 assert(type->isPointerType()); 4546 return CK_CPointerToObjCPointerCast; 4547 } 4548 } 4549 4550 /// Prepares for a scalar cast, performing all the necessary stages 4551 /// except the final cast and returning the kind required. 4552 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4553 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4554 // Also, callers should have filtered out the invalid cases with 4555 // pointers. Everything else should be possible. 4556 4557 QualType SrcTy = Src.get()->getType(); 4558 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4559 return CK_NoOp; 4560 4561 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4562 case Type::STK_MemberPointer: 4563 llvm_unreachable("member pointer type in C"); 4564 4565 case Type::STK_CPointer: 4566 case Type::STK_BlockPointer: 4567 case Type::STK_ObjCObjectPointer: 4568 switch (DestTy->getScalarTypeKind()) { 4569 case Type::STK_CPointer: 4570 return CK_BitCast; 4571 case Type::STK_BlockPointer: 4572 return (SrcKind == Type::STK_BlockPointer 4573 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4574 case Type::STK_ObjCObjectPointer: 4575 if (SrcKind == Type::STK_ObjCObjectPointer) 4576 return CK_BitCast; 4577 if (SrcKind == Type::STK_CPointer) 4578 return CK_CPointerToObjCPointerCast; 4579 maybeExtendBlockObject(*this, Src); 4580 return CK_BlockPointerToObjCPointerCast; 4581 case Type::STK_Bool: 4582 return CK_PointerToBoolean; 4583 case Type::STK_Integral: 4584 return CK_PointerToIntegral; 4585 case Type::STK_Floating: 4586 case Type::STK_FloatingComplex: 4587 case Type::STK_IntegralComplex: 4588 case Type::STK_MemberPointer: 4589 llvm_unreachable("illegal cast from pointer"); 4590 } 4591 llvm_unreachable("Should have returned before this"); 4592 4593 case Type::STK_Bool: // casting from bool is like casting from an integer 4594 case Type::STK_Integral: 4595 switch (DestTy->getScalarTypeKind()) { 4596 case Type::STK_CPointer: 4597 case Type::STK_ObjCObjectPointer: 4598 case Type::STK_BlockPointer: 4599 if (Src.get()->isNullPointerConstant(Context, 4600 Expr::NPC_ValueDependentIsNull)) 4601 return CK_NullToPointer; 4602 return CK_IntegralToPointer; 4603 case Type::STK_Bool: 4604 return CK_IntegralToBoolean; 4605 case Type::STK_Integral: 4606 return CK_IntegralCast; 4607 case Type::STK_Floating: 4608 return CK_IntegralToFloating; 4609 case Type::STK_IntegralComplex: 4610 Src = ImpCastExprToType(Src.take(), 4611 DestTy->castAs<ComplexType>()->getElementType(), 4612 CK_IntegralCast); 4613 return CK_IntegralRealToComplex; 4614 case Type::STK_FloatingComplex: 4615 Src = ImpCastExprToType(Src.take(), 4616 DestTy->castAs<ComplexType>()->getElementType(), 4617 CK_IntegralToFloating); 4618 return CK_FloatingRealToComplex; 4619 case Type::STK_MemberPointer: 4620 llvm_unreachable("member pointer type in C"); 4621 } 4622 llvm_unreachable("Should have returned before this"); 4623 4624 case Type::STK_Floating: 4625 switch (DestTy->getScalarTypeKind()) { 4626 case Type::STK_Floating: 4627 return CK_FloatingCast; 4628 case Type::STK_Bool: 4629 return CK_FloatingToBoolean; 4630 case Type::STK_Integral: 4631 return CK_FloatingToIntegral; 4632 case Type::STK_FloatingComplex: 4633 Src = ImpCastExprToType(Src.take(), 4634 DestTy->castAs<ComplexType>()->getElementType(), 4635 CK_FloatingCast); 4636 return CK_FloatingRealToComplex; 4637 case Type::STK_IntegralComplex: 4638 Src = ImpCastExprToType(Src.take(), 4639 DestTy->castAs<ComplexType>()->getElementType(), 4640 CK_FloatingToIntegral); 4641 return CK_IntegralRealToComplex; 4642 case Type::STK_CPointer: 4643 case Type::STK_ObjCObjectPointer: 4644 case Type::STK_BlockPointer: 4645 llvm_unreachable("valid float->pointer cast?"); 4646 case Type::STK_MemberPointer: 4647 llvm_unreachable("member pointer type in C"); 4648 } 4649 llvm_unreachable("Should have returned before this"); 4650 4651 case Type::STK_FloatingComplex: 4652 switch (DestTy->getScalarTypeKind()) { 4653 case Type::STK_FloatingComplex: 4654 return CK_FloatingComplexCast; 4655 case Type::STK_IntegralComplex: 4656 return CK_FloatingComplexToIntegralComplex; 4657 case Type::STK_Floating: { 4658 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4659 if (Context.hasSameType(ET, DestTy)) 4660 return CK_FloatingComplexToReal; 4661 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4662 return CK_FloatingCast; 4663 } 4664 case Type::STK_Bool: 4665 return CK_FloatingComplexToBoolean; 4666 case Type::STK_Integral: 4667 Src = ImpCastExprToType(Src.take(), 4668 SrcTy->castAs<ComplexType>()->getElementType(), 4669 CK_FloatingComplexToReal); 4670 return CK_FloatingToIntegral; 4671 case Type::STK_CPointer: 4672 case Type::STK_ObjCObjectPointer: 4673 case Type::STK_BlockPointer: 4674 llvm_unreachable("valid complex float->pointer cast?"); 4675 case Type::STK_MemberPointer: 4676 llvm_unreachable("member pointer type in C"); 4677 } 4678 llvm_unreachable("Should have returned before this"); 4679 4680 case Type::STK_IntegralComplex: 4681 switch (DestTy->getScalarTypeKind()) { 4682 case Type::STK_FloatingComplex: 4683 return CK_IntegralComplexToFloatingComplex; 4684 case Type::STK_IntegralComplex: 4685 return CK_IntegralComplexCast; 4686 case Type::STK_Integral: { 4687 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4688 if (Context.hasSameType(ET, DestTy)) 4689 return CK_IntegralComplexToReal; 4690 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4691 return CK_IntegralCast; 4692 } 4693 case Type::STK_Bool: 4694 return CK_IntegralComplexToBoolean; 4695 case Type::STK_Floating: 4696 Src = ImpCastExprToType(Src.take(), 4697 SrcTy->castAs<ComplexType>()->getElementType(), 4698 CK_IntegralComplexToReal); 4699 return CK_IntegralToFloating; 4700 case Type::STK_CPointer: 4701 case Type::STK_ObjCObjectPointer: 4702 case Type::STK_BlockPointer: 4703 llvm_unreachable("valid complex int->pointer cast?"); 4704 case Type::STK_MemberPointer: 4705 llvm_unreachable("member pointer type in C"); 4706 } 4707 llvm_unreachable("Should have returned before this"); 4708 } 4709 4710 llvm_unreachable("Unhandled scalar cast"); 4711 } 4712 4713 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4714 CastKind &Kind) { 4715 assert(VectorTy->isVectorType() && "Not a vector type!"); 4716 4717 if (Ty->isVectorType() || Ty->isIntegerType()) { 4718 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4719 return Diag(R.getBegin(), 4720 Ty->isVectorType() ? 4721 diag::err_invalid_conversion_between_vectors : 4722 diag::err_invalid_conversion_between_vector_and_integer) 4723 << VectorTy << Ty << R; 4724 } else 4725 return Diag(R.getBegin(), 4726 diag::err_invalid_conversion_between_vector_and_scalar) 4727 << VectorTy << Ty << R; 4728 4729 Kind = CK_BitCast; 4730 return false; 4731 } 4732 4733 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4734 Expr *CastExpr, CastKind &Kind) { 4735 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4736 4737 QualType SrcTy = CastExpr->getType(); 4738 4739 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4740 // an ExtVectorType. 4741 // In OpenCL, casts between vectors of different types are not allowed. 4742 // (See OpenCL 6.2). 4743 if (SrcTy->isVectorType()) { 4744 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4745 || (getLangOpts().OpenCL && 4746 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4747 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4748 << DestTy << SrcTy << R; 4749 return ExprError(); 4750 } 4751 Kind = CK_BitCast; 4752 return Owned(CastExpr); 4753 } 4754 4755 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4756 // conversion will take place first from scalar to elt type, and then 4757 // splat from elt type to vector. 4758 if (SrcTy->isPointerType()) 4759 return Diag(R.getBegin(), 4760 diag::err_invalid_conversion_between_vector_and_scalar) 4761 << DestTy << SrcTy << R; 4762 4763 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4764 ExprResult CastExprRes = Owned(CastExpr); 4765 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4766 if (CastExprRes.isInvalid()) 4767 return ExprError(); 4768 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4769 4770 Kind = CK_VectorSplat; 4771 return Owned(CastExpr); 4772 } 4773 4774 ExprResult 4775 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4776 Declarator &D, ParsedType &Ty, 4777 SourceLocation RParenLoc, Expr *CastExpr) { 4778 assert(!D.isInvalidType() && (CastExpr != 0) && 4779 "ActOnCastExpr(): missing type or expr"); 4780 4781 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4782 if (D.isInvalidType()) 4783 return ExprError(); 4784 4785 if (getLangOpts().CPlusPlus) { 4786 // Check that there are no default arguments (C++ only). 4787 CheckExtraCXXDefaultArguments(D); 4788 } 4789 4790 checkUnusedDeclAttributes(D); 4791 4792 QualType castType = castTInfo->getType(); 4793 Ty = CreateParsedType(castType, castTInfo); 4794 4795 bool isVectorLiteral = false; 4796 4797 // Check for an altivec or OpenCL literal, 4798 // i.e. all the elements are integer constants. 4799 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4800 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4801 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4802 && castType->isVectorType() && (PE || PLE)) { 4803 if (PLE && PLE->getNumExprs() == 0) { 4804 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4805 return ExprError(); 4806 } 4807 if (PE || PLE->getNumExprs() == 1) { 4808 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4809 if (!E->getType()->isVectorType()) 4810 isVectorLiteral = true; 4811 } 4812 else 4813 isVectorLiteral = true; 4814 } 4815 4816 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4817 // then handle it as such. 4818 if (isVectorLiteral) 4819 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4820 4821 // If the Expr being casted is a ParenListExpr, handle it specially. 4822 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4823 // sequence of BinOp comma operators. 4824 if (isa<ParenListExpr>(CastExpr)) { 4825 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4826 if (Result.isInvalid()) return ExprError(); 4827 CastExpr = Result.take(); 4828 } 4829 4830 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4831 } 4832 4833 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4834 SourceLocation RParenLoc, Expr *E, 4835 TypeSourceInfo *TInfo) { 4836 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4837 "Expected paren or paren list expression"); 4838 4839 Expr **exprs; 4840 unsigned numExprs; 4841 Expr *subExpr; 4842 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 4843 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4844 LiteralLParenLoc = PE->getLParenLoc(); 4845 LiteralRParenLoc = PE->getRParenLoc(); 4846 exprs = PE->getExprs(); 4847 numExprs = PE->getNumExprs(); 4848 } else { // isa<ParenExpr> by assertion at function entrance 4849 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 4850 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 4851 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4852 exprs = &subExpr; 4853 numExprs = 1; 4854 } 4855 4856 QualType Ty = TInfo->getType(); 4857 assert(Ty->isVectorType() && "Expected vector type"); 4858 4859 SmallVector<Expr *, 8> initExprs; 4860 const VectorType *VTy = Ty->getAs<VectorType>(); 4861 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4862 4863 // '(...)' form of vector initialization in AltiVec: the number of 4864 // initializers must be one or must match the size of the vector. 4865 // If a single value is specified in the initializer then it will be 4866 // replicated to all the components of the vector 4867 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4868 // The number of initializers must be one or must match the size of the 4869 // vector. If a single value is specified in the initializer then it will 4870 // be replicated to all the components of the vector 4871 if (numExprs == 1) { 4872 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4873 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4874 if (Literal.isInvalid()) 4875 return ExprError(); 4876 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4877 PrepareScalarCast(Literal, ElemTy)); 4878 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4879 } 4880 else if (numExprs < numElems) { 4881 Diag(E->getExprLoc(), 4882 diag::err_incorrect_number_of_vector_initializers); 4883 return ExprError(); 4884 } 4885 else 4886 initExprs.append(exprs, exprs + numExprs); 4887 } 4888 else { 4889 // For OpenCL, when the number of initializers is a single value, 4890 // it will be replicated to all components of the vector. 4891 if (getLangOpts().OpenCL && 4892 VTy->getVectorKind() == VectorType::GenericVector && 4893 numExprs == 1) { 4894 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4895 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4896 if (Literal.isInvalid()) 4897 return ExprError(); 4898 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4899 PrepareScalarCast(Literal, ElemTy)); 4900 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4901 } 4902 4903 initExprs.append(exprs, exprs + numExprs); 4904 } 4905 // FIXME: This means that pretty-printing the final AST will produce curly 4906 // braces instead of the original commas. 4907 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 4908 initExprs, LiteralRParenLoc); 4909 initE->setType(Ty); 4910 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4911 } 4912 4913 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4914 /// the ParenListExpr into a sequence of comma binary operators. 4915 ExprResult 4916 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4917 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4918 if (!E) 4919 return Owned(OrigExpr); 4920 4921 ExprResult Result(E->getExpr(0)); 4922 4923 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4924 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4925 E->getExpr(i)); 4926 4927 if (Result.isInvalid()) return ExprError(); 4928 4929 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4930 } 4931 4932 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4933 SourceLocation R, 4934 MultiExprArg Val) { 4935 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 4936 return Owned(expr); 4937 } 4938 4939 /// \brief Emit a specialized diagnostic when one expression is a null pointer 4940 /// constant and the other is not a pointer. Returns true if a diagnostic is 4941 /// emitted. 4942 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4943 SourceLocation QuestionLoc) { 4944 Expr *NullExpr = LHSExpr; 4945 Expr *NonPointerExpr = RHSExpr; 4946 Expr::NullPointerConstantKind NullKind = 4947 NullExpr->isNullPointerConstant(Context, 4948 Expr::NPC_ValueDependentIsNotNull); 4949 4950 if (NullKind == Expr::NPCK_NotNull) { 4951 NullExpr = RHSExpr; 4952 NonPointerExpr = LHSExpr; 4953 NullKind = 4954 NullExpr->isNullPointerConstant(Context, 4955 Expr::NPC_ValueDependentIsNotNull); 4956 } 4957 4958 if (NullKind == Expr::NPCK_NotNull) 4959 return false; 4960 4961 if (NullKind == Expr::NPCK_ZeroExpression) 4962 return false; 4963 4964 if (NullKind == Expr::NPCK_ZeroLiteral) { 4965 // In this case, check to make sure that we got here from a "NULL" 4966 // string in the source code. 4967 NullExpr = NullExpr->IgnoreParenImpCasts(); 4968 SourceLocation loc = NullExpr->getExprLoc(); 4969 if (!findMacroSpelling(loc, "NULL")) 4970 return false; 4971 } 4972 4973 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 4974 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4975 << NonPointerExpr->getType() << DiagType 4976 << NonPointerExpr->getSourceRange(); 4977 return true; 4978 } 4979 4980 /// \brief Return false if the condition expression is valid, true otherwise. 4981 static bool checkCondition(Sema &S, Expr *Cond) { 4982 QualType CondTy = Cond->getType(); 4983 4984 // C99 6.5.15p2 4985 if (CondTy->isScalarType()) return false; 4986 4987 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 4988 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 4989 return false; 4990 4991 // Emit the proper error message. 4992 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 4993 diag::err_typecheck_cond_expect_scalar : 4994 diag::err_typecheck_cond_expect_scalar_or_vector) 4995 << CondTy; 4996 return true; 4997 } 4998 4999 /// \brief Return false if the two expressions can be converted to a vector, 5000 /// true otherwise 5001 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5002 ExprResult &RHS, 5003 QualType CondTy) { 5004 // Both operands should be of scalar type. 5005 if (!LHS.get()->getType()->isScalarType()) { 5006 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5007 << CondTy; 5008 return true; 5009 } 5010 if (!RHS.get()->getType()->isScalarType()) { 5011 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5012 << CondTy; 5013 return true; 5014 } 5015 5016 // Implicity convert these scalars to the type of the condition. 5017 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5018 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5019 return false; 5020 } 5021 5022 /// \brief Handle when one or both operands are void type. 5023 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5024 ExprResult &RHS) { 5025 Expr *LHSExpr = LHS.get(); 5026 Expr *RHSExpr = RHS.get(); 5027 5028 if (!LHSExpr->getType()->isVoidType()) 5029 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5030 << RHSExpr->getSourceRange(); 5031 if (!RHSExpr->getType()->isVoidType()) 5032 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5033 << LHSExpr->getSourceRange(); 5034 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5035 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5036 return S.Context.VoidTy; 5037 } 5038 5039 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5040 /// true otherwise. 5041 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5042 QualType PointerTy) { 5043 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5044 !NullExpr.get()->isNullPointerConstant(S.Context, 5045 Expr::NPC_ValueDependentIsNull)) 5046 return true; 5047 5048 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5049 return false; 5050 } 5051 5052 /// \brief Checks compatibility between two pointers and return the resulting 5053 /// type. 5054 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5055 ExprResult &RHS, 5056 SourceLocation Loc) { 5057 QualType LHSTy = LHS.get()->getType(); 5058 QualType RHSTy = RHS.get()->getType(); 5059 5060 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5061 // Two identical pointers types are always compatible. 5062 return LHSTy; 5063 } 5064 5065 QualType lhptee, rhptee; 5066 5067 // Get the pointee types. 5068 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5069 lhptee = LHSBTy->getPointeeType(); 5070 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5071 } else { 5072 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5073 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5074 } 5075 5076 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5077 // differently qualified versions of compatible types, the result type is 5078 // a pointer to an appropriately qualified version of the composite 5079 // type. 5080 5081 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5082 // clause doesn't make sense for our extensions. E.g. address space 2 should 5083 // be incompatible with address space 3: they may live on different devices or 5084 // anything. 5085 Qualifiers lhQual = lhptee.getQualifiers(); 5086 Qualifiers rhQual = rhptee.getQualifiers(); 5087 5088 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5089 lhQual.removeCVRQualifiers(); 5090 rhQual.removeCVRQualifiers(); 5091 5092 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5093 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5094 5095 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5096 5097 if (CompositeTy.isNull()) { 5098 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5099 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5100 << RHS.get()->getSourceRange(); 5101 // In this situation, we assume void* type. No especially good 5102 // reason, but this is what gcc does, and we do have to pick 5103 // to get a consistent AST. 5104 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5105 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5106 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5107 return incompatTy; 5108 } 5109 5110 // The pointer types are compatible. 5111 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5112 ResultTy = S.Context.getPointerType(ResultTy); 5113 5114 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5115 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5116 return ResultTy; 5117 } 5118 5119 /// \brief Return the resulting type when the operands are both block pointers. 5120 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5121 ExprResult &LHS, 5122 ExprResult &RHS, 5123 SourceLocation Loc) { 5124 QualType LHSTy = LHS.get()->getType(); 5125 QualType RHSTy = RHS.get()->getType(); 5126 5127 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5128 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5129 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5130 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5131 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5132 return destType; 5133 } 5134 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5135 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5136 << RHS.get()->getSourceRange(); 5137 return QualType(); 5138 } 5139 5140 // We have 2 block pointer types. 5141 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5142 } 5143 5144 /// \brief Return the resulting type when the operands are both pointers. 5145 static QualType 5146 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5147 ExprResult &RHS, 5148 SourceLocation Loc) { 5149 // get the pointer types 5150 QualType LHSTy = LHS.get()->getType(); 5151 QualType RHSTy = RHS.get()->getType(); 5152 5153 // get the "pointed to" types 5154 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5155 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5156 5157 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5158 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5159 // Figure out necessary qualifiers (C99 6.5.15p6) 5160 QualType destPointee 5161 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5162 QualType destType = S.Context.getPointerType(destPointee); 5163 // Add qualifiers if necessary. 5164 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5165 // Promote to void*. 5166 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5167 return destType; 5168 } 5169 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5170 QualType destPointee 5171 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5172 QualType destType = S.Context.getPointerType(destPointee); 5173 // Add qualifiers if necessary. 5174 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5175 // Promote to void*. 5176 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5177 return destType; 5178 } 5179 5180 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5181 } 5182 5183 /// \brief Return false if the first expression is not an integer and the second 5184 /// expression is not a pointer, true otherwise. 5185 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5186 Expr* PointerExpr, SourceLocation Loc, 5187 bool IsIntFirstExpr) { 5188 if (!PointerExpr->getType()->isPointerType() || 5189 !Int.get()->getType()->isIntegerType()) 5190 return false; 5191 5192 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5193 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5194 5195 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5196 << Expr1->getType() << Expr2->getType() 5197 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5198 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5199 CK_IntegralToPointer); 5200 return true; 5201 } 5202 5203 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5204 /// In that case, LHS = cond. 5205 /// C99 6.5.15 5206 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5207 ExprResult &RHS, ExprValueKind &VK, 5208 ExprObjectKind &OK, 5209 SourceLocation QuestionLoc) { 5210 5211 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5212 if (!LHSResult.isUsable()) return QualType(); 5213 LHS = LHSResult; 5214 5215 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5216 if (!RHSResult.isUsable()) return QualType(); 5217 RHS = RHSResult; 5218 5219 // C++ is sufficiently different to merit its own checker. 5220 if (getLangOpts().CPlusPlus) 5221 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5222 5223 VK = VK_RValue; 5224 OK = OK_Ordinary; 5225 5226 Cond = UsualUnaryConversions(Cond.take()); 5227 if (Cond.isInvalid()) 5228 return QualType(); 5229 LHS = UsualUnaryConversions(LHS.take()); 5230 if (LHS.isInvalid()) 5231 return QualType(); 5232 RHS = UsualUnaryConversions(RHS.take()); 5233 if (RHS.isInvalid()) 5234 return QualType(); 5235 5236 QualType CondTy = Cond.get()->getType(); 5237 QualType LHSTy = LHS.get()->getType(); 5238 QualType RHSTy = RHS.get()->getType(); 5239 5240 // first, check the condition. 5241 if (checkCondition(*this, Cond.get())) 5242 return QualType(); 5243 5244 // Now check the two expressions. 5245 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5246 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5247 5248 // If the condition is a vector, and both operands are scalar, 5249 // attempt to implicity convert them to the vector type to act like the 5250 // built in select. (OpenCL v1.1 s6.3.i) 5251 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5252 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5253 return QualType(); 5254 5255 // If both operands have arithmetic type, do the usual arithmetic conversions 5256 // to find a common type: C99 6.5.15p3,5. 5257 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 5258 UsualArithmeticConversions(LHS, RHS); 5259 if (LHS.isInvalid() || RHS.isInvalid()) 5260 return QualType(); 5261 return LHS.get()->getType(); 5262 } 5263 5264 // If both operands are the same structure or union type, the result is that 5265 // type. 5266 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5267 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5268 if (LHSRT->getDecl() == RHSRT->getDecl()) 5269 // "If both the operands have structure or union type, the result has 5270 // that type." This implies that CV qualifiers are dropped. 5271 return LHSTy.getUnqualifiedType(); 5272 // FIXME: Type of conditional expression must be complete in C mode. 5273 } 5274 5275 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5276 // The following || allows only one side to be void (a GCC-ism). 5277 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5278 return checkConditionalVoidType(*this, LHS, RHS); 5279 } 5280 5281 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5282 // the type of the other operand." 5283 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5284 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5285 5286 // All objective-c pointer type analysis is done here. 5287 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5288 QuestionLoc); 5289 if (LHS.isInvalid() || RHS.isInvalid()) 5290 return QualType(); 5291 if (!compositeType.isNull()) 5292 return compositeType; 5293 5294 5295 // Handle block pointer types. 5296 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5297 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5298 QuestionLoc); 5299 5300 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5301 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5302 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5303 QuestionLoc); 5304 5305 // GCC compatibility: soften pointer/integer mismatch. Note that 5306 // null pointers have been filtered out by this point. 5307 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5308 /*isIntFirstExpr=*/true)) 5309 return RHSTy; 5310 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5311 /*isIntFirstExpr=*/false)) 5312 return LHSTy; 5313 5314 // Emit a better diagnostic if one of the expressions is a null pointer 5315 // constant and the other is not a pointer type. In this case, the user most 5316 // likely forgot to take the address of the other expression. 5317 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5318 return QualType(); 5319 5320 // Otherwise, the operands are not compatible. 5321 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5322 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5323 << RHS.get()->getSourceRange(); 5324 return QualType(); 5325 } 5326 5327 /// FindCompositeObjCPointerType - Helper method to find composite type of 5328 /// two objective-c pointer types of the two input expressions. 5329 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5330 SourceLocation QuestionLoc) { 5331 QualType LHSTy = LHS.get()->getType(); 5332 QualType RHSTy = RHS.get()->getType(); 5333 5334 // Handle things like Class and struct objc_class*. Here we case the result 5335 // to the pseudo-builtin, because that will be implicitly cast back to the 5336 // redefinition type if an attempt is made to access its fields. 5337 if (LHSTy->isObjCClassType() && 5338 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5339 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5340 return LHSTy; 5341 } 5342 if (RHSTy->isObjCClassType() && 5343 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5344 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5345 return RHSTy; 5346 } 5347 // And the same for struct objc_object* / id 5348 if (LHSTy->isObjCIdType() && 5349 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5350 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5351 return LHSTy; 5352 } 5353 if (RHSTy->isObjCIdType() && 5354 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5355 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5356 return RHSTy; 5357 } 5358 // And the same for struct objc_selector* / SEL 5359 if (Context.isObjCSelType(LHSTy) && 5360 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5361 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5362 return LHSTy; 5363 } 5364 if (Context.isObjCSelType(RHSTy) && 5365 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5366 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5367 return RHSTy; 5368 } 5369 // Check constraints for Objective-C object pointers types. 5370 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5371 5372 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5373 // Two identical object pointer types are always compatible. 5374 return LHSTy; 5375 } 5376 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5377 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5378 QualType compositeType = LHSTy; 5379 5380 // If both operands are interfaces and either operand can be 5381 // assigned to the other, use that type as the composite 5382 // type. This allows 5383 // xxx ? (A*) a : (B*) b 5384 // where B is a subclass of A. 5385 // 5386 // Additionally, as for assignment, if either type is 'id' 5387 // allow silent coercion. Finally, if the types are 5388 // incompatible then make sure to use 'id' as the composite 5389 // type so the result is acceptable for sending messages to. 5390 5391 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5392 // It could return the composite type. 5393 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5394 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5395 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5396 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5397 } else if ((LHSTy->isObjCQualifiedIdType() || 5398 RHSTy->isObjCQualifiedIdType()) && 5399 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5400 // Need to handle "id<xx>" explicitly. 5401 // GCC allows qualified id and any Objective-C type to devolve to 5402 // id. Currently localizing to here until clear this should be 5403 // part of ObjCQualifiedIdTypesAreCompatible. 5404 compositeType = Context.getObjCIdType(); 5405 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5406 compositeType = Context.getObjCIdType(); 5407 } else if (!(compositeType = 5408 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5409 ; 5410 else { 5411 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5412 << LHSTy << RHSTy 5413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5414 QualType incompatTy = Context.getObjCIdType(); 5415 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5416 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5417 return incompatTy; 5418 } 5419 // The object pointer types are compatible. 5420 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5421 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5422 return compositeType; 5423 } 5424 // Check Objective-C object pointer types and 'void *' 5425 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5426 if (getLangOpts().ObjCAutoRefCount) { 5427 // ARC forbids the implicit conversion of object pointers to 'void *', 5428 // so these types are not compatible. 5429 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5430 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5431 LHS = RHS = true; 5432 return QualType(); 5433 } 5434 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5435 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5436 QualType destPointee 5437 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5438 QualType destType = Context.getPointerType(destPointee); 5439 // Add qualifiers if necessary. 5440 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5441 // Promote to void*. 5442 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5443 return destType; 5444 } 5445 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5446 if (getLangOpts().ObjCAutoRefCount) { 5447 // ARC forbids the implicit conversion of object pointers to 'void *', 5448 // so these types are not compatible. 5449 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5450 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5451 LHS = RHS = true; 5452 return QualType(); 5453 } 5454 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5455 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5456 QualType destPointee 5457 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5458 QualType destType = Context.getPointerType(destPointee); 5459 // Add qualifiers if necessary. 5460 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5461 // Promote to void*. 5462 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5463 return destType; 5464 } 5465 return QualType(); 5466 } 5467 5468 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5469 /// ParenRange in parentheses. 5470 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5471 const PartialDiagnostic &Note, 5472 SourceRange ParenRange) { 5473 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5474 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5475 EndLoc.isValid()) { 5476 Self.Diag(Loc, Note) 5477 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5478 << FixItHint::CreateInsertion(EndLoc, ")"); 5479 } else { 5480 // We can't display the parentheses, so just show the bare note. 5481 Self.Diag(Loc, Note) << ParenRange; 5482 } 5483 } 5484 5485 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5486 return Opc >= BO_Mul && Opc <= BO_Shr; 5487 } 5488 5489 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5490 /// expression, either using a built-in or overloaded operator, 5491 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5492 /// expression. 5493 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5494 Expr **RHSExprs) { 5495 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5496 E = E->IgnoreImpCasts(); 5497 E = E->IgnoreConversionOperator(); 5498 E = E->IgnoreImpCasts(); 5499 5500 // Built-in binary operator. 5501 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5502 if (IsArithmeticOp(OP->getOpcode())) { 5503 *Opcode = OP->getOpcode(); 5504 *RHSExprs = OP->getRHS(); 5505 return true; 5506 } 5507 } 5508 5509 // Overloaded operator. 5510 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5511 if (Call->getNumArgs() != 2) 5512 return false; 5513 5514 // Make sure this is really a binary operator that is safe to pass into 5515 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5516 OverloadedOperatorKind OO = Call->getOperator(); 5517 if (OO < OO_Plus || OO > OO_Arrow || 5518 OO == OO_PlusPlus || OO == OO_MinusMinus) 5519 return false; 5520 5521 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5522 if (IsArithmeticOp(OpKind)) { 5523 *Opcode = OpKind; 5524 *RHSExprs = Call->getArg(1); 5525 return true; 5526 } 5527 } 5528 5529 return false; 5530 } 5531 5532 static bool IsLogicOp(BinaryOperatorKind Opc) { 5533 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5534 } 5535 5536 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5537 /// or is a logical expression such as (x==y) which has int type, but is 5538 /// commonly interpreted as boolean. 5539 static bool ExprLooksBoolean(Expr *E) { 5540 E = E->IgnoreParenImpCasts(); 5541 5542 if (E->getType()->isBooleanType()) 5543 return true; 5544 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5545 return IsLogicOp(OP->getOpcode()); 5546 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5547 return OP->getOpcode() == UO_LNot; 5548 5549 return false; 5550 } 5551 5552 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5553 /// and binary operator are mixed in a way that suggests the programmer assumed 5554 /// the conditional operator has higher precedence, for example: 5555 /// "int x = a + someBinaryCondition ? 1 : 2". 5556 static void DiagnoseConditionalPrecedence(Sema &Self, 5557 SourceLocation OpLoc, 5558 Expr *Condition, 5559 Expr *LHSExpr, 5560 Expr *RHSExpr) { 5561 BinaryOperatorKind CondOpcode; 5562 Expr *CondRHS; 5563 5564 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5565 return; 5566 if (!ExprLooksBoolean(CondRHS)) 5567 return; 5568 5569 // The condition is an arithmetic binary expression, with a right- 5570 // hand side that looks boolean, so warn. 5571 5572 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5573 << Condition->getSourceRange() 5574 << BinaryOperator::getOpcodeStr(CondOpcode); 5575 5576 SuggestParentheses(Self, OpLoc, 5577 Self.PDiag(diag::note_precedence_silence) 5578 << BinaryOperator::getOpcodeStr(CondOpcode), 5579 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5580 5581 SuggestParentheses(Self, OpLoc, 5582 Self.PDiag(diag::note_precedence_conditional_first), 5583 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5584 } 5585 5586 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5587 /// in the case of a the GNU conditional expr extension. 5588 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5589 SourceLocation ColonLoc, 5590 Expr *CondExpr, Expr *LHSExpr, 5591 Expr *RHSExpr) { 5592 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5593 // was the condition. 5594 OpaqueValueExpr *opaqueValue = 0; 5595 Expr *commonExpr = 0; 5596 if (LHSExpr == 0) { 5597 commonExpr = CondExpr; 5598 5599 // We usually want to apply unary conversions *before* saving, except 5600 // in the special case of a C++ l-value conditional. 5601 if (!(getLangOpts().CPlusPlus 5602 && !commonExpr->isTypeDependent() 5603 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5604 && commonExpr->isGLValue() 5605 && commonExpr->isOrdinaryOrBitFieldObject() 5606 && RHSExpr->isOrdinaryOrBitFieldObject() 5607 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5608 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5609 if (commonRes.isInvalid()) 5610 return ExprError(); 5611 commonExpr = commonRes.take(); 5612 } 5613 5614 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5615 commonExpr->getType(), 5616 commonExpr->getValueKind(), 5617 commonExpr->getObjectKind(), 5618 commonExpr); 5619 LHSExpr = CondExpr = opaqueValue; 5620 } 5621 5622 ExprValueKind VK = VK_RValue; 5623 ExprObjectKind OK = OK_Ordinary; 5624 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5625 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5626 VK, OK, QuestionLoc); 5627 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5628 RHS.isInvalid()) 5629 return ExprError(); 5630 5631 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5632 RHS.get()); 5633 5634 if (!commonExpr) 5635 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5636 LHS.take(), ColonLoc, 5637 RHS.take(), result, VK, OK)); 5638 5639 return Owned(new (Context) 5640 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5641 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5642 OK)); 5643 } 5644 5645 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5646 // being closely modeled after the C99 spec:-). The odd characteristic of this 5647 // routine is it effectively iqnores the qualifiers on the top level pointee. 5648 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5649 // FIXME: add a couple examples in this comment. 5650 static Sema::AssignConvertType 5651 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5652 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5653 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5654 5655 // get the "pointed to" type (ignoring qualifiers at the top level) 5656 const Type *lhptee, *rhptee; 5657 Qualifiers lhq, rhq; 5658 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5659 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5660 5661 Sema::AssignConvertType ConvTy = Sema::Compatible; 5662 5663 // C99 6.5.16.1p1: This following citation is common to constraints 5664 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5665 // qualifiers of the type *pointed to* by the right; 5666 Qualifiers lq; 5667 5668 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5669 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5670 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5671 // Ignore lifetime for further calculation. 5672 lhq.removeObjCLifetime(); 5673 rhq.removeObjCLifetime(); 5674 } 5675 5676 if (!lhq.compatiblyIncludes(rhq)) { 5677 // Treat address-space mismatches as fatal. TODO: address subspaces 5678 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5679 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5680 5681 // It's okay to add or remove GC or lifetime qualifiers when converting to 5682 // and from void*. 5683 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5684 .compatiblyIncludes( 5685 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5686 && (lhptee->isVoidType() || rhptee->isVoidType())) 5687 ; // keep old 5688 5689 // Treat lifetime mismatches as fatal. 5690 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5691 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5692 5693 // For GCC compatibility, other qualifier mismatches are treated 5694 // as still compatible in C. 5695 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5696 } 5697 5698 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5699 // incomplete type and the other is a pointer to a qualified or unqualified 5700 // version of void... 5701 if (lhptee->isVoidType()) { 5702 if (rhptee->isIncompleteOrObjectType()) 5703 return ConvTy; 5704 5705 // As an extension, we allow cast to/from void* to function pointer. 5706 assert(rhptee->isFunctionType()); 5707 return Sema::FunctionVoidPointer; 5708 } 5709 5710 if (rhptee->isVoidType()) { 5711 if (lhptee->isIncompleteOrObjectType()) 5712 return ConvTy; 5713 5714 // As an extension, we allow cast to/from void* to function pointer. 5715 assert(lhptee->isFunctionType()); 5716 return Sema::FunctionVoidPointer; 5717 } 5718 5719 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5720 // unqualified versions of compatible types, ... 5721 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5722 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5723 // Check if the pointee types are compatible ignoring the sign. 5724 // We explicitly check for char so that we catch "char" vs 5725 // "unsigned char" on systems where "char" is unsigned. 5726 if (lhptee->isCharType()) 5727 ltrans = S.Context.UnsignedCharTy; 5728 else if (lhptee->hasSignedIntegerRepresentation()) 5729 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5730 5731 if (rhptee->isCharType()) 5732 rtrans = S.Context.UnsignedCharTy; 5733 else if (rhptee->hasSignedIntegerRepresentation()) 5734 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5735 5736 if (ltrans == rtrans) { 5737 // Types are compatible ignoring the sign. Qualifier incompatibility 5738 // takes priority over sign incompatibility because the sign 5739 // warning can be disabled. 5740 if (ConvTy != Sema::Compatible) 5741 return ConvTy; 5742 5743 return Sema::IncompatiblePointerSign; 5744 } 5745 5746 // If we are a multi-level pointer, it's possible that our issue is simply 5747 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5748 // the eventual target type is the same and the pointers have the same 5749 // level of indirection, this must be the issue. 5750 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5751 do { 5752 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5753 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5754 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5755 5756 if (lhptee == rhptee) 5757 return Sema::IncompatibleNestedPointerQualifiers; 5758 } 5759 5760 // General pointer incompatibility takes priority over qualifiers. 5761 return Sema::IncompatiblePointer; 5762 } 5763 if (!S.getLangOpts().CPlusPlus && 5764 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5765 return Sema::IncompatiblePointer; 5766 return ConvTy; 5767 } 5768 5769 /// checkBlockPointerTypesForAssignment - This routine determines whether two 5770 /// block pointer types are compatible or whether a block and normal pointer 5771 /// are compatible. It is more restrict than comparing two function pointer 5772 // types. 5773 static Sema::AssignConvertType 5774 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5775 QualType RHSType) { 5776 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5777 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5778 5779 QualType lhptee, rhptee; 5780 5781 // get the "pointed to" type (ignoring qualifiers at the top level) 5782 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5783 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5784 5785 // In C++, the types have to match exactly. 5786 if (S.getLangOpts().CPlusPlus) 5787 return Sema::IncompatibleBlockPointer; 5788 5789 Sema::AssignConvertType ConvTy = Sema::Compatible; 5790 5791 // For blocks we enforce that qualifiers are identical. 5792 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5793 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5794 5795 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5796 return Sema::IncompatibleBlockPointer; 5797 5798 return ConvTy; 5799 } 5800 5801 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5802 /// for assignment compatibility. 5803 static Sema::AssignConvertType 5804 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5805 QualType RHSType) { 5806 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5807 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5808 5809 if (LHSType->isObjCBuiltinType()) { 5810 // Class is not compatible with ObjC object pointers. 5811 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5812 !RHSType->isObjCQualifiedClassType()) 5813 return Sema::IncompatiblePointer; 5814 return Sema::Compatible; 5815 } 5816 if (RHSType->isObjCBuiltinType()) { 5817 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5818 !LHSType->isObjCQualifiedClassType()) 5819 return Sema::IncompatiblePointer; 5820 return Sema::Compatible; 5821 } 5822 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5823 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5824 5825 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5826 // make an exception for id<P> 5827 !LHSType->isObjCQualifiedIdType()) 5828 return Sema::CompatiblePointerDiscardsQualifiers; 5829 5830 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5831 return Sema::Compatible; 5832 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5833 return Sema::IncompatibleObjCQualifiedId; 5834 return Sema::IncompatiblePointer; 5835 } 5836 5837 Sema::AssignConvertType 5838 Sema::CheckAssignmentConstraints(SourceLocation Loc, 5839 QualType LHSType, QualType RHSType) { 5840 // Fake up an opaque expression. We don't actually care about what 5841 // cast operations are required, so if CheckAssignmentConstraints 5842 // adds casts to this they'll be wasted, but fortunately that doesn't 5843 // usually happen on valid code. 5844 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5845 ExprResult RHSPtr = &RHSExpr; 5846 CastKind K = CK_Invalid; 5847 5848 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5849 } 5850 5851 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5852 /// has code to accommodate several GCC extensions when type checking 5853 /// pointers. Here are some objectionable examples that GCC considers warnings: 5854 /// 5855 /// int a, *pint; 5856 /// short *pshort; 5857 /// struct foo *pfoo; 5858 /// 5859 /// pint = pshort; // warning: assignment from incompatible pointer type 5860 /// a = pint; // warning: assignment makes integer from pointer without a cast 5861 /// pint = a; // warning: assignment makes pointer from integer without a cast 5862 /// pint = pfoo; // warning: assignment from incompatible pointer type 5863 /// 5864 /// As a result, the code for dealing with pointers is more complex than the 5865 /// C99 spec dictates. 5866 /// 5867 /// Sets 'Kind' for any result kind except Incompatible. 5868 Sema::AssignConvertType 5869 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5870 CastKind &Kind) { 5871 QualType RHSType = RHS.get()->getType(); 5872 QualType OrigLHSType = LHSType; 5873 5874 // Get canonical types. We're not formatting these types, just comparing 5875 // them. 5876 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5877 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5878 5879 // Common case: no conversion required. 5880 if (LHSType == RHSType) { 5881 Kind = CK_NoOp; 5882 return Compatible; 5883 } 5884 5885 // If we have an atomic type, try a non-atomic assignment, then just add an 5886 // atomic qualification step. 5887 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5888 Sema::AssignConvertType result = 5889 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 5890 if (result != Compatible) 5891 return result; 5892 if (Kind != CK_NoOp) 5893 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 5894 Kind = CK_NonAtomicToAtomic; 5895 return Compatible; 5896 } 5897 5898 // If the left-hand side is a reference type, then we are in a 5899 // (rare!) case where we've allowed the use of references in C, 5900 // e.g., as a parameter type in a built-in function. In this case, 5901 // just make sure that the type referenced is compatible with the 5902 // right-hand side type. The caller is responsible for adjusting 5903 // LHSType so that the resulting expression does not have reference 5904 // type. 5905 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5906 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5907 Kind = CK_LValueBitCast; 5908 return Compatible; 5909 } 5910 return Incompatible; 5911 } 5912 5913 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5914 // to the same ExtVector type. 5915 if (LHSType->isExtVectorType()) { 5916 if (RHSType->isExtVectorType()) 5917 return Incompatible; 5918 if (RHSType->isArithmeticType()) { 5919 // CK_VectorSplat does T -> vector T, so first cast to the 5920 // element type. 5921 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5922 if (elType != RHSType) { 5923 Kind = PrepareScalarCast(RHS, elType); 5924 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5925 } 5926 Kind = CK_VectorSplat; 5927 return Compatible; 5928 } 5929 } 5930 5931 // Conversions to or from vector type. 5932 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5933 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5934 // Allow assignments of an AltiVec vector type to an equivalent GCC 5935 // vector type and vice versa 5936 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5937 Kind = CK_BitCast; 5938 return Compatible; 5939 } 5940 5941 // If we are allowing lax vector conversions, and LHS and RHS are both 5942 // vectors, the total size only needs to be the same. This is a bitcast; 5943 // no bits are changed but the result type is different. 5944 if (getLangOpts().LaxVectorConversions && 5945 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5946 Kind = CK_BitCast; 5947 return IncompatibleVectors; 5948 } 5949 } 5950 return Incompatible; 5951 } 5952 5953 // Arithmetic conversions. 5954 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5955 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 5956 Kind = PrepareScalarCast(RHS, LHSType); 5957 return Compatible; 5958 } 5959 5960 // Conversions to normal pointers. 5961 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5962 // U* -> T* 5963 if (isa<PointerType>(RHSType)) { 5964 Kind = CK_BitCast; 5965 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5966 } 5967 5968 // int -> T* 5969 if (RHSType->isIntegerType()) { 5970 Kind = CK_IntegralToPointer; // FIXME: null? 5971 return IntToPointer; 5972 } 5973 5974 // C pointers are not compatible with ObjC object pointers, 5975 // with two exceptions: 5976 if (isa<ObjCObjectPointerType>(RHSType)) { 5977 // - conversions to void* 5978 if (LHSPointer->getPointeeType()->isVoidType()) { 5979 Kind = CK_BitCast; 5980 return Compatible; 5981 } 5982 5983 // - conversions from 'Class' to the redefinition type 5984 if (RHSType->isObjCClassType() && 5985 Context.hasSameType(LHSType, 5986 Context.getObjCClassRedefinitionType())) { 5987 Kind = CK_BitCast; 5988 return Compatible; 5989 } 5990 5991 Kind = CK_BitCast; 5992 return IncompatiblePointer; 5993 } 5994 5995 // U^ -> void* 5996 if (RHSType->getAs<BlockPointerType>()) { 5997 if (LHSPointer->getPointeeType()->isVoidType()) { 5998 Kind = CK_BitCast; 5999 return Compatible; 6000 } 6001 } 6002 6003 return Incompatible; 6004 } 6005 6006 // Conversions to block pointers. 6007 if (isa<BlockPointerType>(LHSType)) { 6008 // U^ -> T^ 6009 if (RHSType->isBlockPointerType()) { 6010 Kind = CK_BitCast; 6011 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6012 } 6013 6014 // int or null -> T^ 6015 if (RHSType->isIntegerType()) { 6016 Kind = CK_IntegralToPointer; // FIXME: null 6017 return IntToBlockPointer; 6018 } 6019 6020 // id -> T^ 6021 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6022 Kind = CK_AnyPointerToBlockPointerCast; 6023 return Compatible; 6024 } 6025 6026 // void* -> T^ 6027 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6028 if (RHSPT->getPointeeType()->isVoidType()) { 6029 Kind = CK_AnyPointerToBlockPointerCast; 6030 return Compatible; 6031 } 6032 6033 return Incompatible; 6034 } 6035 6036 // Conversions to Objective-C pointers. 6037 if (isa<ObjCObjectPointerType>(LHSType)) { 6038 // A* -> B* 6039 if (RHSType->isObjCObjectPointerType()) { 6040 Kind = CK_BitCast; 6041 Sema::AssignConvertType result = 6042 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6043 if (getLangOpts().ObjCAutoRefCount && 6044 result == Compatible && 6045 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6046 result = IncompatibleObjCWeakRef; 6047 return result; 6048 } 6049 6050 // int or null -> A* 6051 if (RHSType->isIntegerType()) { 6052 Kind = CK_IntegralToPointer; // FIXME: null 6053 return IntToPointer; 6054 } 6055 6056 // In general, C pointers are not compatible with ObjC object pointers, 6057 // with two exceptions: 6058 if (isa<PointerType>(RHSType)) { 6059 Kind = CK_CPointerToObjCPointerCast; 6060 6061 // - conversions from 'void*' 6062 if (RHSType->isVoidPointerType()) { 6063 return Compatible; 6064 } 6065 6066 // - conversions to 'Class' from its redefinition type 6067 if (LHSType->isObjCClassType() && 6068 Context.hasSameType(RHSType, 6069 Context.getObjCClassRedefinitionType())) { 6070 return Compatible; 6071 } 6072 6073 return IncompatiblePointer; 6074 } 6075 6076 // T^ -> A* 6077 if (RHSType->isBlockPointerType()) { 6078 maybeExtendBlockObject(*this, RHS); 6079 Kind = CK_BlockPointerToObjCPointerCast; 6080 return Compatible; 6081 } 6082 6083 return Incompatible; 6084 } 6085 6086 // Conversions from pointers that are not covered by the above. 6087 if (isa<PointerType>(RHSType)) { 6088 // T* -> _Bool 6089 if (LHSType == Context.BoolTy) { 6090 Kind = CK_PointerToBoolean; 6091 return Compatible; 6092 } 6093 6094 // T* -> int 6095 if (LHSType->isIntegerType()) { 6096 Kind = CK_PointerToIntegral; 6097 return PointerToInt; 6098 } 6099 6100 return Incompatible; 6101 } 6102 6103 // Conversions from Objective-C pointers that are not covered by the above. 6104 if (isa<ObjCObjectPointerType>(RHSType)) { 6105 // T* -> _Bool 6106 if (LHSType == Context.BoolTy) { 6107 Kind = CK_PointerToBoolean; 6108 return Compatible; 6109 } 6110 6111 // T* -> int 6112 if (LHSType->isIntegerType()) { 6113 Kind = CK_PointerToIntegral; 6114 return PointerToInt; 6115 } 6116 6117 return Incompatible; 6118 } 6119 6120 // struct A -> struct B 6121 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6122 if (Context.typesAreCompatible(LHSType, RHSType)) { 6123 Kind = CK_NoOp; 6124 return Compatible; 6125 } 6126 } 6127 6128 return Incompatible; 6129 } 6130 6131 /// \brief Constructs a transparent union from an expression that is 6132 /// used to initialize the transparent union. 6133 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6134 ExprResult &EResult, QualType UnionType, 6135 FieldDecl *Field) { 6136 // Build an initializer list that designates the appropriate member 6137 // of the transparent union. 6138 Expr *E = EResult.take(); 6139 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6140 E, SourceLocation()); 6141 Initializer->setType(UnionType); 6142 Initializer->setInitializedFieldInUnion(Field); 6143 6144 // Build a compound literal constructing a value of the transparent 6145 // union type from this initializer list. 6146 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6147 EResult = S.Owned( 6148 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6149 VK_RValue, Initializer, false)); 6150 } 6151 6152 Sema::AssignConvertType 6153 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6154 ExprResult &RHS) { 6155 QualType RHSType = RHS.get()->getType(); 6156 6157 // If the ArgType is a Union type, we want to handle a potential 6158 // transparent_union GCC extension. 6159 const RecordType *UT = ArgType->getAsUnionType(); 6160 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6161 return Incompatible; 6162 6163 // The field to initialize within the transparent union. 6164 RecordDecl *UD = UT->getDecl(); 6165 FieldDecl *InitField = 0; 6166 // It's compatible if the expression matches any of the fields. 6167 for (RecordDecl::field_iterator it = UD->field_begin(), 6168 itend = UD->field_end(); 6169 it != itend; ++it) { 6170 if (it->getType()->isPointerType()) { 6171 // If the transparent union contains a pointer type, we allow: 6172 // 1) void pointer 6173 // 2) null pointer constant 6174 if (RHSType->isPointerType()) 6175 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6176 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6177 InitField = *it; 6178 break; 6179 } 6180 6181 if (RHS.get()->isNullPointerConstant(Context, 6182 Expr::NPC_ValueDependentIsNull)) { 6183 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6184 CK_NullToPointer); 6185 InitField = *it; 6186 break; 6187 } 6188 } 6189 6190 CastKind Kind = CK_Invalid; 6191 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6192 == Compatible) { 6193 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6194 InitField = *it; 6195 break; 6196 } 6197 } 6198 6199 if (!InitField) 6200 return Incompatible; 6201 6202 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6203 return Compatible; 6204 } 6205 6206 Sema::AssignConvertType 6207 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6208 bool Diagnose) { 6209 if (getLangOpts().CPlusPlus) { 6210 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6211 // C++ 5.17p3: If the left operand is not of class type, the 6212 // expression is implicitly converted (C++ 4) to the 6213 // cv-unqualified type of the left operand. 6214 ExprResult Res; 6215 if (Diagnose) { 6216 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6217 AA_Assigning); 6218 } else { 6219 ImplicitConversionSequence ICS = 6220 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6221 /*SuppressUserConversions=*/false, 6222 /*AllowExplicit=*/false, 6223 /*InOverloadResolution=*/false, 6224 /*CStyle=*/false, 6225 /*AllowObjCWritebackConversion=*/false); 6226 if (ICS.isFailure()) 6227 return Incompatible; 6228 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6229 ICS, AA_Assigning); 6230 } 6231 if (Res.isInvalid()) 6232 return Incompatible; 6233 Sema::AssignConvertType result = Compatible; 6234 if (getLangOpts().ObjCAutoRefCount && 6235 !CheckObjCARCUnavailableWeakConversion(LHSType, 6236 RHS.get()->getType())) 6237 result = IncompatibleObjCWeakRef; 6238 RHS = Res; 6239 return result; 6240 } 6241 6242 // FIXME: Currently, we fall through and treat C++ classes like C 6243 // structures. 6244 // FIXME: We also fall through for atomics; not sure what should 6245 // happen there, though. 6246 } 6247 6248 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6249 // a null pointer constant. 6250 if ((LHSType->isPointerType() || 6251 LHSType->isObjCObjectPointerType() || 6252 LHSType->isBlockPointerType()) 6253 && RHS.get()->isNullPointerConstant(Context, 6254 Expr::NPC_ValueDependentIsNull)) { 6255 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6256 return Compatible; 6257 } 6258 6259 // This check seems unnatural, however it is necessary to ensure the proper 6260 // conversion of functions/arrays. If the conversion were done for all 6261 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6262 // expressions that suppress this implicit conversion (&, sizeof). 6263 // 6264 // Suppress this for references: C++ 8.5.3p5. 6265 if (!LHSType->isReferenceType()) { 6266 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6267 if (RHS.isInvalid()) 6268 return Incompatible; 6269 } 6270 6271 CastKind Kind = CK_Invalid; 6272 Sema::AssignConvertType result = 6273 CheckAssignmentConstraints(LHSType, RHS, Kind); 6274 6275 // C99 6.5.16.1p2: The value of the right operand is converted to the 6276 // type of the assignment expression. 6277 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6278 // so that we can use references in built-in functions even in C. 6279 // The getNonReferenceType() call makes sure that the resulting expression 6280 // does not have reference type. 6281 if (result != Incompatible && RHS.get()->getType() != LHSType) 6282 RHS = ImpCastExprToType(RHS.take(), 6283 LHSType.getNonLValueExprType(Context), Kind); 6284 return result; 6285 } 6286 6287 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6288 ExprResult &RHS) { 6289 Diag(Loc, diag::err_typecheck_invalid_operands) 6290 << LHS.get()->getType() << RHS.get()->getType() 6291 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6292 return QualType(); 6293 } 6294 6295 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6296 SourceLocation Loc, bool IsCompAssign) { 6297 if (!IsCompAssign) { 6298 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6299 if (LHS.isInvalid()) 6300 return QualType(); 6301 } 6302 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6303 if (RHS.isInvalid()) 6304 return QualType(); 6305 6306 // For conversion purposes, we ignore any qualifiers. 6307 // For example, "const float" and "float" are equivalent. 6308 QualType LHSType = 6309 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6310 QualType RHSType = 6311 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6312 6313 // If the vector types are identical, return. 6314 if (LHSType == RHSType) 6315 return LHSType; 6316 6317 // Handle the case of equivalent AltiVec and GCC vector types 6318 if (LHSType->isVectorType() && RHSType->isVectorType() && 6319 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6320 if (LHSType->isExtVectorType()) { 6321 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6322 return LHSType; 6323 } 6324 6325 if (!IsCompAssign) 6326 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6327 return RHSType; 6328 } 6329 6330 if (getLangOpts().LaxVectorConversions && 6331 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6332 // If we are allowing lax vector conversions, and LHS and RHS are both 6333 // vectors, the total size only needs to be the same. This is a 6334 // bitcast; no bits are changed but the result type is different. 6335 // FIXME: Should we really be allowing this? 6336 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6337 return LHSType; 6338 } 6339 6340 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6341 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6342 bool swapped = false; 6343 if (RHSType->isExtVectorType() && !IsCompAssign) { 6344 swapped = true; 6345 std::swap(RHS, LHS); 6346 std::swap(RHSType, LHSType); 6347 } 6348 6349 // Handle the case of an ext vector and scalar. 6350 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6351 QualType EltTy = LV->getElementType(); 6352 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6353 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6354 if (order > 0) 6355 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6356 if (order >= 0) { 6357 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6358 if (swapped) std::swap(RHS, LHS); 6359 return LHSType; 6360 } 6361 } 6362 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 6363 RHSType->isRealFloatingType()) { 6364 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6365 if (order > 0) 6366 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6367 if (order >= 0) { 6368 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6369 if (swapped) std::swap(RHS, LHS); 6370 return LHSType; 6371 } 6372 } 6373 } 6374 6375 // Vectors of different size or scalar and non-ext-vector are errors. 6376 if (swapped) std::swap(RHS, LHS); 6377 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6378 << LHS.get()->getType() << RHS.get()->getType() 6379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6380 return QualType(); 6381 } 6382 6383 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6384 // expression. These are mainly cases where the null pointer is used as an 6385 // integer instead of a pointer. 6386 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6387 SourceLocation Loc, bool IsCompare) { 6388 // The canonical way to check for a GNU null is with isNullPointerConstant, 6389 // but we use a bit of a hack here for speed; this is a relatively 6390 // hot path, and isNullPointerConstant is slow. 6391 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6392 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6393 6394 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6395 6396 // Avoid analyzing cases where the result will either be invalid (and 6397 // diagnosed as such) or entirely valid and not something to warn about. 6398 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6399 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6400 return; 6401 6402 // Comparison operations would not make sense with a null pointer no matter 6403 // what the other expression is. 6404 if (!IsCompare) { 6405 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6406 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6407 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6408 return; 6409 } 6410 6411 // The rest of the operations only make sense with a null pointer 6412 // if the other expression is a pointer. 6413 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6414 NonNullType->canDecayToPointerType()) 6415 return; 6416 6417 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6418 << LHSNull /* LHS is NULL */ << NonNullType 6419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6420 } 6421 6422 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6423 SourceLocation Loc, 6424 bool IsCompAssign, bool IsDiv) { 6425 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6426 6427 if (LHS.get()->getType()->isVectorType() || 6428 RHS.get()->getType()->isVectorType()) 6429 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6430 6431 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6432 if (LHS.isInvalid() || RHS.isInvalid()) 6433 return QualType(); 6434 6435 6436 if (compType.isNull() || !compType->isArithmeticType()) 6437 return InvalidOperands(Loc, LHS, RHS); 6438 6439 // Check for division by zero. 6440 if (IsDiv && 6441 RHS.get()->isNullPointerConstant(Context, 6442 Expr::NPC_ValueDependentIsNotNull)) 6443 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 6444 << RHS.get()->getSourceRange()); 6445 6446 return compType; 6447 } 6448 6449 QualType Sema::CheckRemainderOperands( 6450 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6451 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6452 6453 if (LHS.get()->getType()->isVectorType() || 6454 RHS.get()->getType()->isVectorType()) { 6455 if (LHS.get()->getType()->hasIntegerRepresentation() && 6456 RHS.get()->getType()->hasIntegerRepresentation()) 6457 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6458 return InvalidOperands(Loc, LHS, RHS); 6459 } 6460 6461 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6462 if (LHS.isInvalid() || RHS.isInvalid()) 6463 return QualType(); 6464 6465 if (compType.isNull() || !compType->isIntegerType()) 6466 return InvalidOperands(Loc, LHS, RHS); 6467 6468 // Check for remainder by zero. 6469 if (RHS.get()->isNullPointerConstant(Context, 6470 Expr::NPC_ValueDependentIsNotNull)) 6471 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 6472 << RHS.get()->getSourceRange()); 6473 6474 return compType; 6475 } 6476 6477 /// \brief Diagnose invalid arithmetic on two void pointers. 6478 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6479 Expr *LHSExpr, Expr *RHSExpr) { 6480 S.Diag(Loc, S.getLangOpts().CPlusPlus 6481 ? diag::err_typecheck_pointer_arith_void_type 6482 : diag::ext_gnu_void_ptr) 6483 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6484 << RHSExpr->getSourceRange(); 6485 } 6486 6487 /// \brief Diagnose invalid arithmetic on a void pointer. 6488 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6489 Expr *Pointer) { 6490 S.Diag(Loc, S.getLangOpts().CPlusPlus 6491 ? diag::err_typecheck_pointer_arith_void_type 6492 : diag::ext_gnu_void_ptr) 6493 << 0 /* one pointer */ << Pointer->getSourceRange(); 6494 } 6495 6496 /// \brief Diagnose invalid arithmetic on two function pointers. 6497 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6498 Expr *LHS, Expr *RHS) { 6499 assert(LHS->getType()->isAnyPointerType()); 6500 assert(RHS->getType()->isAnyPointerType()); 6501 S.Diag(Loc, S.getLangOpts().CPlusPlus 6502 ? diag::err_typecheck_pointer_arith_function_type 6503 : diag::ext_gnu_ptr_func_arith) 6504 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6505 // We only show the second type if it differs from the first. 6506 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6507 RHS->getType()) 6508 << RHS->getType()->getPointeeType() 6509 << LHS->getSourceRange() << RHS->getSourceRange(); 6510 } 6511 6512 /// \brief Diagnose invalid arithmetic on a function pointer. 6513 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6514 Expr *Pointer) { 6515 assert(Pointer->getType()->isAnyPointerType()); 6516 S.Diag(Loc, S.getLangOpts().CPlusPlus 6517 ? diag::err_typecheck_pointer_arith_function_type 6518 : diag::ext_gnu_ptr_func_arith) 6519 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6520 << 0 /* one pointer, so only one type */ 6521 << Pointer->getSourceRange(); 6522 } 6523 6524 /// \brief Emit error if Operand is incomplete pointer type 6525 /// 6526 /// \returns True if pointer has incomplete type 6527 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6528 Expr *Operand) { 6529 assert(Operand->getType()->isAnyPointerType() && 6530 !Operand->getType()->isDependentType()); 6531 QualType PointeeTy = Operand->getType()->getPointeeType(); 6532 return S.RequireCompleteType(Loc, PointeeTy, 6533 diag::err_typecheck_arithmetic_incomplete_type, 6534 PointeeTy, Operand->getSourceRange()); 6535 } 6536 6537 /// \brief Check the validity of an arithmetic pointer operand. 6538 /// 6539 /// If the operand has pointer type, this code will check for pointer types 6540 /// which are invalid in arithmetic operations. These will be diagnosed 6541 /// appropriately, including whether or not the use is supported as an 6542 /// extension. 6543 /// 6544 /// \returns True when the operand is valid to use (even if as an extension). 6545 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6546 Expr *Operand) { 6547 if (!Operand->getType()->isAnyPointerType()) return true; 6548 6549 QualType PointeeTy = Operand->getType()->getPointeeType(); 6550 if (PointeeTy->isVoidType()) { 6551 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6552 return !S.getLangOpts().CPlusPlus; 6553 } 6554 if (PointeeTy->isFunctionType()) { 6555 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6556 return !S.getLangOpts().CPlusPlus; 6557 } 6558 6559 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6560 6561 return true; 6562 } 6563 6564 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6565 /// operands. 6566 /// 6567 /// This routine will diagnose any invalid arithmetic on pointer operands much 6568 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6569 /// for emitting a single diagnostic even for operations where both LHS and RHS 6570 /// are (potentially problematic) pointers. 6571 /// 6572 /// \returns True when the operand is valid to use (even if as an extension). 6573 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6574 Expr *LHSExpr, Expr *RHSExpr) { 6575 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6576 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6577 if (!isLHSPointer && !isRHSPointer) return true; 6578 6579 QualType LHSPointeeTy, RHSPointeeTy; 6580 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6581 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6582 6583 // Check for arithmetic on pointers to incomplete types. 6584 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6585 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6586 if (isLHSVoidPtr || isRHSVoidPtr) { 6587 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6588 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6589 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6590 6591 return !S.getLangOpts().CPlusPlus; 6592 } 6593 6594 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6595 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6596 if (isLHSFuncPtr || isRHSFuncPtr) { 6597 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6598 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6599 RHSExpr); 6600 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6601 6602 return !S.getLangOpts().CPlusPlus; 6603 } 6604 6605 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6606 return false; 6607 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6608 return false; 6609 6610 return true; 6611 } 6612 6613 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6614 /// literal. 6615 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6616 Expr *LHSExpr, Expr *RHSExpr) { 6617 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6618 Expr* IndexExpr = RHSExpr; 6619 if (!StrExpr) { 6620 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6621 IndexExpr = LHSExpr; 6622 } 6623 6624 bool IsStringPlusInt = StrExpr && 6625 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6626 if (!IsStringPlusInt) 6627 return; 6628 6629 llvm::APSInt index; 6630 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6631 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6632 if (index.isNonNegative() && 6633 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6634 index.isUnsigned())) 6635 return; 6636 } 6637 6638 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6639 Self.Diag(OpLoc, diag::warn_string_plus_int) 6640 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6641 6642 // Only print a fixit for "str" + int, not for int + "str". 6643 if (IndexExpr == RHSExpr) { 6644 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6645 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6646 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6647 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6648 << FixItHint::CreateInsertion(EndLoc, "]"); 6649 } else 6650 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6651 } 6652 6653 /// \brief Emit error when two pointers are incompatible. 6654 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6655 Expr *LHSExpr, Expr *RHSExpr) { 6656 assert(LHSExpr->getType()->isAnyPointerType()); 6657 assert(RHSExpr->getType()->isAnyPointerType()); 6658 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6659 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6660 << RHSExpr->getSourceRange(); 6661 } 6662 6663 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6664 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6665 QualType* CompLHSTy) { 6666 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6667 6668 if (LHS.get()->getType()->isVectorType() || 6669 RHS.get()->getType()->isVectorType()) { 6670 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6671 if (CompLHSTy) *CompLHSTy = compType; 6672 return compType; 6673 } 6674 6675 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6676 if (LHS.isInvalid() || RHS.isInvalid()) 6677 return QualType(); 6678 6679 // Diagnose "string literal" '+' int. 6680 if (Opc == BO_Add) 6681 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6682 6683 // handle the common case first (both operands are arithmetic). 6684 if (!compType.isNull() && compType->isArithmeticType()) { 6685 if (CompLHSTy) *CompLHSTy = compType; 6686 return compType; 6687 } 6688 6689 // Type-checking. Ultimately the pointer's going to be in PExp; 6690 // note that we bias towards the LHS being the pointer. 6691 Expr *PExp = LHS.get(), *IExp = RHS.get(); 6692 6693 bool isObjCPointer; 6694 if (PExp->getType()->isPointerType()) { 6695 isObjCPointer = false; 6696 } else if (PExp->getType()->isObjCObjectPointerType()) { 6697 isObjCPointer = true; 6698 } else { 6699 std::swap(PExp, IExp); 6700 if (PExp->getType()->isPointerType()) { 6701 isObjCPointer = false; 6702 } else if (PExp->getType()->isObjCObjectPointerType()) { 6703 isObjCPointer = true; 6704 } else { 6705 return InvalidOperands(Loc, LHS, RHS); 6706 } 6707 } 6708 assert(PExp->getType()->isAnyPointerType()); 6709 6710 if (!IExp->getType()->isIntegerType()) 6711 return InvalidOperands(Loc, LHS, RHS); 6712 6713 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6714 return QualType(); 6715 6716 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 6717 return QualType(); 6718 6719 // Check array bounds for pointer arithemtic 6720 CheckArrayAccess(PExp, IExp); 6721 6722 if (CompLHSTy) { 6723 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6724 if (LHSTy.isNull()) { 6725 LHSTy = LHS.get()->getType(); 6726 if (LHSTy->isPromotableIntegerType()) 6727 LHSTy = Context.getPromotedIntegerType(LHSTy); 6728 } 6729 *CompLHSTy = LHSTy; 6730 } 6731 6732 return PExp->getType(); 6733 } 6734 6735 // C99 6.5.6 6736 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6737 SourceLocation Loc, 6738 QualType* CompLHSTy) { 6739 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6740 6741 if (LHS.get()->getType()->isVectorType() || 6742 RHS.get()->getType()->isVectorType()) { 6743 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6744 if (CompLHSTy) *CompLHSTy = compType; 6745 return compType; 6746 } 6747 6748 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6749 if (LHS.isInvalid() || RHS.isInvalid()) 6750 return QualType(); 6751 6752 // Enforce type constraints: C99 6.5.6p3. 6753 6754 // Handle the common case first (both operands are arithmetic). 6755 if (!compType.isNull() && compType->isArithmeticType()) { 6756 if (CompLHSTy) *CompLHSTy = compType; 6757 return compType; 6758 } 6759 6760 // Either ptr - int or ptr - ptr. 6761 if (LHS.get()->getType()->isAnyPointerType()) { 6762 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6763 6764 // Diagnose bad cases where we step over interface counts. 6765 if (LHS.get()->getType()->isObjCObjectPointerType() && 6766 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 6767 return QualType(); 6768 6769 // The result type of a pointer-int computation is the pointer type. 6770 if (RHS.get()->getType()->isIntegerType()) { 6771 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6772 return QualType(); 6773 6774 // Check array bounds for pointer arithemtic 6775 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6776 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6777 6778 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6779 return LHS.get()->getType(); 6780 } 6781 6782 // Handle pointer-pointer subtractions. 6783 if (const PointerType *RHSPTy 6784 = RHS.get()->getType()->getAs<PointerType>()) { 6785 QualType rpointee = RHSPTy->getPointeeType(); 6786 6787 if (getLangOpts().CPlusPlus) { 6788 // Pointee types must be the same: C++ [expr.add] 6789 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6790 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6791 } 6792 } else { 6793 // Pointee types must be compatible C99 6.5.6p3 6794 if (!Context.typesAreCompatible( 6795 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6796 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6797 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6798 return QualType(); 6799 } 6800 } 6801 6802 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6803 LHS.get(), RHS.get())) 6804 return QualType(); 6805 6806 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6807 return Context.getPointerDiffType(); 6808 } 6809 } 6810 6811 return InvalidOperands(Loc, LHS, RHS); 6812 } 6813 6814 static bool isScopedEnumerationType(QualType T) { 6815 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6816 return ET->getDecl()->isScoped(); 6817 return false; 6818 } 6819 6820 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6821 SourceLocation Loc, unsigned Opc, 6822 QualType LHSType) { 6823 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 6824 // so skip remaining warnings as we don't want to modify values within Sema. 6825 if (S.getLangOpts().OpenCL) 6826 return; 6827 6828 llvm::APSInt Right; 6829 // Check right/shifter operand 6830 if (RHS.get()->isValueDependent() || 6831 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6832 return; 6833 6834 if (Right.isNegative()) { 6835 S.DiagRuntimeBehavior(Loc, RHS.get(), 6836 S.PDiag(diag::warn_shift_negative) 6837 << RHS.get()->getSourceRange()); 6838 return; 6839 } 6840 llvm::APInt LeftBits(Right.getBitWidth(), 6841 S.Context.getTypeSize(LHS.get()->getType())); 6842 if (Right.uge(LeftBits)) { 6843 S.DiagRuntimeBehavior(Loc, RHS.get(), 6844 S.PDiag(diag::warn_shift_gt_typewidth) 6845 << RHS.get()->getSourceRange()); 6846 return; 6847 } 6848 if (Opc != BO_Shl) 6849 return; 6850 6851 // When left shifting an ICE which is signed, we can check for overflow which 6852 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6853 // integers have defined behavior modulo one more than the maximum value 6854 // representable in the result type, so never warn for those. 6855 llvm::APSInt Left; 6856 if (LHS.get()->isValueDependent() || 6857 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6858 LHSType->hasUnsignedIntegerRepresentation()) 6859 return; 6860 llvm::APInt ResultBits = 6861 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6862 if (LeftBits.uge(ResultBits)) 6863 return; 6864 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6865 Result = Result.shl(Right); 6866 6867 // Print the bit representation of the signed integer as an unsigned 6868 // hexadecimal number. 6869 SmallString<40> HexResult; 6870 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6871 6872 // If we are only missing a sign bit, this is less likely to result in actual 6873 // bugs -- if the result is cast back to an unsigned type, it will have the 6874 // expected value. Thus we place this behind a different warning that can be 6875 // turned off separately if needed. 6876 if (LeftBits == ResultBits - 1) { 6877 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6878 << HexResult.str() << LHSType 6879 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6880 return; 6881 } 6882 6883 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6884 << HexResult.str() << Result.getMinSignedBits() << LHSType 6885 << Left.getBitWidth() << LHS.get()->getSourceRange() 6886 << RHS.get()->getSourceRange(); 6887 } 6888 6889 // C99 6.5.7 6890 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6891 SourceLocation Loc, unsigned Opc, 6892 bool IsCompAssign) { 6893 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6894 6895 // Vector shifts promote their scalar inputs to vector type. 6896 if (LHS.get()->getType()->isVectorType() || 6897 RHS.get()->getType()->isVectorType()) 6898 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6899 6900 // Shifts don't perform usual arithmetic conversions, they just do integer 6901 // promotions on each operand. C99 6.5.7p3 6902 6903 // For the LHS, do usual unary conversions, but then reset them away 6904 // if this is a compound assignment. 6905 ExprResult OldLHS = LHS; 6906 LHS = UsualUnaryConversions(LHS.take()); 6907 if (LHS.isInvalid()) 6908 return QualType(); 6909 QualType LHSType = LHS.get()->getType(); 6910 if (IsCompAssign) LHS = OldLHS; 6911 6912 // The RHS is simpler. 6913 RHS = UsualUnaryConversions(RHS.take()); 6914 if (RHS.isInvalid()) 6915 return QualType(); 6916 QualType RHSType = RHS.get()->getType(); 6917 6918 // C99 6.5.7p2: Each of the operands shall have integer type. 6919 if (!LHSType->hasIntegerRepresentation() || 6920 !RHSType->hasIntegerRepresentation()) 6921 return InvalidOperands(Loc, LHS, RHS); 6922 6923 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6924 // hasIntegerRepresentation() above instead of this. 6925 if (isScopedEnumerationType(LHSType) || 6926 isScopedEnumerationType(RHSType)) { 6927 return InvalidOperands(Loc, LHS, RHS); 6928 } 6929 // Sanity-check shift operands 6930 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6931 6932 // "The type of the result is that of the promoted left operand." 6933 return LHSType; 6934 } 6935 6936 static bool IsWithinTemplateSpecialization(Decl *D) { 6937 if (DeclContext *DC = D->getDeclContext()) { 6938 if (isa<ClassTemplateSpecializationDecl>(DC)) 6939 return true; 6940 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6941 return FD->isFunctionTemplateSpecialization(); 6942 } 6943 return false; 6944 } 6945 6946 /// If two different enums are compared, raise a warning. 6947 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 6948 Expr *RHS) { 6949 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 6950 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 6951 6952 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6953 if (!LHSEnumType) 6954 return; 6955 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6956 if (!RHSEnumType) 6957 return; 6958 6959 // Ignore anonymous enums. 6960 if (!LHSEnumType->getDecl()->getIdentifier()) 6961 return; 6962 if (!RHSEnumType->getDecl()->getIdentifier()) 6963 return; 6964 6965 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6966 return; 6967 6968 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6969 << LHSStrippedType << RHSStrippedType 6970 << LHS->getSourceRange() << RHS->getSourceRange(); 6971 } 6972 6973 /// \brief Diagnose bad pointer comparisons. 6974 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6975 ExprResult &LHS, ExprResult &RHS, 6976 bool IsError) { 6977 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 6978 : diag::ext_typecheck_comparison_of_distinct_pointers) 6979 << LHS.get()->getType() << RHS.get()->getType() 6980 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6981 } 6982 6983 /// \brief Returns false if the pointers are converted to a composite type, 6984 /// true otherwise. 6985 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6986 ExprResult &LHS, ExprResult &RHS) { 6987 // C++ [expr.rel]p2: 6988 // [...] Pointer conversions (4.10) and qualification 6989 // conversions (4.4) are performed on pointer operands (or on 6990 // a pointer operand and a null pointer constant) to bring 6991 // them to their composite pointer type. [...] 6992 // 6993 // C++ [expr.eq]p1 uses the same notion for (in)equality 6994 // comparisons of pointers. 6995 6996 // C++ [expr.eq]p2: 6997 // In addition, pointers to members can be compared, or a pointer to 6998 // member and a null pointer constant. Pointer to member conversions 6999 // (4.11) and qualification conversions (4.4) are performed to bring 7000 // them to a common type. If one operand is a null pointer constant, 7001 // the common type is the type of the other operand. Otherwise, the 7002 // common type is a pointer to member type similar (4.4) to the type 7003 // of one of the operands, with a cv-qualification signature (4.4) 7004 // that is the union of the cv-qualification signatures of the operand 7005 // types. 7006 7007 QualType LHSType = LHS.get()->getType(); 7008 QualType RHSType = RHS.get()->getType(); 7009 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7010 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7011 7012 bool NonStandardCompositeType = false; 7013 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7014 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7015 if (T.isNull()) { 7016 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7017 return true; 7018 } 7019 7020 if (NonStandardCompositeType) 7021 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7022 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7023 << RHS.get()->getSourceRange(); 7024 7025 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7026 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7027 return false; 7028 } 7029 7030 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7031 ExprResult &LHS, 7032 ExprResult &RHS, 7033 bool IsError) { 7034 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7035 : diag::ext_typecheck_comparison_of_fptr_to_void) 7036 << LHS.get()->getType() << RHS.get()->getType() 7037 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7038 } 7039 7040 static bool isObjCObjectLiteral(ExprResult &E) { 7041 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7042 case Stmt::ObjCArrayLiteralClass: 7043 case Stmt::ObjCDictionaryLiteralClass: 7044 case Stmt::ObjCStringLiteralClass: 7045 case Stmt::ObjCBoxedExprClass: 7046 return true; 7047 default: 7048 // Note that ObjCBoolLiteral is NOT an object literal! 7049 return false; 7050 } 7051 } 7052 7053 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7054 const ObjCObjectPointerType *Type = 7055 LHS->getType()->getAs<ObjCObjectPointerType>(); 7056 7057 // If this is not actually an Objective-C object, bail out. 7058 if (!Type) 7059 return false; 7060 7061 // Get the LHS object's interface type. 7062 QualType InterfaceType = Type->getPointeeType(); 7063 if (const ObjCObjectType *iQFaceTy = 7064 InterfaceType->getAsObjCQualifiedInterfaceType()) 7065 InterfaceType = iQFaceTy->getBaseType(); 7066 7067 // If the RHS isn't an Objective-C object, bail out. 7068 if (!RHS->getType()->isObjCObjectPointerType()) 7069 return false; 7070 7071 // Try to find the -isEqual: method. 7072 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7073 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7074 InterfaceType, 7075 /*instance=*/true); 7076 if (!Method) { 7077 if (Type->isObjCIdType()) { 7078 // For 'id', just check the global pool. 7079 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7080 /*receiverId=*/true, 7081 /*warn=*/false); 7082 } else { 7083 // Check protocols. 7084 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7085 /*instance=*/true); 7086 } 7087 } 7088 7089 if (!Method) 7090 return false; 7091 7092 QualType T = Method->param_begin()[0]->getType(); 7093 if (!T->isObjCObjectPointerType()) 7094 return false; 7095 7096 QualType R = Method->getResultType(); 7097 if (!R->isScalarType()) 7098 return false; 7099 7100 return true; 7101 } 7102 7103 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7104 FromE = FromE->IgnoreParenImpCasts(); 7105 switch (FromE->getStmtClass()) { 7106 default: 7107 break; 7108 case Stmt::ObjCStringLiteralClass: 7109 // "string literal" 7110 return LK_String; 7111 case Stmt::ObjCArrayLiteralClass: 7112 // "array literal" 7113 return LK_Array; 7114 case Stmt::ObjCDictionaryLiteralClass: 7115 // "dictionary literal" 7116 return LK_Dictionary; 7117 case Stmt::BlockExprClass: 7118 return LK_Block; 7119 case Stmt::ObjCBoxedExprClass: { 7120 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7121 switch (Inner->getStmtClass()) { 7122 case Stmt::IntegerLiteralClass: 7123 case Stmt::FloatingLiteralClass: 7124 case Stmt::CharacterLiteralClass: 7125 case Stmt::ObjCBoolLiteralExprClass: 7126 case Stmt::CXXBoolLiteralExprClass: 7127 // "numeric literal" 7128 return LK_Numeric; 7129 case Stmt::ImplicitCastExprClass: { 7130 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7131 // Boolean literals can be represented by implicit casts. 7132 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7133 return LK_Numeric; 7134 break; 7135 } 7136 default: 7137 break; 7138 } 7139 return LK_Boxed; 7140 } 7141 } 7142 return LK_None; 7143 } 7144 7145 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7146 ExprResult &LHS, ExprResult &RHS, 7147 BinaryOperator::Opcode Opc){ 7148 Expr *Literal; 7149 Expr *Other; 7150 if (isObjCObjectLiteral(LHS)) { 7151 Literal = LHS.get(); 7152 Other = RHS.get(); 7153 } else { 7154 Literal = RHS.get(); 7155 Other = LHS.get(); 7156 } 7157 7158 // Don't warn on comparisons against nil. 7159 Other = Other->IgnoreParenCasts(); 7160 if (Other->isNullPointerConstant(S.getASTContext(), 7161 Expr::NPC_ValueDependentIsNotNull)) 7162 return; 7163 7164 // This should be kept in sync with warn_objc_literal_comparison. 7165 // LK_String should always be after the other literals, since it has its own 7166 // warning flag. 7167 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7168 assert(LiteralKind != Sema::LK_Block); 7169 if (LiteralKind == Sema::LK_None) { 7170 llvm_unreachable("Unknown Objective-C object literal kind"); 7171 } 7172 7173 if (LiteralKind == Sema::LK_String) 7174 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7175 << Literal->getSourceRange(); 7176 else 7177 S.Diag(Loc, diag::warn_objc_literal_comparison) 7178 << LiteralKind << Literal->getSourceRange(); 7179 7180 if (BinaryOperator::isEqualityOp(Opc) && 7181 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7182 SourceLocation Start = LHS.get()->getLocStart(); 7183 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7184 CharSourceRange OpRange = 7185 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7186 7187 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7188 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7189 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7190 << FixItHint::CreateInsertion(End, "]"); 7191 } 7192 } 7193 7194 // C99 6.5.8, C++ [expr.rel] 7195 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7196 SourceLocation Loc, unsigned OpaqueOpc, 7197 bool IsRelational) { 7198 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7199 7200 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7201 7202 // Handle vector comparisons separately. 7203 if (LHS.get()->getType()->isVectorType() || 7204 RHS.get()->getType()->isVectorType()) 7205 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7206 7207 QualType LHSType = LHS.get()->getType(); 7208 QualType RHSType = RHS.get()->getType(); 7209 7210 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7211 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7212 7213 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7214 7215 if (!LHSType->hasFloatingRepresentation() && 7216 !(LHSType->isBlockPointerType() && IsRelational) && 7217 !LHS.get()->getLocStart().isMacroID() && 7218 !RHS.get()->getLocStart().isMacroID()) { 7219 // For non-floating point types, check for self-comparisons of the form 7220 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7221 // often indicate logic errors in the program. 7222 // 7223 // NOTE: Don't warn about comparison expressions resulting from macro 7224 // expansion. Also don't warn about comparisons which are only self 7225 // comparisons within a template specialization. The warnings should catch 7226 // obvious cases in the definition of the template anyways. The idea is to 7227 // warn when the typed comparison operator will always evaluate to the same 7228 // result. 7229 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 7230 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 7231 if (DRL->getDecl() == DRR->getDecl() && 7232 !IsWithinTemplateSpecialization(DRL->getDecl())) { 7233 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7234 << 0 // self- 7235 << (Opc == BO_EQ 7236 || Opc == BO_LE 7237 || Opc == BO_GE)); 7238 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 7239 !DRL->getDecl()->getType()->isReferenceType() && 7240 !DRR->getDecl()->getType()->isReferenceType()) { 7241 // what is it always going to eval to? 7242 char always_evals_to; 7243 switch(Opc) { 7244 case BO_EQ: // e.g. array1 == array2 7245 always_evals_to = 0; // false 7246 break; 7247 case BO_NE: // e.g. array1 != array2 7248 always_evals_to = 1; // true 7249 break; 7250 default: 7251 // best we can say is 'a constant' 7252 always_evals_to = 2; // e.g. array1 <= array2 7253 break; 7254 } 7255 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7256 << 1 // array 7257 << always_evals_to); 7258 } 7259 } 7260 } 7261 7262 if (isa<CastExpr>(LHSStripped)) 7263 LHSStripped = LHSStripped->IgnoreParenCasts(); 7264 if (isa<CastExpr>(RHSStripped)) 7265 RHSStripped = RHSStripped->IgnoreParenCasts(); 7266 7267 // Warn about comparisons against a string constant (unless the other 7268 // operand is null), the user probably wants strcmp. 7269 Expr *literalString = 0; 7270 Expr *literalStringStripped = 0; 7271 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7272 !RHSStripped->isNullPointerConstant(Context, 7273 Expr::NPC_ValueDependentIsNull)) { 7274 literalString = LHS.get(); 7275 literalStringStripped = LHSStripped; 7276 } else if ((isa<StringLiteral>(RHSStripped) || 7277 isa<ObjCEncodeExpr>(RHSStripped)) && 7278 !LHSStripped->isNullPointerConstant(Context, 7279 Expr::NPC_ValueDependentIsNull)) { 7280 literalString = RHS.get(); 7281 literalStringStripped = RHSStripped; 7282 } 7283 7284 if (literalString) { 7285 DiagRuntimeBehavior(Loc, 0, 7286 PDiag(diag::warn_stringcompare) 7287 << isa<ObjCEncodeExpr>(literalStringStripped) 7288 << literalString->getSourceRange()); 7289 } 7290 } 7291 7292 // C99 6.5.8p3 / C99 6.5.9p4 7293 if (LHS.get()->getType()->isArithmeticType() && 7294 RHS.get()->getType()->isArithmeticType()) { 7295 UsualArithmeticConversions(LHS, RHS); 7296 if (LHS.isInvalid() || RHS.isInvalid()) 7297 return QualType(); 7298 } 7299 else { 7300 LHS = UsualUnaryConversions(LHS.take()); 7301 if (LHS.isInvalid()) 7302 return QualType(); 7303 7304 RHS = UsualUnaryConversions(RHS.take()); 7305 if (RHS.isInvalid()) 7306 return QualType(); 7307 } 7308 7309 LHSType = LHS.get()->getType(); 7310 RHSType = RHS.get()->getType(); 7311 7312 // The result of comparisons is 'bool' in C++, 'int' in C. 7313 QualType ResultTy = Context.getLogicalOperationType(); 7314 7315 if (IsRelational) { 7316 if (LHSType->isRealType() && RHSType->isRealType()) 7317 return ResultTy; 7318 } else { 7319 // Check for comparisons of floating point operands using != and ==. 7320 if (LHSType->hasFloatingRepresentation()) 7321 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7322 7323 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7324 return ResultTy; 7325 } 7326 7327 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7328 Expr::NPC_ValueDependentIsNull); 7329 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7330 Expr::NPC_ValueDependentIsNull); 7331 7332 // All of the following pointer-related warnings are GCC extensions, except 7333 // when handling null pointer constants. 7334 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7335 QualType LCanPointeeTy = 7336 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7337 QualType RCanPointeeTy = 7338 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7339 7340 if (getLangOpts().CPlusPlus) { 7341 if (LCanPointeeTy == RCanPointeeTy) 7342 return ResultTy; 7343 if (!IsRelational && 7344 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7345 // Valid unless comparison between non-null pointer and function pointer 7346 // This is a gcc extension compatibility comparison. 7347 // In a SFINAE context, we treat this as a hard error to maintain 7348 // conformance with the C++ standard. 7349 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7350 && !LHSIsNull && !RHSIsNull) { 7351 diagnoseFunctionPointerToVoidComparison( 7352 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7353 7354 if (isSFINAEContext()) 7355 return QualType(); 7356 7357 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7358 return ResultTy; 7359 } 7360 } 7361 7362 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7363 return QualType(); 7364 else 7365 return ResultTy; 7366 } 7367 // C99 6.5.9p2 and C99 6.5.8p2 7368 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7369 RCanPointeeTy.getUnqualifiedType())) { 7370 // Valid unless a relational comparison of function pointers 7371 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7372 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7373 << LHSType << RHSType << LHS.get()->getSourceRange() 7374 << RHS.get()->getSourceRange(); 7375 } 7376 } else if (!IsRelational && 7377 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7378 // Valid unless comparison between non-null pointer and function pointer 7379 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7380 && !LHSIsNull && !RHSIsNull) 7381 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7382 /*isError*/false); 7383 } else { 7384 // Invalid 7385 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7386 } 7387 if (LCanPointeeTy != RCanPointeeTy) { 7388 if (LHSIsNull && !RHSIsNull) 7389 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7390 else 7391 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7392 } 7393 return ResultTy; 7394 } 7395 7396 if (getLangOpts().CPlusPlus) { 7397 // Comparison of nullptr_t with itself. 7398 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7399 return ResultTy; 7400 7401 // Comparison of pointers with null pointer constants and equality 7402 // comparisons of member pointers to null pointer constants. 7403 if (RHSIsNull && 7404 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7405 (!IsRelational && 7406 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7407 RHS = ImpCastExprToType(RHS.take(), LHSType, 7408 LHSType->isMemberPointerType() 7409 ? CK_NullToMemberPointer 7410 : CK_NullToPointer); 7411 return ResultTy; 7412 } 7413 if (LHSIsNull && 7414 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7415 (!IsRelational && 7416 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7417 LHS = ImpCastExprToType(LHS.take(), RHSType, 7418 RHSType->isMemberPointerType() 7419 ? CK_NullToMemberPointer 7420 : CK_NullToPointer); 7421 return ResultTy; 7422 } 7423 7424 // Comparison of member pointers. 7425 if (!IsRelational && 7426 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7427 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7428 return QualType(); 7429 else 7430 return ResultTy; 7431 } 7432 7433 // Handle scoped enumeration types specifically, since they don't promote 7434 // to integers. 7435 if (LHS.get()->getType()->isEnumeralType() && 7436 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7437 RHS.get()->getType())) 7438 return ResultTy; 7439 } 7440 7441 // Handle block pointer types. 7442 if (!IsRelational && LHSType->isBlockPointerType() && 7443 RHSType->isBlockPointerType()) { 7444 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7445 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7446 7447 if (!LHSIsNull && !RHSIsNull && 7448 !Context.typesAreCompatible(lpointee, rpointee)) { 7449 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7450 << LHSType << RHSType << LHS.get()->getSourceRange() 7451 << RHS.get()->getSourceRange(); 7452 } 7453 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7454 return ResultTy; 7455 } 7456 7457 // Allow block pointers to be compared with null pointer constants. 7458 if (!IsRelational 7459 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7460 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7461 if (!LHSIsNull && !RHSIsNull) { 7462 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7463 ->getPointeeType()->isVoidType()) 7464 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7465 ->getPointeeType()->isVoidType()))) 7466 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7467 << LHSType << RHSType << LHS.get()->getSourceRange() 7468 << RHS.get()->getSourceRange(); 7469 } 7470 if (LHSIsNull && !RHSIsNull) 7471 LHS = ImpCastExprToType(LHS.take(), RHSType, 7472 RHSType->isPointerType() ? CK_BitCast 7473 : CK_AnyPointerToBlockPointerCast); 7474 else 7475 RHS = ImpCastExprToType(RHS.take(), LHSType, 7476 LHSType->isPointerType() ? CK_BitCast 7477 : CK_AnyPointerToBlockPointerCast); 7478 return ResultTy; 7479 } 7480 7481 if (LHSType->isObjCObjectPointerType() || 7482 RHSType->isObjCObjectPointerType()) { 7483 const PointerType *LPT = LHSType->getAs<PointerType>(); 7484 const PointerType *RPT = RHSType->getAs<PointerType>(); 7485 if (LPT || RPT) { 7486 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7487 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7488 7489 if (!LPtrToVoid && !RPtrToVoid && 7490 !Context.typesAreCompatible(LHSType, RHSType)) { 7491 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7492 /*isError*/false); 7493 } 7494 if (LHSIsNull && !RHSIsNull) 7495 LHS = ImpCastExprToType(LHS.take(), RHSType, 7496 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7497 else 7498 RHS = ImpCastExprToType(RHS.take(), LHSType, 7499 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7500 return ResultTy; 7501 } 7502 if (LHSType->isObjCObjectPointerType() && 7503 RHSType->isObjCObjectPointerType()) { 7504 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7505 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7506 /*isError*/false); 7507 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7508 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7509 7510 if (LHSIsNull && !RHSIsNull) 7511 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7512 else 7513 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7514 return ResultTy; 7515 } 7516 } 7517 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7518 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7519 unsigned DiagID = 0; 7520 bool isError = false; 7521 if (LangOpts.DebuggerSupport) { 7522 // Under a debugger, allow the comparison of pointers to integers, 7523 // since users tend to want to compare addresses. 7524 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7525 (RHSIsNull && RHSType->isIntegerType())) { 7526 if (IsRelational && !getLangOpts().CPlusPlus) 7527 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7528 } else if (IsRelational && !getLangOpts().CPlusPlus) 7529 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7530 else if (getLangOpts().CPlusPlus) { 7531 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7532 isError = true; 7533 } else 7534 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7535 7536 if (DiagID) { 7537 Diag(Loc, DiagID) 7538 << LHSType << RHSType << LHS.get()->getSourceRange() 7539 << RHS.get()->getSourceRange(); 7540 if (isError) 7541 return QualType(); 7542 } 7543 7544 if (LHSType->isIntegerType()) 7545 LHS = ImpCastExprToType(LHS.take(), RHSType, 7546 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7547 else 7548 RHS = ImpCastExprToType(RHS.take(), LHSType, 7549 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7550 return ResultTy; 7551 } 7552 7553 // Handle block pointers. 7554 if (!IsRelational && RHSIsNull 7555 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7556 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7557 return ResultTy; 7558 } 7559 if (!IsRelational && LHSIsNull 7560 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7561 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7562 return ResultTy; 7563 } 7564 7565 return InvalidOperands(Loc, LHS, RHS); 7566 } 7567 7568 7569 // Return a signed type that is of identical size and number of elements. 7570 // For floating point vectors, return an integer type of identical size 7571 // and number of elements. 7572 QualType Sema::GetSignedVectorType(QualType V) { 7573 const VectorType *VTy = V->getAs<VectorType>(); 7574 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7575 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7576 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7577 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7578 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7579 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7580 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7581 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7582 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7583 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7584 "Unhandled vector element size in vector compare"); 7585 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7586 } 7587 7588 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7589 /// operates on extended vector types. Instead of producing an IntTy result, 7590 /// like a scalar comparison, a vector comparison produces a vector of integer 7591 /// types. 7592 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7593 SourceLocation Loc, 7594 bool IsRelational) { 7595 // Check to make sure we're operating on vectors of the same type and width, 7596 // Allowing one side to be a scalar of element type. 7597 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7598 if (vType.isNull()) 7599 return vType; 7600 7601 QualType LHSType = LHS.get()->getType(); 7602 7603 // If AltiVec, the comparison results in a numeric type, i.e. 7604 // bool for C++, int for C 7605 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7606 return Context.getLogicalOperationType(); 7607 7608 // For non-floating point types, check for self-comparisons of the form 7609 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7610 // often indicate logic errors in the program. 7611 if (!LHSType->hasFloatingRepresentation()) { 7612 if (DeclRefExpr* DRL 7613 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7614 if (DeclRefExpr* DRR 7615 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7616 if (DRL->getDecl() == DRR->getDecl()) 7617 DiagRuntimeBehavior(Loc, 0, 7618 PDiag(diag::warn_comparison_always) 7619 << 0 // self- 7620 << 2 // "a constant" 7621 ); 7622 } 7623 7624 // Check for comparisons of floating point operands using != and ==. 7625 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7626 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7627 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7628 } 7629 7630 // Return a signed type for the vector. 7631 return GetSignedVectorType(LHSType); 7632 } 7633 7634 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7635 SourceLocation Loc) { 7636 // Ensure that either both operands are of the same vector type, or 7637 // one operand is of a vector type and the other is of its element type. 7638 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7639 if (vType.isNull()) 7640 return InvalidOperands(Loc, LHS, RHS); 7641 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 7642 vType->hasFloatingRepresentation()) 7643 return InvalidOperands(Loc, LHS, RHS); 7644 7645 return GetSignedVectorType(LHS.get()->getType()); 7646 } 7647 7648 inline QualType Sema::CheckBitwiseOperands( 7649 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7650 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7651 7652 if (LHS.get()->getType()->isVectorType() || 7653 RHS.get()->getType()->isVectorType()) { 7654 if (LHS.get()->getType()->hasIntegerRepresentation() && 7655 RHS.get()->getType()->hasIntegerRepresentation()) 7656 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7657 7658 return InvalidOperands(Loc, LHS, RHS); 7659 } 7660 7661 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7662 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7663 IsCompAssign); 7664 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7665 return QualType(); 7666 LHS = LHSResult.take(); 7667 RHS = RHSResult.take(); 7668 7669 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7670 return compType; 7671 return InvalidOperands(Loc, LHS, RHS); 7672 } 7673 7674 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7675 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7676 7677 // Check vector operands differently. 7678 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7679 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7680 7681 // Diagnose cases where the user write a logical and/or but probably meant a 7682 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7683 // is a constant. 7684 if (LHS.get()->getType()->isIntegerType() && 7685 !LHS.get()->getType()->isBooleanType() && 7686 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7687 // Don't warn in macros or template instantiations. 7688 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7689 // If the RHS can be constant folded, and if it constant folds to something 7690 // that isn't 0 or 1 (which indicate a potential logical operation that 7691 // happened to fold to true/false) then warn. 7692 // Parens on the RHS are ignored. 7693 llvm::APSInt Result; 7694 if (RHS.get()->EvaluateAsInt(Result, Context)) 7695 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7696 (Result != 0 && Result != 1)) { 7697 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7698 << RHS.get()->getSourceRange() 7699 << (Opc == BO_LAnd ? "&&" : "||"); 7700 // Suggest replacing the logical operator with the bitwise version 7701 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7702 << (Opc == BO_LAnd ? "&" : "|") 7703 << FixItHint::CreateReplacement(SourceRange( 7704 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7705 getLangOpts())), 7706 Opc == BO_LAnd ? "&" : "|"); 7707 if (Opc == BO_LAnd) 7708 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7709 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7710 << FixItHint::CreateRemoval( 7711 SourceRange( 7712 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7713 0, getSourceManager(), 7714 getLangOpts()), 7715 RHS.get()->getLocEnd())); 7716 } 7717 } 7718 7719 if (!Context.getLangOpts().CPlusPlus) { 7720 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 7721 // not operate on the built-in scalar and vector float types. 7722 if (Context.getLangOpts().OpenCL && 7723 Context.getLangOpts().OpenCLVersion < 120) { 7724 if (LHS.get()->getType()->isFloatingType() || 7725 RHS.get()->getType()->isFloatingType()) 7726 return InvalidOperands(Loc, LHS, RHS); 7727 } 7728 7729 LHS = UsualUnaryConversions(LHS.take()); 7730 if (LHS.isInvalid()) 7731 return QualType(); 7732 7733 RHS = UsualUnaryConversions(RHS.take()); 7734 if (RHS.isInvalid()) 7735 return QualType(); 7736 7737 if (!LHS.get()->getType()->isScalarType() || 7738 !RHS.get()->getType()->isScalarType()) 7739 return InvalidOperands(Loc, LHS, RHS); 7740 7741 return Context.IntTy; 7742 } 7743 7744 // The following is safe because we only use this method for 7745 // non-overloadable operands. 7746 7747 // C++ [expr.log.and]p1 7748 // C++ [expr.log.or]p1 7749 // The operands are both contextually converted to type bool. 7750 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7751 if (LHSRes.isInvalid()) 7752 return InvalidOperands(Loc, LHS, RHS); 7753 LHS = LHSRes; 7754 7755 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7756 if (RHSRes.isInvalid()) 7757 return InvalidOperands(Loc, LHS, RHS); 7758 RHS = RHSRes; 7759 7760 // C++ [expr.log.and]p2 7761 // C++ [expr.log.or]p2 7762 // The result is a bool. 7763 return Context.BoolTy; 7764 } 7765 7766 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7767 /// is a read-only property; return true if so. A readonly property expression 7768 /// depends on various declarations and thus must be treated specially. 7769 /// 7770 static bool IsReadonlyProperty(Expr *E, Sema &S) { 7771 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 7772 if (!PropExpr) return false; 7773 if (PropExpr->isImplicitProperty()) return false; 7774 7775 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7776 QualType BaseType = PropExpr->isSuperReceiver() ? 7777 PropExpr->getSuperReceiverType() : 7778 PropExpr->getBase()->getType(); 7779 7780 if (const ObjCObjectPointerType *OPT = 7781 BaseType->getAsObjCInterfacePointerType()) 7782 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7783 if (S.isPropertyReadonly(PDecl, IFace)) 7784 return true; 7785 return false; 7786 } 7787 7788 static bool IsReadonlyMessage(Expr *E, Sema &S) { 7789 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7790 if (!ME) return false; 7791 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7792 ObjCMessageExpr *Base = 7793 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7794 if (!Base) return false; 7795 return Base->getMethodDecl() != 0; 7796 } 7797 7798 /// Is the given expression (which must be 'const') a reference to a 7799 /// variable which was originally non-const, but which has become 7800 /// 'const' due to being captured within a block? 7801 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7802 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7803 assert(E->isLValue() && E->getType().isConstQualified()); 7804 E = E->IgnoreParens(); 7805 7806 // Must be a reference to a declaration from an enclosing scope. 7807 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7808 if (!DRE) return NCCK_None; 7809 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7810 7811 // The declaration must be a variable which is not declared 'const'. 7812 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7813 if (!var) return NCCK_None; 7814 if (var->getType().isConstQualified()) return NCCK_None; 7815 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7816 7817 // Decide whether the first capture was for a block or a lambda. 7818 DeclContext *DC = S.CurContext; 7819 while (DC->getParent() != var->getDeclContext()) 7820 DC = DC->getParent(); 7821 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7822 } 7823 7824 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7825 /// emit an error and return true. If so, return false. 7826 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7827 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7828 SourceLocation OrigLoc = Loc; 7829 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7830 &Loc); 7831 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7832 IsLV = Expr::MLV_ReadonlyProperty; 7833 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7834 IsLV = Expr::MLV_InvalidMessageExpression; 7835 if (IsLV == Expr::MLV_Valid) 7836 return false; 7837 7838 unsigned Diag = 0; 7839 bool NeedType = false; 7840 switch (IsLV) { // C99 6.5.16p2 7841 case Expr::MLV_ConstQualified: 7842 Diag = diag::err_typecheck_assign_const; 7843 7844 // Use a specialized diagnostic when we're assigning to an object 7845 // from an enclosing function or block. 7846 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7847 if (NCCK == NCCK_Block) 7848 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7849 else 7850 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7851 break; 7852 } 7853 7854 // In ARC, use some specialized diagnostics for occasions where we 7855 // infer 'const'. These are always pseudo-strong variables. 7856 if (S.getLangOpts().ObjCAutoRefCount) { 7857 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7858 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7859 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7860 7861 // Use the normal diagnostic if it's pseudo-__strong but the 7862 // user actually wrote 'const'. 7863 if (var->isARCPseudoStrong() && 7864 (!var->getTypeSourceInfo() || 7865 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7866 // There are two pseudo-strong cases: 7867 // - self 7868 ObjCMethodDecl *method = S.getCurMethodDecl(); 7869 if (method && var == method->getSelfDecl()) 7870 Diag = method->isClassMethod() 7871 ? diag::err_typecheck_arc_assign_self_class_method 7872 : diag::err_typecheck_arc_assign_self; 7873 7874 // - fast enumeration variables 7875 else 7876 Diag = diag::err_typecheck_arr_assign_enumeration; 7877 7878 SourceRange Assign; 7879 if (Loc != OrigLoc) 7880 Assign = SourceRange(OrigLoc, OrigLoc); 7881 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7882 // We need to preserve the AST regardless, so migration tool 7883 // can do its job. 7884 return false; 7885 } 7886 } 7887 } 7888 7889 break; 7890 case Expr::MLV_ArrayType: 7891 case Expr::MLV_ArrayTemporary: 7892 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7893 NeedType = true; 7894 break; 7895 case Expr::MLV_NotObjectType: 7896 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7897 NeedType = true; 7898 break; 7899 case Expr::MLV_LValueCast: 7900 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7901 break; 7902 case Expr::MLV_Valid: 7903 llvm_unreachable("did not take early return for MLV_Valid"); 7904 case Expr::MLV_InvalidExpression: 7905 case Expr::MLV_MemberFunction: 7906 case Expr::MLV_ClassTemporary: 7907 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7908 break; 7909 case Expr::MLV_IncompleteType: 7910 case Expr::MLV_IncompleteVoidType: 7911 return S.RequireCompleteType(Loc, E->getType(), 7912 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 7913 case Expr::MLV_DuplicateVectorComponents: 7914 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7915 break; 7916 case Expr::MLV_ReadonlyProperty: 7917 case Expr::MLV_NoSetterProperty: 7918 llvm_unreachable("readonly properties should be processed differently"); 7919 case Expr::MLV_InvalidMessageExpression: 7920 Diag = diag::error_readonly_message_assignment; 7921 break; 7922 case Expr::MLV_SubObjCPropertySetting: 7923 Diag = diag::error_no_subobject_property_setting; 7924 break; 7925 } 7926 7927 SourceRange Assign; 7928 if (Loc != OrigLoc) 7929 Assign = SourceRange(OrigLoc, OrigLoc); 7930 if (NeedType) 7931 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7932 else 7933 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7934 return true; 7935 } 7936 7937 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 7938 SourceLocation Loc, 7939 Sema &Sema) { 7940 // C / C++ fields 7941 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 7942 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 7943 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 7944 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 7945 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 7946 } 7947 7948 // Objective-C instance variables 7949 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 7950 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 7951 if (OL && OR && OL->getDecl() == OR->getDecl()) { 7952 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 7953 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 7954 if (RL && RR && RL->getDecl() == RR->getDecl()) 7955 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 7956 } 7957 } 7958 7959 // C99 6.5.16.1 7960 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7961 SourceLocation Loc, 7962 QualType CompoundType) { 7963 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7964 7965 // Verify that LHS is a modifiable lvalue, and emit error if not. 7966 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 7967 return QualType(); 7968 7969 QualType LHSType = LHSExpr->getType(); 7970 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7971 CompoundType; 7972 AssignConvertType ConvTy; 7973 if (CompoundType.isNull()) { 7974 Expr *RHSCheck = RHS.get(); 7975 7976 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 7977 7978 QualType LHSTy(LHSType); 7979 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7980 if (RHS.isInvalid()) 7981 return QualType(); 7982 // Special case of NSObject attributes on c-style pointer types. 7983 if (ConvTy == IncompatiblePointer && 7984 ((Context.isObjCNSObjectType(LHSType) && 7985 RHSType->isObjCObjectPointerType()) || 7986 (Context.isObjCNSObjectType(RHSType) && 7987 LHSType->isObjCObjectPointerType()))) 7988 ConvTy = Compatible; 7989 7990 if (ConvTy == Compatible && 7991 LHSType->isObjCObjectType()) 7992 Diag(Loc, diag::err_objc_object_assignment) 7993 << LHSType; 7994 7995 // If the RHS is a unary plus or minus, check to see if they = and + are 7996 // right next to each other. If so, the user may have typo'd "x =+ 4" 7997 // instead of "x += 4". 7998 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7999 RHSCheck = ICE->getSubExpr(); 8000 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8001 if ((UO->getOpcode() == UO_Plus || 8002 UO->getOpcode() == UO_Minus) && 8003 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8004 // Only if the two operators are exactly adjacent. 8005 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8006 // And there is a space or other character before the subexpr of the 8007 // unary +/-. We don't want to warn on "x=-1". 8008 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8009 UO->getSubExpr()->getLocStart().isFileID()) { 8010 Diag(Loc, diag::warn_not_compound_assign) 8011 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8012 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8013 } 8014 } 8015 8016 if (ConvTy == Compatible) { 8017 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8018 // Warn about retain cycles where a block captures the LHS, but 8019 // not if the LHS is a simple variable into which the block is 8020 // being stored...unless that variable can be captured by reference! 8021 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8022 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8023 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8024 checkRetainCycles(LHSExpr, RHS.get()); 8025 8026 // It is safe to assign a weak reference into a strong variable. 8027 // Although this code can still have problems: 8028 // id x = self.weakProp; 8029 // id y = self.weakProp; 8030 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8031 // paths through the function. This should be revisited if 8032 // -Wrepeated-use-of-weak is made flow-sensitive. 8033 DiagnosticsEngine::Level Level = 8034 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8035 RHS.get()->getLocStart()); 8036 if (Level != DiagnosticsEngine::Ignored) 8037 getCurFunction()->markSafeWeakUse(RHS.get()); 8038 8039 } else if (getLangOpts().ObjCAutoRefCount) { 8040 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8041 } 8042 } 8043 } else { 8044 // Compound assignment "x += y" 8045 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8046 } 8047 8048 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8049 RHS.get(), AA_Assigning)) 8050 return QualType(); 8051 8052 CheckForNullPointerDereference(*this, LHSExpr); 8053 8054 // C99 6.5.16p3: The type of an assignment expression is the type of the 8055 // left operand unless the left operand has qualified type, in which case 8056 // it is the unqualified version of the type of the left operand. 8057 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8058 // is converted to the type of the assignment expression (above). 8059 // C++ 5.17p1: the type of the assignment expression is that of its left 8060 // operand. 8061 return (getLangOpts().CPlusPlus 8062 ? LHSType : LHSType.getUnqualifiedType()); 8063 } 8064 8065 // C99 6.5.17 8066 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8067 SourceLocation Loc) { 8068 LHS = S.CheckPlaceholderExpr(LHS.take()); 8069 RHS = S.CheckPlaceholderExpr(RHS.take()); 8070 if (LHS.isInvalid() || RHS.isInvalid()) 8071 return QualType(); 8072 8073 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8074 // operands, but not unary promotions. 8075 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8076 8077 // So we treat the LHS as a ignored value, and in C++ we allow the 8078 // containing site to determine what should be done with the RHS. 8079 LHS = S.IgnoredValueConversions(LHS.take()); 8080 if (LHS.isInvalid()) 8081 return QualType(); 8082 8083 S.DiagnoseUnusedExprResult(LHS.get()); 8084 8085 if (!S.getLangOpts().CPlusPlus) { 8086 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8087 if (RHS.isInvalid()) 8088 return QualType(); 8089 if (!RHS.get()->getType()->isVoidType()) 8090 S.RequireCompleteType(Loc, RHS.get()->getType(), 8091 diag::err_incomplete_type); 8092 } 8093 8094 return RHS.get()->getType(); 8095 } 8096 8097 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8098 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8099 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8100 ExprValueKind &VK, 8101 SourceLocation OpLoc, 8102 bool IsInc, bool IsPrefix) { 8103 if (Op->isTypeDependent()) 8104 return S.Context.DependentTy; 8105 8106 QualType ResType = Op->getType(); 8107 // Atomic types can be used for increment / decrement where the non-atomic 8108 // versions can, so ignore the _Atomic() specifier for the purpose of 8109 // checking. 8110 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8111 ResType = ResAtomicType->getValueType(); 8112 8113 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8114 8115 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8116 // Decrement of bool is not allowed. 8117 if (!IsInc) { 8118 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8119 return QualType(); 8120 } 8121 // Increment of bool sets it to true, but is deprecated. 8122 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8123 } else if (ResType->isRealType()) { 8124 // OK! 8125 } else if (ResType->isPointerType()) { 8126 // C99 6.5.2.4p2, 6.5.6p2 8127 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8128 return QualType(); 8129 } else if (ResType->isObjCObjectPointerType()) { 8130 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8131 // Otherwise, we just need a complete type. 8132 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8133 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8134 return QualType(); 8135 } else if (ResType->isAnyComplexType()) { 8136 // C99 does not support ++/-- on complex types, we allow as an extension. 8137 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8138 << ResType << Op->getSourceRange(); 8139 } else if (ResType->isPlaceholderType()) { 8140 ExprResult PR = S.CheckPlaceholderExpr(Op); 8141 if (PR.isInvalid()) return QualType(); 8142 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8143 IsInc, IsPrefix); 8144 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8145 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8146 } else { 8147 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8148 << ResType << int(IsInc) << Op->getSourceRange(); 8149 return QualType(); 8150 } 8151 // At this point, we know we have a real, complex or pointer type. 8152 // Now make sure the operand is a modifiable lvalue. 8153 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8154 return QualType(); 8155 // In C++, a prefix increment is the same type as the operand. Otherwise 8156 // (in C or with postfix), the increment is the unqualified type of the 8157 // operand. 8158 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8159 VK = VK_LValue; 8160 return ResType; 8161 } else { 8162 VK = VK_RValue; 8163 return ResType.getUnqualifiedType(); 8164 } 8165 } 8166 8167 8168 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8169 /// This routine allows us to typecheck complex/recursive expressions 8170 /// where the declaration is needed for type checking. We only need to 8171 /// handle cases when the expression references a function designator 8172 /// or is an lvalue. Here are some examples: 8173 /// - &(x) => x 8174 /// - &*****f => f for f a function designator. 8175 /// - &s.xx => s 8176 /// - &s.zz[1].yy -> s, if zz is an array 8177 /// - *(x + 1) -> x, if x is an array 8178 /// - &"123"[2] -> 0 8179 /// - & __real__ x -> x 8180 static ValueDecl *getPrimaryDecl(Expr *E) { 8181 switch (E->getStmtClass()) { 8182 case Stmt::DeclRefExprClass: 8183 return cast<DeclRefExpr>(E)->getDecl(); 8184 case Stmt::MemberExprClass: 8185 // If this is an arrow operator, the address is an offset from 8186 // the base's value, so the object the base refers to is 8187 // irrelevant. 8188 if (cast<MemberExpr>(E)->isArrow()) 8189 return 0; 8190 // Otherwise, the expression refers to a part of the base 8191 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8192 case Stmt::ArraySubscriptExprClass: { 8193 // FIXME: This code shouldn't be necessary! We should catch the implicit 8194 // promotion of register arrays earlier. 8195 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8196 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8197 if (ICE->getSubExpr()->getType()->isArrayType()) 8198 return getPrimaryDecl(ICE->getSubExpr()); 8199 } 8200 return 0; 8201 } 8202 case Stmt::UnaryOperatorClass: { 8203 UnaryOperator *UO = cast<UnaryOperator>(E); 8204 8205 switch(UO->getOpcode()) { 8206 case UO_Real: 8207 case UO_Imag: 8208 case UO_Extension: 8209 return getPrimaryDecl(UO->getSubExpr()); 8210 default: 8211 return 0; 8212 } 8213 } 8214 case Stmt::ParenExprClass: 8215 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8216 case Stmt::ImplicitCastExprClass: 8217 // If the result of an implicit cast is an l-value, we care about 8218 // the sub-expression; otherwise, the result here doesn't matter. 8219 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8220 default: 8221 return 0; 8222 } 8223 } 8224 8225 namespace { 8226 enum { 8227 AO_Bit_Field = 0, 8228 AO_Vector_Element = 1, 8229 AO_Property_Expansion = 2, 8230 AO_Register_Variable = 3, 8231 AO_No_Error = 4 8232 }; 8233 } 8234 /// \brief Diagnose invalid operand for address of operations. 8235 /// 8236 /// \param Type The type of operand which cannot have its address taken. 8237 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8238 Expr *E, unsigned Type) { 8239 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8240 } 8241 8242 /// CheckAddressOfOperand - The operand of & must be either a function 8243 /// designator or an lvalue designating an object. If it is an lvalue, the 8244 /// object cannot be declared with storage class register or be a bit field. 8245 /// Note: The usual conversions are *not* applied to the operand of the & 8246 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8247 /// In C++, the operand might be an overloaded function name, in which case 8248 /// we allow the '&' but retain the overloaded-function type. 8249 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 8250 SourceLocation OpLoc) { 8251 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8252 if (PTy->getKind() == BuiltinType::Overload) { 8253 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 8254 assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode() 8255 == UO_AddrOf); 8256 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8257 << OrigOp.get()->getSourceRange(); 8258 return QualType(); 8259 } 8260 8261 return S.Context.OverloadTy; 8262 } 8263 8264 if (PTy->getKind() == BuiltinType::UnknownAny) 8265 return S.Context.UnknownAnyTy; 8266 8267 if (PTy->getKind() == BuiltinType::BoundMember) { 8268 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8269 << OrigOp.get()->getSourceRange(); 8270 return QualType(); 8271 } 8272 8273 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 8274 if (OrigOp.isInvalid()) return QualType(); 8275 } 8276 8277 if (OrigOp.get()->isTypeDependent()) 8278 return S.Context.DependentTy; 8279 8280 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8281 8282 // Make sure to ignore parentheses in subsequent checks 8283 Expr *op = OrigOp.get()->IgnoreParens(); 8284 8285 if (S.getLangOpts().C99) { 8286 // Implement C99-only parts of addressof rules. 8287 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8288 if (uOp->getOpcode() == UO_Deref) 8289 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8290 // (assuming the deref expression is valid). 8291 return uOp->getSubExpr()->getType(); 8292 } 8293 // Technically, there should be a check for array subscript 8294 // expressions here, but the result of one is always an lvalue anyway. 8295 } 8296 ValueDecl *dcl = getPrimaryDecl(op); 8297 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 8298 unsigned AddressOfError = AO_No_Error; 8299 8300 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8301 bool sfinae = (bool)S.isSFINAEContext(); 8302 S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8303 : diag::ext_typecheck_addrof_temporary) 8304 << op->getType() << op->getSourceRange(); 8305 if (sfinae) 8306 return QualType(); 8307 } else if (isa<ObjCSelectorExpr>(op)) { 8308 return S.Context.getPointerType(op->getType()); 8309 } else if (lval == Expr::LV_MemberFunction) { 8310 // If it's an instance method, make a member pointer. 8311 // The expression must have exactly the form &A::foo. 8312 8313 // If the underlying expression isn't a decl ref, give up. 8314 if (!isa<DeclRefExpr>(op)) { 8315 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8316 << OrigOp.get()->getSourceRange(); 8317 return QualType(); 8318 } 8319 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8320 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8321 8322 // The id-expression was parenthesized. 8323 if (OrigOp.get() != DRE) { 8324 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 8325 << OrigOp.get()->getSourceRange(); 8326 8327 // The method was named without a qualifier. 8328 } else if (!DRE->getQualifier()) { 8329 if (MD->getParent()->getName().empty()) 8330 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8331 << op->getSourceRange(); 8332 else { 8333 SmallString<32> Str; 8334 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8335 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8336 << op->getSourceRange() 8337 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8338 } 8339 } 8340 8341 return S.Context.getMemberPointerType(op->getType(), 8342 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8343 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8344 // C99 6.5.3.2p1 8345 // The operand must be either an l-value or a function designator 8346 if (!op->getType()->isFunctionType()) { 8347 // Use a special diagnostic for loads from property references. 8348 if (isa<PseudoObjectExpr>(op)) { 8349 AddressOfError = AO_Property_Expansion; 8350 } else { 8351 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8352 << op->getType() << op->getSourceRange(); 8353 return QualType(); 8354 } 8355 } 8356 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8357 // The operand cannot be a bit-field 8358 AddressOfError = AO_Bit_Field; 8359 } else if (op->getObjectKind() == OK_VectorComponent) { 8360 // The operand cannot be an element of a vector 8361 AddressOfError = AO_Vector_Element; 8362 } else if (dcl) { // C99 6.5.3.2p1 8363 // We have an lvalue with a decl. Make sure the decl is not declared 8364 // with the register storage-class specifier. 8365 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8366 // in C++ it is not error to take address of a register 8367 // variable (c++03 7.1.1P3) 8368 if (vd->getStorageClass() == SC_Register && 8369 !S.getLangOpts().CPlusPlus) { 8370 AddressOfError = AO_Register_Variable; 8371 } 8372 } else if (isa<FunctionTemplateDecl>(dcl)) { 8373 return S.Context.OverloadTy; 8374 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8375 // Okay: we can take the address of a field. 8376 // Could be a pointer to member, though, if there is an explicit 8377 // scope qualifier for the class. 8378 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8379 DeclContext *Ctx = dcl->getDeclContext(); 8380 if (Ctx && Ctx->isRecord()) { 8381 if (dcl->getType()->isReferenceType()) { 8382 S.Diag(OpLoc, 8383 diag::err_cannot_form_pointer_to_member_of_reference_type) 8384 << dcl->getDeclName() << dcl->getType(); 8385 return QualType(); 8386 } 8387 8388 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8389 Ctx = Ctx->getParent(); 8390 return S.Context.getMemberPointerType(op->getType(), 8391 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8392 } 8393 } 8394 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8395 llvm_unreachable("Unknown/unexpected decl type"); 8396 } 8397 8398 if (AddressOfError != AO_No_Error) { 8399 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 8400 return QualType(); 8401 } 8402 8403 if (lval == Expr::LV_IncompleteVoidType) { 8404 // Taking the address of a void variable is technically illegal, but we 8405 // allow it in cases which are otherwise valid. 8406 // Example: "extern void x; void* y = &x;". 8407 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8408 } 8409 8410 // If the operand has type "type", the result has type "pointer to type". 8411 if (op->getType()->isObjCObjectType()) 8412 return S.Context.getObjCObjectPointerType(op->getType()); 8413 return S.Context.getPointerType(op->getType()); 8414 } 8415 8416 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8417 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8418 SourceLocation OpLoc) { 8419 if (Op->isTypeDependent()) 8420 return S.Context.DependentTy; 8421 8422 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8423 if (ConvResult.isInvalid()) 8424 return QualType(); 8425 Op = ConvResult.take(); 8426 QualType OpTy = Op->getType(); 8427 QualType Result; 8428 8429 if (isa<CXXReinterpretCastExpr>(Op)) { 8430 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8431 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8432 Op->getSourceRange()); 8433 } 8434 8435 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8436 // is an incomplete type or void. It would be possible to warn about 8437 // dereferencing a void pointer, but it's completely well-defined, and such a 8438 // warning is unlikely to catch any mistakes. 8439 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8440 Result = PT->getPointeeType(); 8441 else if (const ObjCObjectPointerType *OPT = 8442 OpTy->getAs<ObjCObjectPointerType>()) 8443 Result = OPT->getPointeeType(); 8444 else { 8445 ExprResult PR = S.CheckPlaceholderExpr(Op); 8446 if (PR.isInvalid()) return QualType(); 8447 if (PR.take() != Op) 8448 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8449 } 8450 8451 if (Result.isNull()) { 8452 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8453 << OpTy << Op->getSourceRange(); 8454 return QualType(); 8455 } 8456 8457 // Dereferences are usually l-values... 8458 VK = VK_LValue; 8459 8460 // ...except that certain expressions are never l-values in C. 8461 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8462 VK = VK_RValue; 8463 8464 return Result; 8465 } 8466 8467 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8468 tok::TokenKind Kind) { 8469 BinaryOperatorKind Opc; 8470 switch (Kind) { 8471 default: llvm_unreachable("Unknown binop!"); 8472 case tok::periodstar: Opc = BO_PtrMemD; break; 8473 case tok::arrowstar: Opc = BO_PtrMemI; break; 8474 case tok::star: Opc = BO_Mul; break; 8475 case tok::slash: Opc = BO_Div; break; 8476 case tok::percent: Opc = BO_Rem; break; 8477 case tok::plus: Opc = BO_Add; break; 8478 case tok::minus: Opc = BO_Sub; break; 8479 case tok::lessless: Opc = BO_Shl; break; 8480 case tok::greatergreater: Opc = BO_Shr; break; 8481 case tok::lessequal: Opc = BO_LE; break; 8482 case tok::less: Opc = BO_LT; break; 8483 case tok::greaterequal: Opc = BO_GE; break; 8484 case tok::greater: Opc = BO_GT; break; 8485 case tok::exclaimequal: Opc = BO_NE; break; 8486 case tok::equalequal: Opc = BO_EQ; break; 8487 case tok::amp: Opc = BO_And; break; 8488 case tok::caret: Opc = BO_Xor; break; 8489 case tok::pipe: Opc = BO_Or; break; 8490 case tok::ampamp: Opc = BO_LAnd; break; 8491 case tok::pipepipe: Opc = BO_LOr; break; 8492 case tok::equal: Opc = BO_Assign; break; 8493 case tok::starequal: Opc = BO_MulAssign; break; 8494 case tok::slashequal: Opc = BO_DivAssign; break; 8495 case tok::percentequal: Opc = BO_RemAssign; break; 8496 case tok::plusequal: Opc = BO_AddAssign; break; 8497 case tok::minusequal: Opc = BO_SubAssign; break; 8498 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8499 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8500 case tok::ampequal: Opc = BO_AndAssign; break; 8501 case tok::caretequal: Opc = BO_XorAssign; break; 8502 case tok::pipeequal: Opc = BO_OrAssign; break; 8503 case tok::comma: Opc = BO_Comma; break; 8504 } 8505 return Opc; 8506 } 8507 8508 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8509 tok::TokenKind Kind) { 8510 UnaryOperatorKind Opc; 8511 switch (Kind) { 8512 default: llvm_unreachable("Unknown unary op!"); 8513 case tok::plusplus: Opc = UO_PreInc; break; 8514 case tok::minusminus: Opc = UO_PreDec; break; 8515 case tok::amp: Opc = UO_AddrOf; break; 8516 case tok::star: Opc = UO_Deref; break; 8517 case tok::plus: Opc = UO_Plus; break; 8518 case tok::minus: Opc = UO_Minus; break; 8519 case tok::tilde: Opc = UO_Not; break; 8520 case tok::exclaim: Opc = UO_LNot; break; 8521 case tok::kw___real: Opc = UO_Real; break; 8522 case tok::kw___imag: Opc = UO_Imag; break; 8523 case tok::kw___extension__: Opc = UO_Extension; break; 8524 } 8525 return Opc; 8526 } 8527 8528 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8529 /// This warning is only emitted for builtin assignment operations. It is also 8530 /// suppressed in the event of macro expansions. 8531 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8532 SourceLocation OpLoc) { 8533 if (!S.ActiveTemplateInstantiations.empty()) 8534 return; 8535 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8536 return; 8537 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8538 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8539 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8540 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8541 if (!LHSDeclRef || !RHSDeclRef || 8542 LHSDeclRef->getLocation().isMacroID() || 8543 RHSDeclRef->getLocation().isMacroID()) 8544 return; 8545 const ValueDecl *LHSDecl = 8546 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8547 const ValueDecl *RHSDecl = 8548 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8549 if (LHSDecl != RHSDecl) 8550 return; 8551 if (LHSDecl->getType().isVolatileQualified()) 8552 return; 8553 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8554 if (RefTy->getPointeeType().isVolatileQualified()) 8555 return; 8556 8557 S.Diag(OpLoc, diag::warn_self_assignment) 8558 << LHSDeclRef->getType() 8559 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8560 } 8561 8562 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 8563 /// operator @p Opc at location @c TokLoc. This routine only supports 8564 /// built-in operations; ActOnBinOp handles overloaded operators. 8565 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8566 BinaryOperatorKind Opc, 8567 Expr *LHSExpr, Expr *RHSExpr) { 8568 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 8569 // The syntax only allows initializer lists on the RHS of assignment, 8570 // so we don't need to worry about accepting invalid code for 8571 // non-assignment operators. 8572 // C++11 5.17p9: 8573 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8574 // of x = {} is x = T(). 8575 InitializationKind Kind = 8576 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8577 InitializedEntity Entity = 8578 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8579 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1); 8580 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8581 if (Init.isInvalid()) 8582 return Init; 8583 RHSExpr = Init.take(); 8584 } 8585 8586 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8587 QualType ResultTy; // Result type of the binary operator. 8588 // The following two variables are used for compound assignment operators 8589 QualType CompLHSTy; // Type of LHS after promotions for computation 8590 QualType CompResultTy; // Type of computation result 8591 ExprValueKind VK = VK_RValue; 8592 ExprObjectKind OK = OK_Ordinary; 8593 8594 switch (Opc) { 8595 case BO_Assign: 8596 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8597 if (getLangOpts().CPlusPlus && 8598 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8599 VK = LHS.get()->getValueKind(); 8600 OK = LHS.get()->getObjectKind(); 8601 } 8602 if (!ResultTy.isNull()) 8603 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8604 break; 8605 case BO_PtrMemD: 8606 case BO_PtrMemI: 8607 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8608 Opc == BO_PtrMemI); 8609 break; 8610 case BO_Mul: 8611 case BO_Div: 8612 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8613 Opc == BO_Div); 8614 break; 8615 case BO_Rem: 8616 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8617 break; 8618 case BO_Add: 8619 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8620 break; 8621 case BO_Sub: 8622 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8623 break; 8624 case BO_Shl: 8625 case BO_Shr: 8626 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8627 break; 8628 case BO_LE: 8629 case BO_LT: 8630 case BO_GE: 8631 case BO_GT: 8632 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8633 break; 8634 case BO_EQ: 8635 case BO_NE: 8636 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8637 break; 8638 case BO_And: 8639 case BO_Xor: 8640 case BO_Or: 8641 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8642 break; 8643 case BO_LAnd: 8644 case BO_LOr: 8645 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8646 break; 8647 case BO_MulAssign: 8648 case BO_DivAssign: 8649 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8650 Opc == BO_DivAssign); 8651 CompLHSTy = CompResultTy; 8652 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8653 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8654 break; 8655 case BO_RemAssign: 8656 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8657 CompLHSTy = CompResultTy; 8658 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8659 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8660 break; 8661 case BO_AddAssign: 8662 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8663 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8664 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8665 break; 8666 case BO_SubAssign: 8667 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8668 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8669 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8670 break; 8671 case BO_ShlAssign: 8672 case BO_ShrAssign: 8673 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 8674 CompLHSTy = CompResultTy; 8675 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8676 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8677 break; 8678 case BO_AndAssign: 8679 case BO_XorAssign: 8680 case BO_OrAssign: 8681 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8682 CompLHSTy = CompResultTy; 8683 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8684 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8685 break; 8686 case BO_Comma: 8687 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8688 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8689 VK = RHS.get()->getValueKind(); 8690 OK = RHS.get()->getObjectKind(); 8691 } 8692 break; 8693 } 8694 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8695 return ExprError(); 8696 8697 // Check for array bounds violations for both sides of the BinaryOperator 8698 CheckArrayAccess(LHS.get()); 8699 CheckArrayAccess(RHS.get()); 8700 8701 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 8702 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 8703 &Context.Idents.get("object_setClass"), 8704 SourceLocation(), LookupOrdinaryName); 8705 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 8706 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8707 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 8708 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 8709 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 8710 FixItHint::CreateInsertion(RHSLocEnd, ")"); 8711 } 8712 else 8713 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 8714 } 8715 else if (const ObjCIvarRefExpr *OIRE = 8716 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 8717 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 8718 8719 if (CompResultTy.isNull()) 8720 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8721 ResultTy, VK, OK, OpLoc, 8722 FPFeatures.fp_contract)); 8723 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8724 OK_ObjCProperty) { 8725 VK = VK_LValue; 8726 OK = LHS.get()->getObjectKind(); 8727 } 8728 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8729 ResultTy, VK, OK, CompLHSTy, 8730 CompResultTy, OpLoc, 8731 FPFeatures.fp_contract)); 8732 } 8733 8734 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8735 /// operators are mixed in a way that suggests that the programmer forgot that 8736 /// comparison operators have higher precedence. The most typical example of 8737 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8738 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8739 SourceLocation OpLoc, Expr *LHSExpr, 8740 Expr *RHSExpr) { 8741 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 8742 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 8743 8744 // Check that one of the sides is a comparison operator. 8745 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 8746 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 8747 if (!isLeftComp && !isRightComp) 8748 return; 8749 8750 // Bitwise operations are sometimes used as eager logical ops. 8751 // Don't diagnose this. 8752 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 8753 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 8754 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 8755 return; 8756 8757 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8758 OpLoc) 8759 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8760 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 8761 SourceRange ParensRange = isLeftComp ? 8762 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 8763 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 8764 8765 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8766 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 8767 SuggestParentheses(Self, OpLoc, 8768 Self.PDiag(diag::note_precedence_silence) << OpStr, 8769 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 8770 SuggestParentheses(Self, OpLoc, 8771 Self.PDiag(diag::note_precedence_bitwise_first) 8772 << BinaryOperator::getOpcodeStr(Opc), 8773 ParensRange); 8774 } 8775 8776 /// \brief It accepts a '&' expr that is inside a '|' one. 8777 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8778 /// in parentheses. 8779 static void 8780 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8781 BinaryOperator *Bop) { 8782 assert(Bop->getOpcode() == BO_And); 8783 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8784 << Bop->getSourceRange() << OpLoc; 8785 SuggestParentheses(Self, Bop->getOperatorLoc(), 8786 Self.PDiag(diag::note_precedence_silence) 8787 << Bop->getOpcodeStr(), 8788 Bop->getSourceRange()); 8789 } 8790 8791 /// \brief It accepts a '&&' expr that is inside a '||' one. 8792 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8793 /// in parentheses. 8794 static void 8795 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8796 BinaryOperator *Bop) { 8797 assert(Bop->getOpcode() == BO_LAnd); 8798 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8799 << Bop->getSourceRange() << OpLoc; 8800 SuggestParentheses(Self, Bop->getOperatorLoc(), 8801 Self.PDiag(diag::note_precedence_silence) 8802 << Bop->getOpcodeStr(), 8803 Bop->getSourceRange()); 8804 } 8805 8806 /// \brief Returns true if the given expression can be evaluated as a constant 8807 /// 'true'. 8808 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8809 bool Res; 8810 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8811 } 8812 8813 /// \brief Returns true if the given expression can be evaluated as a constant 8814 /// 'false'. 8815 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8816 bool Res; 8817 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8818 } 8819 8820 /// \brief Look for '&&' in the left hand of a '||' expr. 8821 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8822 Expr *LHSExpr, Expr *RHSExpr) { 8823 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8824 if (Bop->getOpcode() == BO_LAnd) { 8825 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8826 if (EvaluatesAsFalse(S, RHSExpr)) 8827 return; 8828 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8829 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8830 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8831 } else if (Bop->getOpcode() == BO_LOr) { 8832 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8833 // If it's "a || b && 1 || c" we didn't warn earlier for 8834 // "a || b && 1", but warn now. 8835 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8836 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8837 } 8838 } 8839 } 8840 } 8841 8842 /// \brief Look for '&&' in the right hand of a '||' expr. 8843 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8844 Expr *LHSExpr, Expr *RHSExpr) { 8845 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8846 if (Bop->getOpcode() == BO_LAnd) { 8847 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8848 if (EvaluatesAsFalse(S, LHSExpr)) 8849 return; 8850 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8851 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8852 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8853 } 8854 } 8855 } 8856 8857 /// \brief Look for '&' in the left or right hand of a '|' expr. 8858 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 8859 Expr *OrArg) { 8860 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 8861 if (Bop->getOpcode() == BO_And) 8862 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 8863 } 8864 } 8865 8866 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 8867 Expr *SubExpr, StringRef Shift) { 8868 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 8869 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 8870 StringRef Op = Bop->getOpcodeStr(); 8871 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 8872 << Bop->getSourceRange() << OpLoc << Shift << Op; 8873 SuggestParentheses(S, Bop->getOperatorLoc(), 8874 S.PDiag(diag::note_precedence_silence) << Op, 8875 Bop->getSourceRange()); 8876 } 8877 } 8878 } 8879 8880 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 8881 Expr *LHSExpr, Expr *RHSExpr) { 8882 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 8883 if (!OCE) 8884 return; 8885 8886 FunctionDecl *FD = OCE->getDirectCallee(); 8887 if (!FD || !FD->isOverloadedOperator()) 8888 return; 8889 8890 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 8891 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 8892 return; 8893 8894 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 8895 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 8896 << (Kind == OO_LessLess); 8897 SuggestParentheses(S, OCE->getOperatorLoc(), 8898 S.PDiag(diag::note_precedence_silence) 8899 << (Kind == OO_LessLess ? "<<" : ">>"), 8900 OCE->getSourceRange()); 8901 SuggestParentheses(S, OpLoc, 8902 S.PDiag(diag::note_evaluate_comparison_first), 8903 SourceRange(OCE->getArg(1)->getLocStart(), 8904 RHSExpr->getLocEnd())); 8905 } 8906 8907 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8908 /// precedence. 8909 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8910 SourceLocation OpLoc, Expr *LHSExpr, 8911 Expr *RHSExpr){ 8912 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8913 if (BinaryOperator::isBitwiseOp(Opc)) 8914 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 8915 8916 // Diagnose "arg1 & arg2 | arg3" 8917 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8918 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 8919 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 8920 } 8921 8922 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 8923 // We don't warn for 'assert(a || b && "bad")' since this is safe. 8924 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8925 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 8926 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 8927 } 8928 8929 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 8930 || Opc == BO_Shr) { 8931 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 8932 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 8933 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 8934 } 8935 8936 // Warn on overloaded shift operators and comparisons, such as: 8937 // cout << 5 == 4; 8938 if (BinaryOperator::isComparisonOp(Opc)) 8939 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 8940 } 8941 8942 // Binary Operators. 'Tok' is the token for the operator. 8943 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 8944 tok::TokenKind Kind, 8945 Expr *LHSExpr, Expr *RHSExpr) { 8946 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 8947 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 8948 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 8949 8950 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 8951 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 8952 8953 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 8954 } 8955 8956 /// Build an overloaded binary operator expression in the given scope. 8957 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 8958 BinaryOperatorKind Opc, 8959 Expr *LHS, Expr *RHS) { 8960 // Find all of the overloaded operators visible from this 8961 // point. We perform both an operator-name lookup from the local 8962 // scope and an argument-dependent lookup based on the types of 8963 // the arguments. 8964 UnresolvedSet<16> Functions; 8965 OverloadedOperatorKind OverOp 8966 = BinaryOperator::getOverloadedOperator(Opc); 8967 if (Sc && OverOp != OO_None) 8968 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 8969 RHS->getType(), Functions); 8970 8971 // Build the (potentially-overloaded, potentially-dependent) 8972 // binary operation. 8973 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 8974 } 8975 8976 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8977 BinaryOperatorKind Opc, 8978 Expr *LHSExpr, Expr *RHSExpr) { 8979 // We want to end up calling one of checkPseudoObjectAssignment 8980 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 8981 // both expressions are overloadable or either is type-dependent), 8982 // or CreateBuiltinBinOp (in any other case). We also want to get 8983 // any placeholder types out of the way. 8984 8985 // Handle pseudo-objects in the LHS. 8986 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 8987 // Assignments with a pseudo-object l-value need special analysis. 8988 if (pty->getKind() == BuiltinType::PseudoObject && 8989 BinaryOperator::isAssignmentOp(Opc)) 8990 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 8991 8992 // Don't resolve overloads if the other type is overloadable. 8993 if (pty->getKind() == BuiltinType::Overload) { 8994 // We can't actually test that if we still have a placeholder, 8995 // though. Fortunately, none of the exceptions we see in that 8996 // code below are valid when the LHS is an overload set. Note 8997 // that an overload set can be dependently-typed, but it never 8998 // instantiates to having an overloadable type. 8999 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9000 if (resolvedRHS.isInvalid()) return ExprError(); 9001 RHSExpr = resolvedRHS.take(); 9002 9003 if (RHSExpr->isTypeDependent() || 9004 RHSExpr->getType()->isOverloadableType()) 9005 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9006 } 9007 9008 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9009 if (LHS.isInvalid()) return ExprError(); 9010 LHSExpr = LHS.take(); 9011 } 9012 9013 // Handle pseudo-objects in the RHS. 9014 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9015 // An overload in the RHS can potentially be resolved by the type 9016 // being assigned to. 9017 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9018 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9019 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9020 9021 if (LHSExpr->getType()->isOverloadableType()) 9022 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9023 9024 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9025 } 9026 9027 // Don't resolve overloads if the other type is overloadable. 9028 if (pty->getKind() == BuiltinType::Overload && 9029 LHSExpr->getType()->isOverloadableType()) 9030 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9031 9032 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9033 if (!resolvedRHS.isUsable()) return ExprError(); 9034 RHSExpr = resolvedRHS.take(); 9035 } 9036 9037 if (getLangOpts().CPlusPlus) { 9038 // If either expression is type-dependent, always build an 9039 // overloaded op. 9040 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9041 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9042 9043 // Otherwise, build an overloaded op if either expression has an 9044 // overloadable type. 9045 if (LHSExpr->getType()->isOverloadableType() || 9046 RHSExpr->getType()->isOverloadableType()) 9047 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9048 } 9049 9050 // Build a built-in binary operation. 9051 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9052 } 9053 9054 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9055 UnaryOperatorKind Opc, 9056 Expr *InputExpr) { 9057 ExprResult Input = Owned(InputExpr); 9058 ExprValueKind VK = VK_RValue; 9059 ExprObjectKind OK = OK_Ordinary; 9060 QualType resultType; 9061 switch (Opc) { 9062 case UO_PreInc: 9063 case UO_PreDec: 9064 case UO_PostInc: 9065 case UO_PostDec: 9066 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9067 Opc == UO_PreInc || 9068 Opc == UO_PostInc, 9069 Opc == UO_PreInc || 9070 Opc == UO_PreDec); 9071 break; 9072 case UO_AddrOf: 9073 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 9074 break; 9075 case UO_Deref: { 9076 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9077 if (Input.isInvalid()) return ExprError(); 9078 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9079 break; 9080 } 9081 case UO_Plus: 9082 case UO_Minus: 9083 Input = UsualUnaryConversions(Input.take()); 9084 if (Input.isInvalid()) return ExprError(); 9085 resultType = Input.get()->getType(); 9086 if (resultType->isDependentType()) 9087 break; 9088 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9089 resultType->isVectorType()) 9090 break; 9091 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 9092 resultType->isEnumeralType()) 9093 break; 9094 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9095 Opc == UO_Plus && 9096 resultType->isPointerType()) 9097 break; 9098 9099 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9100 << resultType << Input.get()->getSourceRange()); 9101 9102 case UO_Not: // bitwise complement 9103 Input = UsualUnaryConversions(Input.take()); 9104 if (Input.isInvalid()) 9105 return ExprError(); 9106 resultType = Input.get()->getType(); 9107 if (resultType->isDependentType()) 9108 break; 9109 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9110 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9111 // C99 does not support '~' for complex conjugation. 9112 Diag(OpLoc, diag::ext_integer_complement_complex) 9113 << resultType << Input.get()->getSourceRange(); 9114 else if (resultType->hasIntegerRepresentation()) 9115 break; 9116 else if (resultType->isExtVectorType()) { 9117 if (Context.getLangOpts().OpenCL) { 9118 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9119 // on vector float types. 9120 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9121 if (!T->isIntegerType()) 9122 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9123 << resultType << Input.get()->getSourceRange()); 9124 } 9125 break; 9126 } else { 9127 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9128 << resultType << Input.get()->getSourceRange()); 9129 } 9130 break; 9131 9132 case UO_LNot: // logical negation 9133 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9134 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9135 if (Input.isInvalid()) return ExprError(); 9136 resultType = Input.get()->getType(); 9137 9138 // Though we still have to promote half FP to float... 9139 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9140 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9141 resultType = Context.FloatTy; 9142 } 9143 9144 if (resultType->isDependentType()) 9145 break; 9146 if (resultType->isScalarType()) { 9147 // C99 6.5.3.3p1: ok, fallthrough; 9148 if (Context.getLangOpts().CPlusPlus) { 9149 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9150 // operand contextually converted to bool. 9151 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9152 ScalarTypeToBooleanCastKind(resultType)); 9153 } else if (Context.getLangOpts().OpenCL && 9154 Context.getLangOpts().OpenCLVersion < 120) { 9155 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9156 // operate on scalar float types. 9157 if (!resultType->isIntegerType()) 9158 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9159 << resultType << Input.get()->getSourceRange()); 9160 } 9161 } else if (resultType->isExtVectorType()) { 9162 if (Context.getLangOpts().OpenCL && 9163 Context.getLangOpts().OpenCLVersion < 120) { 9164 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9165 // operate on vector float types. 9166 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9167 if (!T->isIntegerType()) 9168 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9169 << resultType << Input.get()->getSourceRange()); 9170 } 9171 // Vector logical not returns the signed variant of the operand type. 9172 resultType = GetSignedVectorType(resultType); 9173 break; 9174 } else { 9175 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9176 << resultType << Input.get()->getSourceRange()); 9177 } 9178 9179 // LNot always has type int. C99 6.5.3.3p5. 9180 // In C++, it's bool. C++ 5.3.1p8 9181 resultType = Context.getLogicalOperationType(); 9182 break; 9183 case UO_Real: 9184 case UO_Imag: 9185 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9186 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9187 // complex l-values to ordinary l-values and all other values to r-values. 9188 if (Input.isInvalid()) return ExprError(); 9189 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9190 if (Input.get()->getValueKind() != VK_RValue && 9191 Input.get()->getObjectKind() == OK_Ordinary) 9192 VK = Input.get()->getValueKind(); 9193 } else if (!getLangOpts().CPlusPlus) { 9194 // In C, a volatile scalar is read by __imag. In C++, it is not. 9195 Input = DefaultLvalueConversion(Input.take()); 9196 } 9197 break; 9198 case UO_Extension: 9199 resultType = Input.get()->getType(); 9200 VK = Input.get()->getValueKind(); 9201 OK = Input.get()->getObjectKind(); 9202 break; 9203 } 9204 if (resultType.isNull() || Input.isInvalid()) 9205 return ExprError(); 9206 9207 // Check for array bounds violations in the operand of the UnaryOperator, 9208 // except for the '*' and '&' operators that have to be handled specially 9209 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9210 // that are explicitly defined as valid by the standard). 9211 if (Opc != UO_AddrOf && Opc != UO_Deref) 9212 CheckArrayAccess(Input.get()); 9213 9214 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9215 VK, OK, OpLoc)); 9216 } 9217 9218 /// \brief Determine whether the given expression is a qualified member 9219 /// access expression, of a form that could be turned into a pointer to member 9220 /// with the address-of operator. 9221 static bool isQualifiedMemberAccess(Expr *E) { 9222 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9223 if (!DRE->getQualifier()) 9224 return false; 9225 9226 ValueDecl *VD = DRE->getDecl(); 9227 if (!VD->isCXXClassMember()) 9228 return false; 9229 9230 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9231 return true; 9232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9233 return Method->isInstance(); 9234 9235 return false; 9236 } 9237 9238 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9239 if (!ULE->getQualifier()) 9240 return false; 9241 9242 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9243 DEnd = ULE->decls_end(); 9244 D != DEnd; ++D) { 9245 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9246 if (Method->isInstance()) 9247 return true; 9248 } else { 9249 // Overload set does not contain methods. 9250 break; 9251 } 9252 } 9253 9254 return false; 9255 } 9256 9257 return false; 9258 } 9259 9260 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9261 UnaryOperatorKind Opc, Expr *Input) { 9262 // First things first: handle placeholders so that the 9263 // overloaded-operator check considers the right type. 9264 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9265 // Increment and decrement of pseudo-object references. 9266 if (pty->getKind() == BuiltinType::PseudoObject && 9267 UnaryOperator::isIncrementDecrementOp(Opc)) 9268 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9269 9270 // extension is always a builtin operator. 9271 if (Opc == UO_Extension) 9272 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9273 9274 // & gets special logic for several kinds of placeholder. 9275 // The builtin code knows what to do. 9276 if (Opc == UO_AddrOf && 9277 (pty->getKind() == BuiltinType::Overload || 9278 pty->getKind() == BuiltinType::UnknownAny || 9279 pty->getKind() == BuiltinType::BoundMember)) 9280 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9281 9282 // Anything else needs to be handled now. 9283 ExprResult Result = CheckPlaceholderExpr(Input); 9284 if (Result.isInvalid()) return ExprError(); 9285 Input = Result.take(); 9286 } 9287 9288 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9289 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9290 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 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 = UnaryOperator::getOverloadedOperator(Opc); 9297 if (S && OverOp != OO_None) 9298 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9299 Functions); 9300 9301 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9302 } 9303 9304 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9305 } 9306 9307 // Unary Operators. 'Tok' is the token for the operator. 9308 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9309 tok::TokenKind Op, Expr *Input) { 9310 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9311 } 9312 9313 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9314 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9315 LabelDecl *TheDecl) { 9316 TheDecl->setUsed(); 9317 // Create the AST node. The address of a label always has type 'void*'. 9318 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9319 Context.getPointerType(Context.VoidTy))); 9320 } 9321 9322 /// Given the last statement in a statement-expression, check whether 9323 /// the result is a producing expression (like a call to an 9324 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9325 /// release out of the full-expression. Otherwise, return null. 9326 /// Cannot fail. 9327 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9328 // Should always be wrapped with one of these. 9329 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9330 if (!cleanups) return 0; 9331 9332 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9333 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9334 return 0; 9335 9336 // Splice out the cast. This shouldn't modify any interesting 9337 // features of the statement. 9338 Expr *producer = cast->getSubExpr(); 9339 assert(producer->getType() == cast->getType()); 9340 assert(producer->getValueKind() == cast->getValueKind()); 9341 cleanups->setSubExpr(producer); 9342 return cleanups; 9343 } 9344 9345 void Sema::ActOnStartStmtExpr() { 9346 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9347 } 9348 9349 void Sema::ActOnStmtExprError() { 9350 // Note that function is also called by TreeTransform when leaving a 9351 // StmtExpr scope without rebuilding anything. 9352 9353 DiscardCleanupsInEvaluationContext(); 9354 PopExpressionEvaluationContext(); 9355 } 9356 9357 ExprResult 9358 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9359 SourceLocation RPLoc) { // "({..})" 9360 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9361 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9362 9363 if (hasAnyUnrecoverableErrorsInThisFunction()) 9364 DiscardCleanupsInEvaluationContext(); 9365 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9366 PopExpressionEvaluationContext(); 9367 9368 bool isFileScope 9369 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9370 if (isFileScope) 9371 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9372 9373 // FIXME: there are a variety of strange constraints to enforce here, for 9374 // example, it is not possible to goto into a stmt expression apparently. 9375 // More semantic analysis is needed. 9376 9377 // If there are sub stmts in the compound stmt, take the type of the last one 9378 // as the type of the stmtexpr. 9379 QualType Ty = Context.VoidTy; 9380 bool StmtExprMayBindToTemp = false; 9381 if (!Compound->body_empty()) { 9382 Stmt *LastStmt = Compound->body_back(); 9383 LabelStmt *LastLabelStmt = 0; 9384 // If LastStmt is a label, skip down through into the body. 9385 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9386 LastLabelStmt = Label; 9387 LastStmt = Label->getSubStmt(); 9388 } 9389 9390 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9391 // Do function/array conversion on the last expression, but not 9392 // lvalue-to-rvalue. However, initialize an unqualified type. 9393 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9394 if (LastExpr.isInvalid()) 9395 return ExprError(); 9396 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9397 9398 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9399 // In ARC, if the final expression ends in a consume, splice 9400 // the consume out and bind it later. In the alternate case 9401 // (when dealing with a retainable type), the result 9402 // initialization will create a produce. In both cases the 9403 // result will be +1, and we'll need to balance that out with 9404 // a bind. 9405 if (Expr *rebuiltLastStmt 9406 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9407 LastExpr = rebuiltLastStmt; 9408 } else { 9409 LastExpr = PerformCopyInitialization( 9410 InitializedEntity::InitializeResult(LPLoc, 9411 Ty, 9412 false), 9413 SourceLocation(), 9414 LastExpr); 9415 } 9416 9417 if (LastExpr.isInvalid()) 9418 return ExprError(); 9419 if (LastExpr.get() != 0) { 9420 if (!LastLabelStmt) 9421 Compound->setLastStmt(LastExpr.take()); 9422 else 9423 LastLabelStmt->setSubStmt(LastExpr.take()); 9424 StmtExprMayBindToTemp = true; 9425 } 9426 } 9427 } 9428 } 9429 9430 // FIXME: Check that expression type is complete/non-abstract; statement 9431 // expressions are not lvalues. 9432 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9433 if (StmtExprMayBindToTemp) 9434 return MaybeBindToTemporary(ResStmtExpr); 9435 return Owned(ResStmtExpr); 9436 } 9437 9438 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9439 TypeSourceInfo *TInfo, 9440 OffsetOfComponent *CompPtr, 9441 unsigned NumComponents, 9442 SourceLocation RParenLoc) { 9443 QualType ArgTy = TInfo->getType(); 9444 bool Dependent = ArgTy->isDependentType(); 9445 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9446 9447 // We must have at least one component that refers to the type, and the first 9448 // one is known to be a field designator. Verify that the ArgTy represents 9449 // a struct/union/class. 9450 if (!Dependent && !ArgTy->isRecordType()) 9451 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9452 << ArgTy << TypeRange); 9453 9454 // Type must be complete per C99 7.17p3 because a declaring a variable 9455 // with an incomplete type would be ill-formed. 9456 if (!Dependent 9457 && RequireCompleteType(BuiltinLoc, ArgTy, 9458 diag::err_offsetof_incomplete_type, TypeRange)) 9459 return ExprError(); 9460 9461 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9462 // GCC extension, diagnose them. 9463 // FIXME: This diagnostic isn't actually visible because the location is in 9464 // a system header! 9465 if (NumComponents != 1) 9466 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9467 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9468 9469 bool DidWarnAboutNonPOD = false; 9470 QualType CurrentType = ArgTy; 9471 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9472 SmallVector<OffsetOfNode, 4> Comps; 9473 SmallVector<Expr*, 4> Exprs; 9474 for (unsigned i = 0; i != NumComponents; ++i) { 9475 const OffsetOfComponent &OC = CompPtr[i]; 9476 if (OC.isBrackets) { 9477 // Offset of an array sub-field. TODO: Should we allow vector elements? 9478 if (!CurrentType->isDependentType()) { 9479 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9480 if(!AT) 9481 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9482 << CurrentType); 9483 CurrentType = AT->getElementType(); 9484 } else 9485 CurrentType = Context.DependentTy; 9486 9487 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9488 if (IdxRval.isInvalid()) 9489 return ExprError(); 9490 Expr *Idx = IdxRval.take(); 9491 9492 // The expression must be an integral expression. 9493 // FIXME: An integral constant expression? 9494 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9495 !Idx->getType()->isIntegerType()) 9496 return ExprError(Diag(Idx->getLocStart(), 9497 diag::err_typecheck_subscript_not_integer) 9498 << Idx->getSourceRange()); 9499 9500 // Record this array index. 9501 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9502 Exprs.push_back(Idx); 9503 continue; 9504 } 9505 9506 // Offset of a field. 9507 if (CurrentType->isDependentType()) { 9508 // We have the offset of a field, but we can't look into the dependent 9509 // type. Just record the identifier of the field. 9510 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9511 CurrentType = Context.DependentTy; 9512 continue; 9513 } 9514 9515 // We need to have a complete type to look into. 9516 if (RequireCompleteType(OC.LocStart, CurrentType, 9517 diag::err_offsetof_incomplete_type)) 9518 return ExprError(); 9519 9520 // Look for the designated field. 9521 const RecordType *RC = CurrentType->getAs<RecordType>(); 9522 if (!RC) 9523 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9524 << CurrentType); 9525 RecordDecl *RD = RC->getDecl(); 9526 9527 // C++ [lib.support.types]p5: 9528 // The macro offsetof accepts a restricted set of type arguments in this 9529 // International Standard. type shall be a POD structure or a POD union 9530 // (clause 9). 9531 // C++11 [support.types]p4: 9532 // If type is not a standard-layout class (Clause 9), the results are 9533 // undefined. 9534 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9535 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 9536 unsigned DiagID = 9537 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 9538 : diag::warn_offsetof_non_pod_type; 9539 9540 if (!IsSafe && !DidWarnAboutNonPOD && 9541 DiagRuntimeBehavior(BuiltinLoc, 0, 9542 PDiag(DiagID) 9543 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9544 << CurrentType)) 9545 DidWarnAboutNonPOD = true; 9546 } 9547 9548 // Look for the field. 9549 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9550 LookupQualifiedName(R, RD); 9551 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9552 IndirectFieldDecl *IndirectMemberDecl = 0; 9553 if (!MemberDecl) { 9554 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9555 MemberDecl = IndirectMemberDecl->getAnonField(); 9556 } 9557 9558 if (!MemberDecl) 9559 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9560 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9561 OC.LocEnd)); 9562 9563 // C99 7.17p3: 9564 // (If the specified member is a bit-field, the behavior is undefined.) 9565 // 9566 // We diagnose this as an error. 9567 if (MemberDecl->isBitField()) { 9568 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9569 << MemberDecl->getDeclName() 9570 << SourceRange(BuiltinLoc, RParenLoc); 9571 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9572 return ExprError(); 9573 } 9574 9575 RecordDecl *Parent = MemberDecl->getParent(); 9576 if (IndirectMemberDecl) 9577 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9578 9579 // If the member was found in a base class, introduce OffsetOfNodes for 9580 // the base class indirections. 9581 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9582 /*DetectVirtual=*/false); 9583 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9584 CXXBasePath &Path = Paths.front(); 9585 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9586 B != BEnd; ++B) 9587 Comps.push_back(OffsetOfNode(B->Base)); 9588 } 9589 9590 if (IndirectMemberDecl) { 9591 for (IndirectFieldDecl::chain_iterator FI = 9592 IndirectMemberDecl->chain_begin(), 9593 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9594 assert(isa<FieldDecl>(*FI)); 9595 Comps.push_back(OffsetOfNode(OC.LocStart, 9596 cast<FieldDecl>(*FI), OC.LocEnd)); 9597 } 9598 } else 9599 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9600 9601 CurrentType = MemberDecl->getType().getNonReferenceType(); 9602 } 9603 9604 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9605 TInfo, Comps, Exprs, RParenLoc)); 9606 } 9607 9608 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9609 SourceLocation BuiltinLoc, 9610 SourceLocation TypeLoc, 9611 ParsedType ParsedArgTy, 9612 OffsetOfComponent *CompPtr, 9613 unsigned NumComponents, 9614 SourceLocation RParenLoc) { 9615 9616 TypeSourceInfo *ArgTInfo; 9617 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9618 if (ArgTy.isNull()) 9619 return ExprError(); 9620 9621 if (!ArgTInfo) 9622 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9623 9624 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9625 RParenLoc); 9626 } 9627 9628 9629 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9630 Expr *CondExpr, 9631 Expr *LHSExpr, Expr *RHSExpr, 9632 SourceLocation RPLoc) { 9633 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9634 9635 ExprValueKind VK = VK_RValue; 9636 ExprObjectKind OK = OK_Ordinary; 9637 QualType resType; 9638 bool ValueDependent = false; 9639 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9640 resType = Context.DependentTy; 9641 ValueDependent = true; 9642 } else { 9643 // The conditional expression is required to be a constant expression. 9644 llvm::APSInt condEval(32); 9645 ExprResult CondICE 9646 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9647 diag::err_typecheck_choose_expr_requires_constant, false); 9648 if (CondICE.isInvalid()) 9649 return ExprError(); 9650 CondExpr = CondICE.take(); 9651 9652 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9653 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 9654 9655 resType = ActiveExpr->getType(); 9656 ValueDependent = ActiveExpr->isValueDependent(); 9657 VK = ActiveExpr->getValueKind(); 9658 OK = ActiveExpr->getObjectKind(); 9659 } 9660 9661 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9662 resType, VK, OK, RPLoc, 9663 resType->isDependentType(), 9664 ValueDependent)); 9665 } 9666 9667 //===----------------------------------------------------------------------===// 9668 // Clang Extensions. 9669 //===----------------------------------------------------------------------===// 9670 9671 /// ActOnBlockStart - This callback is invoked when a block literal is started. 9672 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 9673 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 9674 PushBlockScope(CurScope, Block); 9675 CurContext->addDecl(Block); 9676 if (CurScope) 9677 PushDeclContext(CurScope, Block); 9678 else 9679 CurContext = Block; 9680 9681 getCurBlock()->HasImplicitReturnType = true; 9682 9683 // Enter a new evaluation context to insulate the block from any 9684 // cleanups from the enclosing full-expression. 9685 PushExpressionEvaluationContext(PotentiallyEvaluated); 9686 } 9687 9688 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 9689 Scope *CurScope) { 9690 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 9691 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 9692 BlockScopeInfo *CurBlock = getCurBlock(); 9693 9694 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 9695 QualType T = Sig->getType(); 9696 9697 // FIXME: We should allow unexpanded parameter packs here, but that would, 9698 // in turn, make the block expression contain unexpanded parameter packs. 9699 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 9700 // Drop the parameters. 9701 FunctionProtoType::ExtProtoInfo EPI; 9702 EPI.HasTrailingReturn = false; 9703 EPI.TypeQuals |= DeclSpec::TQ_const; 9704 T = Context.getFunctionType(Context.DependentTy, ArrayRef<QualType>(), EPI); 9705 Sig = Context.getTrivialTypeSourceInfo(T); 9706 } 9707 9708 // GetTypeForDeclarator always produces a function type for a block 9709 // literal signature. Furthermore, it is always a FunctionProtoType 9710 // unless the function was written with a typedef. 9711 assert(T->isFunctionType() && 9712 "GetTypeForDeclarator made a non-function block signature"); 9713 9714 // Look for an explicit signature in that function type. 9715 FunctionProtoTypeLoc ExplicitSignature; 9716 9717 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 9718 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 9719 9720 // Check whether that explicit signature was synthesized by 9721 // GetTypeForDeclarator. If so, don't save that as part of the 9722 // written signature. 9723 if (ExplicitSignature.getLocalRangeBegin() == 9724 ExplicitSignature.getLocalRangeEnd()) { 9725 // This would be much cheaper if we stored TypeLocs instead of 9726 // TypeSourceInfos. 9727 TypeLoc Result = ExplicitSignature.getResultLoc(); 9728 unsigned Size = Result.getFullDataSize(); 9729 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 9730 Sig->getTypeLoc().initializeFullCopy(Result, Size); 9731 9732 ExplicitSignature = FunctionProtoTypeLoc(); 9733 } 9734 } 9735 9736 CurBlock->TheDecl->setSignatureAsWritten(Sig); 9737 CurBlock->FunctionType = T; 9738 9739 const FunctionType *Fn = T->getAs<FunctionType>(); 9740 QualType RetTy = Fn->getResultType(); 9741 bool isVariadic = 9742 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 9743 9744 CurBlock->TheDecl->setIsVariadic(isVariadic); 9745 9746 // Don't allow returning a objc interface by value. 9747 if (RetTy->isObjCObjectType()) { 9748 Diag(ParamInfo.getLocStart(), 9749 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 9750 return; 9751 } 9752 9753 // Context.DependentTy is used as a placeholder for a missing block 9754 // return type. TODO: what should we do with declarators like: 9755 // ^ * { ... } 9756 // If the answer is "apply template argument deduction".... 9757 if (RetTy != Context.DependentTy) { 9758 CurBlock->ReturnType = RetTy; 9759 CurBlock->TheDecl->setBlockMissingReturnType(false); 9760 CurBlock->HasImplicitReturnType = false; 9761 } 9762 9763 // Push block parameters from the declarator if we had them. 9764 SmallVector<ParmVarDecl*, 8> Params; 9765 if (ExplicitSignature) { 9766 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 9767 ParmVarDecl *Param = ExplicitSignature.getArg(I); 9768 if (Param->getIdentifier() == 0 && 9769 !Param->isImplicit() && 9770 !Param->isInvalidDecl() && 9771 !getLangOpts().CPlusPlus) 9772 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9773 Params.push_back(Param); 9774 } 9775 9776 // Fake up parameter variables if we have a typedef, like 9777 // ^ fntype { ... } 9778 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 9779 for (FunctionProtoType::arg_type_iterator 9780 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 9781 ParmVarDecl *Param = 9782 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 9783 ParamInfo.getLocStart(), 9784 *I); 9785 Params.push_back(Param); 9786 } 9787 } 9788 9789 // Set the parameters on the block decl. 9790 if (!Params.empty()) { 9791 CurBlock->TheDecl->setParams(Params); 9792 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9793 CurBlock->TheDecl->param_end(), 9794 /*CheckParameterNames=*/false); 9795 } 9796 9797 // Finally we can process decl attributes. 9798 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9799 9800 // Put the parameter variables in scope. We can bail out immediately 9801 // if we don't have any. 9802 if (Params.empty()) 9803 return; 9804 9805 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9806 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9807 (*AI)->setOwningFunction(CurBlock->TheDecl); 9808 9809 // If this has an identifier, add it to the scope stack. 9810 if ((*AI)->getIdentifier()) { 9811 CheckShadow(CurBlock->TheScope, *AI); 9812 9813 PushOnScopeChains(*AI, CurBlock->TheScope); 9814 } 9815 } 9816 } 9817 9818 /// ActOnBlockError - If there is an error parsing a block, this callback 9819 /// is invoked to pop the information about the block from the action impl. 9820 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9821 // Leave the expression-evaluation context. 9822 DiscardCleanupsInEvaluationContext(); 9823 PopExpressionEvaluationContext(); 9824 9825 // Pop off CurBlock, handle nested blocks. 9826 PopDeclContext(); 9827 PopFunctionScopeInfo(); 9828 } 9829 9830 /// ActOnBlockStmtExpr - This is called when the body of a block statement 9831 /// literal was successfully completed. ^(int x){...} 9832 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9833 Stmt *Body, Scope *CurScope) { 9834 // If blocks are disabled, emit an error. 9835 if (!LangOpts.Blocks) 9836 Diag(CaretLoc, diag::err_blocks_disable); 9837 9838 // Leave the expression-evaluation context. 9839 if (hasAnyUnrecoverableErrorsInThisFunction()) 9840 DiscardCleanupsInEvaluationContext(); 9841 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9842 PopExpressionEvaluationContext(); 9843 9844 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9845 9846 if (BSI->HasImplicitReturnType) 9847 deduceClosureReturnType(*BSI); 9848 9849 PopDeclContext(); 9850 9851 QualType RetTy = Context.VoidTy; 9852 if (!BSI->ReturnType.isNull()) 9853 RetTy = BSI->ReturnType; 9854 9855 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9856 QualType BlockTy; 9857 9858 // Set the captured variables on the block. 9859 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 9860 SmallVector<BlockDecl::Capture, 4> Captures; 9861 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 9862 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 9863 if (Cap.isThisCapture()) 9864 continue; 9865 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 9866 Cap.isNested(), Cap.getCopyExpr()); 9867 Captures.push_back(NewCap); 9868 } 9869 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 9870 BSI->CXXThisCaptureIndex != 0); 9871 9872 // If the user wrote a function type in some form, try to use that. 9873 if (!BSI->FunctionType.isNull()) { 9874 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 9875 9876 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 9877 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 9878 9879 // Turn protoless block types into nullary block types. 9880 if (isa<FunctionNoProtoType>(FTy)) { 9881 FunctionProtoType::ExtProtoInfo EPI; 9882 EPI.ExtInfo = Ext; 9883 BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI); 9884 9885 // Otherwise, if we don't need to change anything about the function type, 9886 // preserve its sugar structure. 9887 } else if (FTy->getResultType() == RetTy && 9888 (!NoReturn || FTy->getNoReturnAttr())) { 9889 BlockTy = BSI->FunctionType; 9890 9891 // Otherwise, make the minimal modifications to the function type. 9892 } else { 9893 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 9894 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9895 EPI.TypeQuals = 0; // FIXME: silently? 9896 EPI.ExtInfo = Ext; 9897 BlockTy = 9898 Context.getFunctionType(RetTy, 9899 ArrayRef<QualType>(FPT->arg_type_begin(), 9900 FPT->getNumArgs()), 9901 EPI); 9902 } 9903 9904 // If we don't have a function type, just build one from nothing. 9905 } else { 9906 FunctionProtoType::ExtProtoInfo EPI; 9907 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 9908 BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI); 9909 } 9910 9911 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9912 BSI->TheDecl->param_end()); 9913 BlockTy = Context.getBlockPointerType(BlockTy); 9914 9915 // If needed, diagnose invalid gotos and switches in the block. 9916 if (getCurFunction()->NeedsScopeChecking() && 9917 !hasAnyUnrecoverableErrorsInThisFunction() && 9918 !PP.isCodeCompletionEnabled()) 9919 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9920 9921 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9922 9923 // Try to apply the named return value optimization. We have to check again 9924 // if we can do this, though, because blocks keep return statements around 9925 // to deduce an implicit return type. 9926 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 9927 !BSI->TheDecl->isDependentContext()) 9928 computeNRVO(Body, getCurBlock()); 9929 9930 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 9931 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 9932 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 9933 9934 // If the block isn't obviously global, i.e. it captures anything at 9935 // all, then we need to do a few things in the surrounding context: 9936 if (Result->getBlockDecl()->hasCaptures()) { 9937 // First, this expression has a new cleanup object. 9938 ExprCleanupObjects.push_back(Result->getBlockDecl()); 9939 ExprNeedsCleanups = true; 9940 9941 // It also gets a branch-protected scope if any of the captured 9942 // variables needs destruction. 9943 for (BlockDecl::capture_const_iterator 9944 ci = Result->getBlockDecl()->capture_begin(), 9945 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 9946 const VarDecl *var = ci->getVariable(); 9947 if (var->getType().isDestructedType() != QualType::DK_none) { 9948 getCurFunction()->setHasBranchProtectedScope(); 9949 break; 9950 } 9951 } 9952 } 9953 9954 return Owned(Result); 9955 } 9956 9957 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 9958 Expr *E, ParsedType Ty, 9959 SourceLocation RPLoc) { 9960 TypeSourceInfo *TInfo; 9961 GetTypeFromParser(Ty, &TInfo); 9962 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 9963 } 9964 9965 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 9966 Expr *E, TypeSourceInfo *TInfo, 9967 SourceLocation RPLoc) { 9968 Expr *OrigExpr = E; 9969 9970 // Get the va_list type 9971 QualType VaListType = Context.getBuiltinVaListType(); 9972 if (VaListType->isArrayType()) { 9973 // Deal with implicit array decay; for example, on x86-64, 9974 // va_list is an array, but it's supposed to decay to 9975 // a pointer for va_arg. 9976 VaListType = Context.getArrayDecayedType(VaListType); 9977 // Make sure the input expression also decays appropriately. 9978 ExprResult Result = UsualUnaryConversions(E); 9979 if (Result.isInvalid()) 9980 return ExprError(); 9981 E = Result.take(); 9982 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 9983 // If va_list is a record type and we are compiling in C++ mode, 9984 // check the argument using reference binding. 9985 InitializedEntity Entity 9986 = InitializedEntity::InitializeParameter(Context, 9987 Context.getLValueReferenceType(VaListType), false); 9988 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 9989 if (Init.isInvalid()) 9990 return ExprError(); 9991 E = Init.takeAs<Expr>(); 9992 } else { 9993 // Otherwise, the va_list argument must be an l-value because 9994 // it is modified by va_arg. 9995 if (!E->isTypeDependent() && 9996 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 9997 return ExprError(); 9998 } 9999 10000 if (!E->isTypeDependent() && 10001 !Context.hasSameType(VaListType, E->getType())) { 10002 return ExprError(Diag(E->getLocStart(), 10003 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10004 << OrigExpr->getType() << E->getSourceRange()); 10005 } 10006 10007 if (!TInfo->getType()->isDependentType()) { 10008 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10009 diag::err_second_parameter_to_va_arg_incomplete, 10010 TInfo->getTypeLoc())) 10011 return ExprError(); 10012 10013 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10014 TInfo->getType(), 10015 diag::err_second_parameter_to_va_arg_abstract, 10016 TInfo->getTypeLoc())) 10017 return ExprError(); 10018 10019 if (!TInfo->getType().isPODType(Context)) { 10020 Diag(TInfo->getTypeLoc().getBeginLoc(), 10021 TInfo->getType()->isObjCLifetimeType() 10022 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10023 : diag::warn_second_parameter_to_va_arg_not_pod) 10024 << TInfo->getType() 10025 << TInfo->getTypeLoc().getSourceRange(); 10026 } 10027 10028 // Check for va_arg where arguments of the given type will be promoted 10029 // (i.e. this va_arg is guaranteed to have undefined behavior). 10030 QualType PromoteType; 10031 if (TInfo->getType()->isPromotableIntegerType()) { 10032 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10033 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10034 PromoteType = QualType(); 10035 } 10036 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10037 PromoteType = Context.DoubleTy; 10038 if (!PromoteType.isNull()) 10039 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10040 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10041 << TInfo->getType() 10042 << PromoteType 10043 << TInfo->getTypeLoc().getSourceRange()); 10044 } 10045 10046 QualType T = TInfo->getType().getNonLValueExprType(Context); 10047 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10048 } 10049 10050 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10051 // The type of __null will be int or long, depending on the size of 10052 // pointers on the target. 10053 QualType Ty; 10054 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10055 if (pw == Context.getTargetInfo().getIntWidth()) 10056 Ty = Context.IntTy; 10057 else if (pw == Context.getTargetInfo().getLongWidth()) 10058 Ty = Context.LongTy; 10059 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10060 Ty = Context.LongLongTy; 10061 else { 10062 llvm_unreachable("I don't know size of pointer!"); 10063 } 10064 10065 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10066 } 10067 10068 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10069 Expr *SrcExpr, FixItHint &Hint) { 10070 if (!SemaRef.getLangOpts().ObjC1) 10071 return; 10072 10073 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10074 if (!PT) 10075 return; 10076 10077 // Check if the destination is of type 'id'. 10078 if (!PT->isObjCIdType()) { 10079 // Check if the destination is the 'NSString' interface. 10080 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10081 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10082 return; 10083 } 10084 10085 // Ignore any parens, implicit casts (should only be 10086 // array-to-pointer decays), and not-so-opaque values. The last is 10087 // important for making this trigger for property assignments. 10088 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10089 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10090 if (OV->getSourceExpr()) 10091 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10092 10093 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10094 if (!SL || !SL->isAscii()) 10095 return; 10096 10097 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10098 } 10099 10100 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10101 SourceLocation Loc, 10102 QualType DstType, QualType SrcType, 10103 Expr *SrcExpr, AssignmentAction Action, 10104 bool *Complained) { 10105 if (Complained) 10106 *Complained = false; 10107 10108 // Decode the result (notice that AST's are still created for extensions). 10109 bool CheckInferredResultType = false; 10110 bool isInvalid = false; 10111 unsigned DiagKind = 0; 10112 FixItHint Hint; 10113 ConversionFixItGenerator ConvHints; 10114 bool MayHaveConvFixit = false; 10115 bool MayHaveFunctionDiff = false; 10116 10117 switch (ConvTy) { 10118 case Compatible: 10119 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10120 return false; 10121 10122 case PointerToInt: 10123 DiagKind = diag::ext_typecheck_convert_pointer_int; 10124 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10125 MayHaveConvFixit = true; 10126 break; 10127 case IntToPointer: 10128 DiagKind = diag::ext_typecheck_convert_int_pointer; 10129 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10130 MayHaveConvFixit = true; 10131 break; 10132 case IncompatiblePointer: 10133 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 10134 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 10135 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10136 SrcType->isObjCObjectPointerType(); 10137 if (Hint.isNull() && !CheckInferredResultType) { 10138 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10139 } 10140 MayHaveConvFixit = true; 10141 break; 10142 case IncompatiblePointerSign: 10143 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10144 break; 10145 case FunctionVoidPointer: 10146 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10147 break; 10148 case IncompatiblePointerDiscardsQualifiers: { 10149 // Perform array-to-pointer decay if necessary. 10150 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10151 10152 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10153 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10154 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10155 DiagKind = diag::err_typecheck_incompatible_address_space; 10156 break; 10157 10158 10159 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10160 DiagKind = diag::err_typecheck_incompatible_ownership; 10161 break; 10162 } 10163 10164 llvm_unreachable("unknown error case for discarding qualifiers!"); 10165 // fallthrough 10166 } 10167 case CompatiblePointerDiscardsQualifiers: 10168 // If the qualifiers lost were because we were applying the 10169 // (deprecated) C++ conversion from a string literal to a char* 10170 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10171 // Ideally, this check would be performed in 10172 // checkPointerTypesForAssignment. However, that would require a 10173 // bit of refactoring (so that the second argument is an 10174 // expression, rather than a type), which should be done as part 10175 // of a larger effort to fix checkPointerTypesForAssignment for 10176 // C++ semantics. 10177 if (getLangOpts().CPlusPlus && 10178 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10179 return false; 10180 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10181 break; 10182 case IncompatibleNestedPointerQualifiers: 10183 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10184 break; 10185 case IntToBlockPointer: 10186 DiagKind = diag::err_int_to_block_pointer; 10187 break; 10188 case IncompatibleBlockPointer: 10189 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10190 break; 10191 case IncompatibleObjCQualifiedId: 10192 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10193 // it can give a more specific diagnostic. 10194 DiagKind = diag::warn_incompatible_qualified_id; 10195 break; 10196 case IncompatibleVectors: 10197 DiagKind = diag::warn_incompatible_vectors; 10198 break; 10199 case IncompatibleObjCWeakRef: 10200 DiagKind = diag::err_arc_weak_unavailable_assign; 10201 break; 10202 case Incompatible: 10203 DiagKind = diag::err_typecheck_convert_incompatible; 10204 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10205 MayHaveConvFixit = true; 10206 isInvalid = true; 10207 MayHaveFunctionDiff = true; 10208 break; 10209 } 10210 10211 QualType FirstType, SecondType; 10212 switch (Action) { 10213 case AA_Assigning: 10214 case AA_Initializing: 10215 // The destination type comes first. 10216 FirstType = DstType; 10217 SecondType = SrcType; 10218 break; 10219 10220 case AA_Returning: 10221 case AA_Passing: 10222 case AA_Converting: 10223 case AA_Sending: 10224 case AA_Casting: 10225 // The source type comes first. 10226 FirstType = SrcType; 10227 SecondType = DstType; 10228 break; 10229 } 10230 10231 PartialDiagnostic FDiag = PDiag(DiagKind); 10232 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10233 10234 // If we can fix the conversion, suggest the FixIts. 10235 assert(ConvHints.isNull() || Hint.isNull()); 10236 if (!ConvHints.isNull()) { 10237 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10238 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10239 FDiag << *HI; 10240 } else { 10241 FDiag << Hint; 10242 } 10243 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10244 10245 if (MayHaveFunctionDiff) 10246 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10247 10248 Diag(Loc, FDiag); 10249 10250 if (SecondType == Context.OverloadTy) 10251 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10252 FirstType); 10253 10254 if (CheckInferredResultType) 10255 EmitRelatedResultTypeNote(SrcExpr); 10256 10257 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10258 EmitRelatedResultTypeNoteForReturn(DstType); 10259 10260 if (Complained) 10261 *Complained = true; 10262 return isInvalid; 10263 } 10264 10265 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10266 llvm::APSInt *Result) { 10267 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10268 public: 10269 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10270 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10271 } 10272 } Diagnoser; 10273 10274 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10275 } 10276 10277 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10278 llvm::APSInt *Result, 10279 unsigned DiagID, 10280 bool AllowFold) { 10281 class IDDiagnoser : public VerifyICEDiagnoser { 10282 unsigned DiagID; 10283 10284 public: 10285 IDDiagnoser(unsigned DiagID) 10286 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10287 10288 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10289 S.Diag(Loc, DiagID) << SR; 10290 } 10291 } Diagnoser(DiagID); 10292 10293 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10294 } 10295 10296 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10297 SourceRange SR) { 10298 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10299 } 10300 10301 ExprResult 10302 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10303 VerifyICEDiagnoser &Diagnoser, 10304 bool AllowFold) { 10305 SourceLocation DiagLoc = E->getLocStart(); 10306 10307 if (getLangOpts().CPlusPlus11) { 10308 // C++11 [expr.const]p5: 10309 // If an expression of literal class type is used in a context where an 10310 // integral constant expression is required, then that class type shall 10311 // have a single non-explicit conversion function to an integral or 10312 // unscoped enumeration type 10313 ExprResult Converted; 10314 if (!Diagnoser.Suppress) { 10315 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10316 public: 10317 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { } 10318 10319 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10320 QualType T) { 10321 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10322 } 10323 10324 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10325 SourceLocation Loc, 10326 QualType T) { 10327 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10328 } 10329 10330 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10331 SourceLocation Loc, 10332 QualType T, 10333 QualType ConvTy) { 10334 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10335 } 10336 10337 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10338 CXXConversionDecl *Conv, 10339 QualType ConvTy) { 10340 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10341 << ConvTy->isEnumeralType() << ConvTy; 10342 } 10343 10344 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10345 QualType T) { 10346 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10347 } 10348 10349 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10350 CXXConversionDecl *Conv, 10351 QualType ConvTy) { 10352 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10353 << ConvTy->isEnumeralType() << ConvTy; 10354 } 10355 10356 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10357 SourceLocation Loc, 10358 QualType T, 10359 QualType ConvTy) { 10360 return DiagnosticBuilder::getEmpty(); 10361 } 10362 } ConvertDiagnoser; 10363 10364 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10365 ConvertDiagnoser, 10366 /*AllowScopedEnumerations*/ false); 10367 } else { 10368 // The caller wants to silently enquire whether this is an ICE. Don't 10369 // produce any diagnostics if it isn't. 10370 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser { 10371 public: 10372 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { } 10373 10374 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10375 QualType T) { 10376 return DiagnosticBuilder::getEmpty(); 10377 } 10378 10379 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10380 SourceLocation Loc, 10381 QualType T) { 10382 return DiagnosticBuilder::getEmpty(); 10383 } 10384 10385 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10386 SourceLocation Loc, 10387 QualType T, 10388 QualType ConvTy) { 10389 return DiagnosticBuilder::getEmpty(); 10390 } 10391 10392 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10393 CXXConversionDecl *Conv, 10394 QualType ConvTy) { 10395 return DiagnosticBuilder::getEmpty(); 10396 } 10397 10398 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10399 QualType T) { 10400 return DiagnosticBuilder::getEmpty(); 10401 } 10402 10403 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10404 CXXConversionDecl *Conv, 10405 QualType ConvTy) { 10406 return DiagnosticBuilder::getEmpty(); 10407 } 10408 10409 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10410 SourceLocation Loc, 10411 QualType T, 10412 QualType ConvTy) { 10413 return DiagnosticBuilder::getEmpty(); 10414 } 10415 } ConvertDiagnoser; 10416 10417 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10418 ConvertDiagnoser, false); 10419 } 10420 if (Converted.isInvalid()) 10421 return Converted; 10422 E = Converted.take(); 10423 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10424 return ExprError(); 10425 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10426 // An ICE must be of integral or unscoped enumeration type. 10427 if (!Diagnoser.Suppress) 10428 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10429 return ExprError(); 10430 } 10431 10432 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10433 // in the non-ICE case. 10434 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10435 if (Result) 10436 *Result = E->EvaluateKnownConstInt(Context); 10437 return Owned(E); 10438 } 10439 10440 Expr::EvalResult EvalResult; 10441 SmallVector<PartialDiagnosticAt, 8> Notes; 10442 EvalResult.Diag = &Notes; 10443 10444 // Try to evaluate the expression, and produce diagnostics explaining why it's 10445 // not a constant expression as a side-effect. 10446 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10447 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10448 10449 // In C++11, we can rely on diagnostics being produced for any expression 10450 // which is not a constant expression. If no diagnostics were produced, then 10451 // this is a constant expression. 10452 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10453 if (Result) 10454 *Result = EvalResult.Val.getInt(); 10455 return Owned(E); 10456 } 10457 10458 // If our only note is the usual "invalid subexpression" note, just point 10459 // the caret at its location rather than producing an essentially 10460 // redundant note. 10461 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10462 diag::note_invalid_subexpr_in_const_expr) { 10463 DiagLoc = Notes[0].first; 10464 Notes.clear(); 10465 } 10466 10467 if (!Folded || !AllowFold) { 10468 if (!Diagnoser.Suppress) { 10469 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10470 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10471 Diag(Notes[I].first, Notes[I].second); 10472 } 10473 10474 return ExprError(); 10475 } 10476 10477 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10478 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10479 Diag(Notes[I].first, Notes[I].second); 10480 10481 if (Result) 10482 *Result = EvalResult.Val.getInt(); 10483 return Owned(E); 10484 } 10485 10486 namespace { 10487 // Handle the case where we conclude a expression which we speculatively 10488 // considered to be unevaluated is actually evaluated. 10489 class TransformToPE : public TreeTransform<TransformToPE> { 10490 typedef TreeTransform<TransformToPE> BaseTransform; 10491 10492 public: 10493 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10494 10495 // Make sure we redo semantic analysis 10496 bool AlwaysRebuild() { return true; } 10497 10498 // Make sure we handle LabelStmts correctly. 10499 // FIXME: This does the right thing, but maybe we need a more general 10500 // fix to TreeTransform? 10501 StmtResult TransformLabelStmt(LabelStmt *S) { 10502 S->getDecl()->setStmt(0); 10503 return BaseTransform::TransformLabelStmt(S); 10504 } 10505 10506 // We need to special-case DeclRefExprs referring to FieldDecls which 10507 // are not part of a member pointer formation; normal TreeTransforming 10508 // doesn't catch this case because of the way we represent them in the AST. 10509 // FIXME: This is a bit ugly; is it really the best way to handle this 10510 // case? 10511 // 10512 // Error on DeclRefExprs referring to FieldDecls. 10513 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10514 if (isa<FieldDecl>(E->getDecl()) && 10515 !SemaRef.isUnevaluatedContext()) 10516 return SemaRef.Diag(E->getLocation(), 10517 diag::err_invalid_non_static_member_use) 10518 << E->getDecl() << E->getSourceRange(); 10519 10520 return BaseTransform::TransformDeclRefExpr(E); 10521 } 10522 10523 // Exception: filter out member pointer formation 10524 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10525 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10526 return E; 10527 10528 return BaseTransform::TransformUnaryOperator(E); 10529 } 10530 10531 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10532 // Lambdas never need to be transformed. 10533 return E; 10534 } 10535 }; 10536 } 10537 10538 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10539 assert(ExprEvalContexts.back().Context == Unevaluated && 10540 "Should only transform unevaluated expressions"); 10541 ExprEvalContexts.back().Context = 10542 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10543 if (ExprEvalContexts.back().Context == Unevaluated) 10544 return E; 10545 return TransformToPE(*this).TransformExpr(E); 10546 } 10547 10548 void 10549 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10550 Decl *LambdaContextDecl, 10551 bool IsDecltype) { 10552 ExprEvalContexts.push_back( 10553 ExpressionEvaluationContextRecord(NewContext, 10554 ExprCleanupObjects.size(), 10555 ExprNeedsCleanups, 10556 LambdaContextDecl, 10557 IsDecltype)); 10558 ExprNeedsCleanups = false; 10559 if (!MaybeODRUseExprs.empty()) 10560 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10561 } 10562 10563 void 10564 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10565 ReuseLambdaContextDecl_t, 10566 bool IsDecltype) { 10567 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl; 10568 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype); 10569 } 10570 10571 void Sema::PopExpressionEvaluationContext() { 10572 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10573 10574 if (!Rec.Lambdas.empty()) { 10575 if (Rec.Context == Unevaluated) { 10576 // C++11 [expr.prim.lambda]p2: 10577 // A lambda-expression shall not appear in an unevaluated operand 10578 // (Clause 5). 10579 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10580 Diag(Rec.Lambdas[I]->getLocStart(), 10581 diag::err_lambda_unevaluated_operand); 10582 } else { 10583 // Mark the capture expressions odr-used. This was deferred 10584 // during lambda expression creation. 10585 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10586 LambdaExpr *Lambda = Rec.Lambdas[I]; 10587 for (LambdaExpr::capture_init_iterator 10588 C = Lambda->capture_init_begin(), 10589 CEnd = Lambda->capture_init_end(); 10590 C != CEnd; ++C) { 10591 MarkDeclarationsReferencedInExpr(*C); 10592 } 10593 } 10594 } 10595 } 10596 10597 // When are coming out of an unevaluated context, clear out any 10598 // temporaries that we may have created as part of the evaluation of 10599 // the expression in that context: they aren't relevant because they 10600 // will never be constructed. 10601 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) { 10602 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10603 ExprCleanupObjects.end()); 10604 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10605 CleanupVarDeclMarking(); 10606 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10607 // Otherwise, merge the contexts together. 10608 } else { 10609 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10610 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10611 Rec.SavedMaybeODRUseExprs.end()); 10612 } 10613 10614 // Pop the current expression evaluation context off the stack. 10615 ExprEvalContexts.pop_back(); 10616 } 10617 10618 void Sema::DiscardCleanupsInEvaluationContext() { 10619 ExprCleanupObjects.erase( 10620 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10621 ExprCleanupObjects.end()); 10622 ExprNeedsCleanups = false; 10623 MaybeODRUseExprs.clear(); 10624 } 10625 10626 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10627 if (!E->getType()->isVariablyModifiedType()) 10628 return E; 10629 return TransformToPotentiallyEvaluated(E); 10630 } 10631 10632 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10633 // Do not mark anything as "used" within a dependent context; wait for 10634 // an instantiation. 10635 if (SemaRef.CurContext->isDependentContext()) 10636 return false; 10637 10638 switch (SemaRef.ExprEvalContexts.back().Context) { 10639 case Sema::Unevaluated: 10640 // We are in an expression that is not potentially evaluated; do nothing. 10641 // (Depending on how you read the standard, we actually do need to do 10642 // something here for null pointer constants, but the standard's 10643 // definition of a null pointer constant is completely crazy.) 10644 return false; 10645 10646 case Sema::ConstantEvaluated: 10647 case Sema::PotentiallyEvaluated: 10648 // We are in a potentially evaluated expression (or a constant-expression 10649 // in C++03); we need to do implicit template instantiation, implicitly 10650 // define class members, and mark most declarations as used. 10651 return true; 10652 10653 case Sema::PotentiallyEvaluatedIfUsed: 10654 // Referenced declarations will only be used if the construct in the 10655 // containing expression is used. 10656 return false; 10657 } 10658 llvm_unreachable("Invalid context"); 10659 } 10660 10661 /// \brief Mark a function referenced, and check whether it is odr-used 10662 /// (C++ [basic.def.odr]p2, C99 6.9p3) 10663 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10664 assert(Func && "No function?"); 10665 10666 Func->setReferenced(); 10667 10668 // C++11 [basic.def.odr]p3: 10669 // A function whose name appears as a potentially-evaluated expression is 10670 // odr-used if it is the unique lookup result or the selected member of a 10671 // set of overloaded functions [...]. 10672 // 10673 // We (incorrectly) mark overload resolution as an unevaluated context, so we 10674 // can just check that here. Skip the rest of this function if we've already 10675 // marked the function as used. 10676 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 10677 // C++11 [temp.inst]p3: 10678 // Unless a function template specialization has been explicitly 10679 // instantiated or explicitly specialized, the function template 10680 // specialization is implicitly instantiated when the specialization is 10681 // referenced in a context that requires a function definition to exist. 10682 // 10683 // We consider constexpr function templates to be referenced in a context 10684 // that requires a definition to exist whenever they are referenced. 10685 // 10686 // FIXME: This instantiates constexpr functions too frequently. If this is 10687 // really an unevaluated context (and we're not just in the definition of a 10688 // function template or overload resolution or other cases which we 10689 // incorrectly consider to be unevaluated contexts), and we're not in a 10690 // subexpression which we actually need to evaluate (for instance, a 10691 // template argument, array bound or an expression in a braced-init-list), 10692 // we are not permitted to instantiate this constexpr function definition. 10693 // 10694 // FIXME: This also implicitly defines special members too frequently. They 10695 // are only supposed to be implicitly defined if they are odr-used, but they 10696 // are not odr-used from constant expressions in unevaluated contexts. 10697 // However, they cannot be referenced if they are deleted, and they are 10698 // deleted whenever the implicit definition of the special member would 10699 // fail. 10700 if (!Func->isConstexpr() || Func->getBody()) 10701 return; 10702 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 10703 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 10704 return; 10705 } 10706 10707 // Note that this declaration has been used. 10708 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10709 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10710 if (Constructor->isDefaultConstructor()) { 10711 if (Constructor->isTrivial()) 10712 return; 10713 if (!Constructor->isUsed(false)) 10714 DefineImplicitDefaultConstructor(Loc, Constructor); 10715 } else if (Constructor->isCopyConstructor()) { 10716 if (!Constructor->isUsed(false)) 10717 DefineImplicitCopyConstructor(Loc, Constructor); 10718 } else if (Constructor->isMoveConstructor()) { 10719 if (!Constructor->isUsed(false)) 10720 DefineImplicitMoveConstructor(Loc, Constructor); 10721 } 10722 } else if (Constructor->getInheritedConstructor()) { 10723 if (!Constructor->isUsed(false)) 10724 DefineInheritingConstructor(Loc, Constructor); 10725 } 10726 10727 MarkVTableUsed(Loc, Constructor->getParent()); 10728 } else if (CXXDestructorDecl *Destructor = 10729 dyn_cast<CXXDestructorDecl>(Func)) { 10730 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 10731 !Destructor->isUsed(false)) 10732 DefineImplicitDestructor(Loc, Destructor); 10733 if (Destructor->isVirtual()) 10734 MarkVTableUsed(Loc, Destructor->getParent()); 10735 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 10736 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 10737 MethodDecl->isOverloadedOperator() && 10738 MethodDecl->getOverloadedOperator() == OO_Equal) { 10739 if (!MethodDecl->isUsed(false)) { 10740 if (MethodDecl->isCopyAssignmentOperator()) 10741 DefineImplicitCopyAssignment(Loc, MethodDecl); 10742 else 10743 DefineImplicitMoveAssignment(Loc, MethodDecl); 10744 } 10745 } else if (isa<CXXConversionDecl>(MethodDecl) && 10746 MethodDecl->getParent()->isLambda()) { 10747 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 10748 if (Conversion->isLambdaToBlockPointerConversion()) 10749 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 10750 else 10751 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 10752 } else if (MethodDecl->isVirtual()) 10753 MarkVTableUsed(Loc, MethodDecl->getParent()); 10754 } 10755 10756 // Recursive functions should be marked when used from another function. 10757 // FIXME: Is this really right? 10758 if (CurContext == Func) return; 10759 10760 // Resolve the exception specification for any function which is 10761 // used: CodeGen will need it. 10762 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 10763 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 10764 ResolveExceptionSpec(Loc, FPT); 10765 10766 // Implicit instantiation of function templates and member functions of 10767 // class templates. 10768 if (Func->isImplicitlyInstantiable()) { 10769 bool AlreadyInstantiated = false; 10770 SourceLocation PointOfInstantiation = Loc; 10771 if (FunctionTemplateSpecializationInfo *SpecInfo 10772 = Func->getTemplateSpecializationInfo()) { 10773 if (SpecInfo->getPointOfInstantiation().isInvalid()) 10774 SpecInfo->setPointOfInstantiation(Loc); 10775 else if (SpecInfo->getTemplateSpecializationKind() 10776 == TSK_ImplicitInstantiation) { 10777 AlreadyInstantiated = true; 10778 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 10779 } 10780 } else if (MemberSpecializationInfo *MSInfo 10781 = Func->getMemberSpecializationInfo()) { 10782 if (MSInfo->getPointOfInstantiation().isInvalid()) 10783 MSInfo->setPointOfInstantiation(Loc); 10784 else if (MSInfo->getTemplateSpecializationKind() 10785 == TSK_ImplicitInstantiation) { 10786 AlreadyInstantiated = true; 10787 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10788 } 10789 } 10790 10791 if (!AlreadyInstantiated || Func->isConstexpr()) { 10792 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 10793 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 10794 PendingLocalImplicitInstantiations.push_back( 10795 std::make_pair(Func, PointOfInstantiation)); 10796 else if (Func->isConstexpr()) 10797 // Do not defer instantiations of constexpr functions, to avoid the 10798 // expression evaluator needing to call back into Sema if it sees a 10799 // call to such a function. 10800 InstantiateFunctionDefinition(PointOfInstantiation, Func); 10801 else { 10802 PendingInstantiations.push_back(std::make_pair(Func, 10803 PointOfInstantiation)); 10804 // Notify the consumer that a function was implicitly instantiated. 10805 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 10806 } 10807 } 10808 } else { 10809 // Walk redefinitions, as some of them may be instantiable. 10810 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 10811 e(Func->redecls_end()); i != e; ++i) { 10812 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 10813 MarkFunctionReferenced(Loc, *i); 10814 } 10815 } 10816 10817 // Keep track of used but undefined functions. 10818 if (!Func->isDefined()) { 10819 if (mightHaveNonExternalLinkage(Func)) 10820 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10821 else if (Func->getMostRecentDecl()->isInlined() && 10822 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10823 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 10824 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10825 } 10826 10827 // Normally the must current decl is marked used while processing the use and 10828 // any subsequent decls are marked used by decl merging. This fails with 10829 // template instantiation since marking can happen at the end of the file 10830 // and, because of the two phase lookup, this function is called with at 10831 // decl in the middle of a decl chain. We loop to maintain the invariant 10832 // that once a decl is used, all decls after it are also used. 10833 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 10834 F->setUsed(true); 10835 if (F == Func) 10836 break; 10837 } 10838 } 10839 10840 static void 10841 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 10842 VarDecl *var, DeclContext *DC) { 10843 DeclContext *VarDC = var->getDeclContext(); 10844 10845 // If the parameter still belongs to the translation unit, then 10846 // we're actually just using one parameter in the declaration of 10847 // the next. 10848 if (isa<ParmVarDecl>(var) && 10849 isa<TranslationUnitDecl>(VarDC)) 10850 return; 10851 10852 // For C code, don't diagnose about capture if we're not actually in code 10853 // right now; it's impossible to write a non-constant expression outside of 10854 // function context, so we'll get other (more useful) diagnostics later. 10855 // 10856 // For C++, things get a bit more nasty... it would be nice to suppress this 10857 // diagnostic for certain cases like using a local variable in an array bound 10858 // for a member of a local class, but the correct predicate is not obvious. 10859 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 10860 return; 10861 10862 if (isa<CXXMethodDecl>(VarDC) && 10863 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10864 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10865 << var->getIdentifier(); 10866 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10867 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10868 << var->getIdentifier() << fn->getDeclName(); 10869 } else if (isa<BlockDecl>(VarDC)) { 10870 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10871 << var->getIdentifier(); 10872 } else { 10873 // FIXME: Is there any other context where a local variable can be 10874 // declared? 10875 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10876 << var->getIdentifier(); 10877 } 10878 10879 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10880 << var->getIdentifier(); 10881 10882 // FIXME: Add additional diagnostic info about class etc. which prevents 10883 // capture. 10884 } 10885 10886 /// \brief Capture the given variable in the captured region. 10887 static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI, 10888 VarDecl *Var, QualType FieldType, 10889 QualType DeclRefType, 10890 SourceLocation Loc, 10891 bool RefersToEnclosingLocal) { 10892 // The current implemention assumes that all variables are captured 10893 // by references. Since there is no capture by copy, no expression evaluation 10894 // will be needed. 10895 // 10896 RecordDecl *RD = RSI->TheRecordDecl; 10897 10898 FieldDecl *Field 10899 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType, 10900 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10901 0, false, ICIS_NoInit); 10902 Field->setImplicit(true); 10903 Field->setAccess(AS_private); 10904 RD->addDecl(Field); 10905 10906 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10907 DeclRefType, VK_LValue, Loc); 10908 Var->setReferenced(true); 10909 Var->setUsed(true); 10910 10911 return Ref; 10912 } 10913 10914 /// \brief Capture the given variable in the given lambda expression. 10915 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 10916 VarDecl *Var, QualType FieldType, 10917 QualType DeclRefType, 10918 SourceLocation Loc, 10919 bool RefersToEnclosingLocal) { 10920 CXXRecordDecl *Lambda = LSI->Lambda; 10921 10922 // Build the non-static data member. 10923 FieldDecl *Field 10924 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 10925 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10926 0, false, ICIS_NoInit); 10927 Field->setImplicit(true); 10928 Field->setAccess(AS_private); 10929 Lambda->addDecl(Field); 10930 10931 // C++11 [expr.prim.lambda]p21: 10932 // When the lambda-expression is evaluated, the entities that 10933 // are captured by copy are used to direct-initialize each 10934 // corresponding non-static data member of the resulting closure 10935 // object. (For array members, the array elements are 10936 // direct-initialized in increasing subscript order.) These 10937 // initializations are performed in the (unspecified) order in 10938 // which the non-static data members are declared. 10939 10940 // Introduce a new evaluation context for the initialization, so 10941 // that temporaries introduced as part of the capture are retained 10942 // to be re-"exported" from the lambda expression itself. 10943 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 10944 10945 // C++ [expr.prim.labda]p12: 10946 // An entity captured by a lambda-expression is odr-used (3.2) in 10947 // the scope containing the lambda-expression. 10948 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10949 DeclRefType, VK_LValue, Loc); 10950 Var->setReferenced(true); 10951 Var->setUsed(true); 10952 10953 // When the field has array type, create index variables for each 10954 // dimension of the array. We use these index variables to subscript 10955 // the source array, and other clients (e.g., CodeGen) will perform 10956 // the necessary iteration with these index variables. 10957 SmallVector<VarDecl *, 4> IndexVariables; 10958 QualType BaseType = FieldType; 10959 QualType SizeType = S.Context.getSizeType(); 10960 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 10961 while (const ConstantArrayType *Array 10962 = S.Context.getAsConstantArrayType(BaseType)) { 10963 // Create the iteration variable for this array index. 10964 IdentifierInfo *IterationVarName = 0; 10965 { 10966 SmallString<8> Str; 10967 llvm::raw_svector_ostream OS(Str); 10968 OS << "__i" << IndexVariables.size(); 10969 IterationVarName = &S.Context.Idents.get(OS.str()); 10970 } 10971 VarDecl *IterationVar 10972 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10973 IterationVarName, SizeType, 10974 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10975 SC_None); 10976 IndexVariables.push_back(IterationVar); 10977 LSI->ArrayIndexVars.push_back(IterationVar); 10978 10979 // Create a reference to the iteration variable. 10980 ExprResult IterationVarRef 10981 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 10982 assert(!IterationVarRef.isInvalid() && 10983 "Reference to invented variable cannot fail!"); 10984 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 10985 assert(!IterationVarRef.isInvalid() && 10986 "Conversion of invented variable cannot fail!"); 10987 10988 // Subscript the array with this iteration variable. 10989 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 10990 Ref, Loc, IterationVarRef.take(), Loc); 10991 if (Subscript.isInvalid()) { 10992 S.CleanupVarDeclMarking(); 10993 S.DiscardCleanupsInEvaluationContext(); 10994 return ExprError(); 10995 } 10996 10997 Ref = Subscript.take(); 10998 BaseType = Array->getElementType(); 10999 } 11000 11001 // Construct the entity that we will be initializing. For an array, this 11002 // will be first element in the array, which may require several levels 11003 // of array-subscript entities. 11004 SmallVector<InitializedEntity, 4> Entities; 11005 Entities.reserve(1 + IndexVariables.size()); 11006 Entities.push_back( 11007 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 11008 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11009 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11010 0, 11011 Entities.back())); 11012 11013 InitializationKind InitKind 11014 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11015 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1); 11016 ExprResult Result(true); 11017 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1)) 11018 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11019 11020 // If this initialization requires any cleanups (e.g., due to a 11021 // default argument to a copy constructor), note that for the 11022 // lambda. 11023 if (S.ExprNeedsCleanups) 11024 LSI->ExprNeedsCleanups = true; 11025 11026 // Exit the expression evaluation context used for the capture. 11027 S.CleanupVarDeclMarking(); 11028 S.DiscardCleanupsInEvaluationContext(); 11029 return Result; 11030 } 11031 11032 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11033 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11034 bool BuildAndDiagnose, 11035 QualType &CaptureType, 11036 QualType &DeclRefType) { 11037 bool Nested = false; 11038 11039 DeclContext *DC = CurContext; 11040 if (Var->getDeclContext() == DC) return true; 11041 if (!Var->hasLocalStorage()) return true; 11042 11043 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11044 11045 // Walk up the stack to determine whether we can capture the variable, 11046 // performing the "simple" checks that don't depend on type. We stop when 11047 // we've either hit the declared scope of the variable or find an existing 11048 // capture of that variable. 11049 CaptureType = Var->getType(); 11050 DeclRefType = CaptureType.getNonReferenceType(); 11051 bool Explicit = (Kind != TryCapture_Implicit); 11052 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 11053 do { 11054 // Only block literals, captured statements, and lambda expressions can 11055 // capture; other scopes don't work. 11056 DeclContext *ParentDC; 11057 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) 11058 ParentDC = DC->getParent(); 11059 else if (isa<CXXMethodDecl>(DC) && 11060 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 11061 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 11062 ParentDC = DC->getParent()->getParent(); 11063 else { 11064 if (BuildAndDiagnose) 11065 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 11066 return true; 11067 } 11068 11069 CapturingScopeInfo *CSI = 11070 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 11071 11072 // Check whether we've already captured it. 11073 if (CSI->CaptureMap.count(Var)) { 11074 // If we found a capture, any subcaptures are nested. 11075 Nested = true; 11076 11077 // Retrieve the capture type for this variable. 11078 CaptureType = CSI->getCapture(Var).getCaptureType(); 11079 11080 // Compute the type of an expression that refers to this variable. 11081 DeclRefType = CaptureType.getNonReferenceType(); 11082 11083 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11084 if (Cap.isCopyCapture() && 11085 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11086 DeclRefType.addConst(); 11087 break; 11088 } 11089 11090 bool IsBlock = isa<BlockScopeInfo>(CSI); 11091 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11092 11093 // Lambdas are not allowed to capture unnamed variables 11094 // (e.g. anonymous unions). 11095 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11096 // assuming that's the intent. 11097 if (IsLambda && !Var->getDeclName()) { 11098 if (BuildAndDiagnose) { 11099 Diag(Loc, diag::err_lambda_capture_anonymous_var); 11100 Diag(Var->getLocation(), diag::note_declared_at); 11101 } 11102 return true; 11103 } 11104 11105 // Prohibit variably-modified types; they're difficult to deal with. 11106 if (Var->getType()->isVariablyModifiedType()) { 11107 if (BuildAndDiagnose) { 11108 if (IsBlock) 11109 Diag(Loc, diag::err_ref_vm_type); 11110 else 11111 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11112 Diag(Var->getLocation(), diag::note_previous_decl) 11113 << Var->getDeclName(); 11114 } 11115 return true; 11116 } 11117 // Prohibit structs with flexible array members too. 11118 // We cannot capture what is in the tail end of the struct. 11119 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11120 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11121 if (BuildAndDiagnose) { 11122 if (IsBlock) 11123 Diag(Loc, diag::err_ref_flexarray_type); 11124 else 11125 Diag(Loc, diag::err_lambda_capture_flexarray_type) 11126 << Var->getDeclName(); 11127 Diag(Var->getLocation(), diag::note_previous_decl) 11128 << Var->getDeclName(); 11129 } 11130 return true; 11131 } 11132 } 11133 // Lambdas are not allowed to capture __block variables; they don't 11134 // support the expected semantics. 11135 if (IsLambda && HasBlocksAttr) { 11136 if (BuildAndDiagnose) { 11137 Diag(Loc, diag::err_lambda_capture_block) 11138 << Var->getDeclName(); 11139 Diag(Var->getLocation(), diag::note_previous_decl) 11140 << Var->getDeclName(); 11141 } 11142 return true; 11143 } 11144 11145 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11146 // No capture-default 11147 if (BuildAndDiagnose) { 11148 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 11149 Diag(Var->getLocation(), diag::note_previous_decl) 11150 << Var->getDeclName(); 11151 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11152 diag::note_lambda_decl); 11153 } 11154 return true; 11155 } 11156 11157 FunctionScopesIndex--; 11158 DC = ParentDC; 11159 Explicit = false; 11160 } while (!Var->getDeclContext()->Equals(DC)); 11161 11162 // Walk back down the scope stack, computing the type of the capture at 11163 // each step, checking type-specific requirements, and adding captures if 11164 // requested. 11165 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 11166 ++I) { 11167 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11168 11169 // Compute the type of the capture and of a reference to the capture within 11170 // this scope. 11171 if (isa<BlockScopeInfo>(CSI)) { 11172 Expr *CopyExpr = 0; 11173 bool ByRef = false; 11174 11175 // Blocks are not allowed to capture arrays. 11176 if (CaptureType->isArrayType()) { 11177 if (BuildAndDiagnose) { 11178 Diag(Loc, diag::err_ref_array_type); 11179 Diag(Var->getLocation(), diag::note_previous_decl) 11180 << Var->getDeclName(); 11181 } 11182 return true; 11183 } 11184 11185 // Forbid the block-capture of autoreleasing variables. 11186 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11187 if (BuildAndDiagnose) { 11188 Diag(Loc, diag::err_arc_autoreleasing_capture) 11189 << /*block*/ 0; 11190 Diag(Var->getLocation(), diag::note_previous_decl) 11191 << Var->getDeclName(); 11192 } 11193 return true; 11194 } 11195 11196 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11197 // Block capture by reference does not change the capture or 11198 // declaration reference types. 11199 ByRef = true; 11200 } else { 11201 // Block capture by copy introduces 'const'. 11202 CaptureType = CaptureType.getNonReferenceType().withConst(); 11203 DeclRefType = CaptureType; 11204 11205 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 11206 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11207 // The capture logic needs the destructor, so make sure we mark it. 11208 // Usually this is unnecessary because most local variables have 11209 // their destructors marked at declaration time, but parameters are 11210 // an exception because it's technically only the call site that 11211 // actually requires the destructor. 11212 if (isa<ParmVarDecl>(Var)) 11213 FinalizeVarWithDestructor(Var, Record); 11214 11215 // Enter a new evaluation context to insulate the copy 11216 // full-expression. 11217 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11218 11219 // According to the blocks spec, the capture of a variable from 11220 // the stack requires a const copy constructor. This is not true 11221 // of the copy/move done to move a __block variable to the heap. 11222 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested, 11223 DeclRefType.withConst(), 11224 VK_LValue, Loc); 11225 11226 ExprResult Result 11227 = PerformCopyInitialization( 11228 InitializedEntity::InitializeBlock(Var->getLocation(), 11229 CaptureType, false), 11230 Loc, Owned(DeclRef)); 11231 11232 // Build a full-expression copy expression if initialization 11233 // succeeded and used a non-trivial constructor. Recover from 11234 // errors by pretending that the copy isn't necessary. 11235 if (!Result.isInvalid() && 11236 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11237 ->isTrivial()) { 11238 Result = MaybeCreateExprWithCleanups(Result); 11239 CopyExpr = Result.take(); 11240 } 11241 } 11242 } 11243 } 11244 11245 // Actually capture the variable. 11246 if (BuildAndDiagnose) 11247 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11248 SourceLocation(), CaptureType, CopyExpr); 11249 Nested = true; 11250 continue; 11251 } 11252 11253 if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11254 // By default, capture variables by reference. 11255 bool ByRef = true; 11256 // Using an LValue reference type is consistent with Lambdas (see below). 11257 CaptureType = Context.getLValueReferenceType(DeclRefType); 11258 11259 Expr *CopyExpr = 0; 11260 if (BuildAndDiagnose) { 11261 ExprResult Result = captureInCapturedRegion(*this, RSI, Var, 11262 CaptureType, DeclRefType, 11263 Loc, Nested); 11264 if (!Result.isInvalid()) 11265 CopyExpr = Result.take(); 11266 } 11267 11268 // Actually capture the variable. 11269 if (BuildAndDiagnose) 11270 CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc, 11271 SourceLocation(), CaptureType, CopyExpr); 11272 Nested = true; 11273 continue; 11274 } 11275 11276 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11277 11278 // Determine whether we are capturing by reference or by value. 11279 bool ByRef = false; 11280 if (I == N - 1 && Kind != TryCapture_Implicit) { 11281 ByRef = (Kind == TryCapture_ExplicitByRef); 11282 } else { 11283 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11284 } 11285 11286 // Compute the type of the field that will capture this variable. 11287 if (ByRef) { 11288 // C++11 [expr.prim.lambda]p15: 11289 // An entity is captured by reference if it is implicitly or 11290 // explicitly captured but not captured by copy. It is 11291 // unspecified whether additional unnamed non-static data 11292 // members are declared in the closure type for entities 11293 // captured by reference. 11294 // 11295 // FIXME: It is not clear whether we want to build an lvalue reference 11296 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11297 // to do the former, while EDG does the latter. Core issue 1249 will 11298 // clarify, but for now we follow GCC because it's a more permissive and 11299 // easily defensible position. 11300 CaptureType = Context.getLValueReferenceType(DeclRefType); 11301 } else { 11302 // C++11 [expr.prim.lambda]p14: 11303 // For each entity captured by copy, an unnamed non-static 11304 // data member is declared in the closure type. The 11305 // declaration order of these members is unspecified. The type 11306 // of such a data member is the type of the corresponding 11307 // captured entity if the entity is not a reference to an 11308 // object, or the referenced type otherwise. [Note: If the 11309 // captured entity is a reference to a function, the 11310 // corresponding data member is also a reference to a 11311 // function. - end note ] 11312 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11313 if (!RefType->getPointeeType()->isFunctionType()) 11314 CaptureType = RefType->getPointeeType(); 11315 } 11316 11317 // Forbid the lambda copy-capture of autoreleasing variables. 11318 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11319 if (BuildAndDiagnose) { 11320 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11321 Diag(Var->getLocation(), diag::note_previous_decl) 11322 << Var->getDeclName(); 11323 } 11324 return true; 11325 } 11326 } 11327 11328 // Capture this variable in the lambda. 11329 Expr *CopyExpr = 0; 11330 if (BuildAndDiagnose) { 11331 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 11332 DeclRefType, Loc, 11333 Nested); 11334 if (!Result.isInvalid()) 11335 CopyExpr = Result.take(); 11336 } 11337 11338 // Compute the type of a reference to this captured variable. 11339 if (ByRef) 11340 DeclRefType = CaptureType.getNonReferenceType(); 11341 else { 11342 // C++ [expr.prim.lambda]p5: 11343 // The closure type for a lambda-expression has a public inline 11344 // function call operator [...]. This function call operator is 11345 // declared const (9.3.1) if and only if the lambda-expression’s 11346 // parameter-declaration-clause is not followed by mutable. 11347 DeclRefType = CaptureType.getNonReferenceType(); 11348 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11349 DeclRefType.addConst(); 11350 } 11351 11352 // Add the capture. 11353 if (BuildAndDiagnose) 11354 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 11355 EllipsisLoc, CaptureType, CopyExpr); 11356 Nested = true; 11357 } 11358 11359 return false; 11360 } 11361 11362 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11363 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11364 QualType CaptureType; 11365 QualType DeclRefType; 11366 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11367 /*BuildAndDiagnose=*/true, CaptureType, 11368 DeclRefType); 11369 } 11370 11371 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11372 QualType CaptureType; 11373 QualType DeclRefType; 11374 11375 // Determine whether we can capture this variable. 11376 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11377 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 11378 return QualType(); 11379 11380 return DeclRefType; 11381 } 11382 11383 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 11384 SourceLocation Loc) { 11385 // Keep track of used but undefined variables. 11386 // FIXME: We shouldn't suppress this warning for static data members. 11387 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 11388 Var->getLinkage() != ExternalLinkage && 11389 !(Var->isStaticDataMember() && Var->hasInit())) { 11390 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 11391 if (old.isInvalid()) old = Loc; 11392 } 11393 11394 SemaRef.tryCaptureVariable(Var, Loc); 11395 11396 Var->setUsed(true); 11397 } 11398 11399 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 11400 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 11401 // an object that satisfies the requirements for appearing in a 11402 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 11403 // is immediately applied." This function handles the lvalue-to-rvalue 11404 // conversion part. 11405 MaybeODRUseExprs.erase(E->IgnoreParens()); 11406 } 11407 11408 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11409 if (!Res.isUsable()) 11410 return Res; 11411 11412 // If a constant-expression is a reference to a variable where we delay 11413 // deciding whether it is an odr-use, just assume we will apply the 11414 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11415 // (a non-type template argument), we have special handling anyway. 11416 UpdateMarkingForLValueToRValue(Res.get()); 11417 return Res; 11418 } 11419 11420 void Sema::CleanupVarDeclMarking() { 11421 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11422 e = MaybeODRUseExprs.end(); 11423 i != e; ++i) { 11424 VarDecl *Var; 11425 SourceLocation Loc; 11426 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11427 Var = cast<VarDecl>(DRE->getDecl()); 11428 Loc = DRE->getLocation(); 11429 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11430 Var = cast<VarDecl>(ME->getMemberDecl()); 11431 Loc = ME->getMemberLoc(); 11432 } else { 11433 llvm_unreachable("Unexpcted expression"); 11434 } 11435 11436 MarkVarDeclODRUsed(*this, Var, Loc); 11437 } 11438 11439 MaybeODRUseExprs.clear(); 11440 } 11441 11442 // Mark a VarDecl referenced, and perform the necessary handling to compute 11443 // odr-uses. 11444 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11445 VarDecl *Var, Expr *E) { 11446 Var->setReferenced(); 11447 11448 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11449 return; 11450 11451 // Implicit instantiation of static data members of class templates. 11452 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 11453 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 11454 assert(MSInfo && "Missing member specialization information?"); 11455 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 11456 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 11457 (!AlreadyInstantiated || 11458 Var->isUsableInConstantExpressions(SemaRef.Context))) { 11459 if (!AlreadyInstantiated) { 11460 // This is a modification of an existing AST node. Notify listeners. 11461 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11462 L->StaticDataMemberInstantiated(Var); 11463 MSInfo->setPointOfInstantiation(Loc); 11464 } 11465 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11466 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 11467 // Do not defer instantiations of variables which could be used in a 11468 // constant expression. 11469 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 11470 else 11471 SemaRef.PendingInstantiations.push_back( 11472 std::make_pair(Var, PointOfInstantiation)); 11473 } 11474 } 11475 11476 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11477 // the requirements for appearing in a constant expression (5.19) and, if 11478 // it is an object, the lvalue-to-rvalue conversion (4.1) 11479 // is immediately applied." We check the first part here, and 11480 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11481 // Note that we use the C++11 definition everywhere because nothing in 11482 // C++03 depends on whether we get the C++03 version correct. The second 11483 // part does not apply to references, since they are not objects. 11484 const VarDecl *DefVD; 11485 if (E && !isa<ParmVarDecl>(Var) && 11486 Var->isUsableInConstantExpressions(SemaRef.Context) && 11487 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11488 if (!Var->getType()->isReferenceType()) 11489 SemaRef.MaybeODRUseExprs.insert(E); 11490 } else 11491 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11492 } 11493 11494 /// \brief Mark a variable referenced, and check whether it is odr-used 11495 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11496 /// used directly for normal expressions referring to VarDecl. 11497 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11498 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11499 } 11500 11501 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11502 Decl *D, Expr *E, bool OdrUse) { 11503 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11504 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11505 return; 11506 } 11507 11508 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 11509 11510 // If this is a call to a method via a cast, also mark the method in the 11511 // derived class used in case codegen can devirtualize the call. 11512 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11513 if (!ME) 11514 return; 11515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 11516 if (!MD) 11517 return; 11518 const Expr *Base = ME->getBase(); 11519 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 11520 if (!MostDerivedClassDecl) 11521 return; 11522 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 11523 if (!DM || DM->isPure()) 11524 return; 11525 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 11526 } 11527 11528 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 11529 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 11530 // TODO: update this with DR# once a defect report is filed. 11531 // C++11 defect. The address of a pure member should not be an ODR use, even 11532 // if it's a qualified reference. 11533 bool OdrUse = true; 11534 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 11535 if (Method->isVirtual()) 11536 OdrUse = false; 11537 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 11538 } 11539 11540 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 11541 void Sema::MarkMemberReferenced(MemberExpr *E) { 11542 // C++11 [basic.def.odr]p2: 11543 // A non-overloaded function whose name appears as a potentially-evaluated 11544 // expression or a member of a set of candidate functions, if selected by 11545 // overload resolution when referred to from a potentially-evaluated 11546 // expression, is odr-used, unless it is a pure virtual function and its 11547 // name is not explicitly qualified. 11548 bool OdrUse = true; 11549 if (!E->hasQualifier()) { 11550 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 11551 if (Method->isPure()) 11552 OdrUse = false; 11553 } 11554 SourceLocation Loc = E->getMemberLoc().isValid() ? 11555 E->getMemberLoc() : E->getLocStart(); 11556 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 11557 } 11558 11559 /// \brief Perform marking for a reference to an arbitrary declaration. It 11560 /// marks the declaration referenced, and performs odr-use checking for functions 11561 /// and variables. This method should not be used when building an normal 11562 /// expression which refers to a variable. 11563 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 11564 if (OdrUse) { 11565 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11566 MarkVariableReferenced(Loc, VD); 11567 return; 11568 } 11569 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 11570 MarkFunctionReferenced(Loc, FD); 11571 return; 11572 } 11573 } 11574 D->setReferenced(); 11575 } 11576 11577 namespace { 11578 // Mark all of the declarations referenced 11579 // FIXME: Not fully implemented yet! We need to have a better understanding 11580 // of when we're entering 11581 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 11582 Sema &S; 11583 SourceLocation Loc; 11584 11585 public: 11586 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 11587 11588 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 11589 11590 bool TraverseTemplateArgument(const TemplateArgument &Arg); 11591 bool TraverseRecordType(RecordType *T); 11592 }; 11593 } 11594 11595 bool MarkReferencedDecls::TraverseTemplateArgument( 11596 const TemplateArgument &Arg) { 11597 if (Arg.getKind() == TemplateArgument::Declaration) { 11598 if (Decl *D = Arg.getAsDecl()) 11599 S.MarkAnyDeclReferenced(Loc, D, true); 11600 } 11601 11602 return Inherited::TraverseTemplateArgument(Arg); 11603 } 11604 11605 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 11606 if (ClassTemplateSpecializationDecl *Spec 11607 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 11608 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 11609 return TraverseTemplateArguments(Args.data(), Args.size()); 11610 } 11611 11612 return true; 11613 } 11614 11615 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 11616 MarkReferencedDecls Marker(*this, Loc); 11617 Marker.TraverseType(Context.getCanonicalType(T)); 11618 } 11619 11620 namespace { 11621 /// \brief Helper class that marks all of the declarations referenced by 11622 /// potentially-evaluated subexpressions as "referenced". 11623 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 11624 Sema &S; 11625 bool SkipLocalVariables; 11626 11627 public: 11628 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 11629 11630 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 11631 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 11632 11633 void VisitDeclRefExpr(DeclRefExpr *E) { 11634 // If we were asked not to visit local variables, don't. 11635 if (SkipLocalVariables) { 11636 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 11637 if (VD->hasLocalStorage()) 11638 return; 11639 } 11640 11641 S.MarkDeclRefReferenced(E); 11642 } 11643 11644 void VisitMemberExpr(MemberExpr *E) { 11645 S.MarkMemberReferenced(E); 11646 Inherited::VisitMemberExpr(E); 11647 } 11648 11649 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 11650 S.MarkFunctionReferenced(E->getLocStart(), 11651 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 11652 Visit(E->getSubExpr()); 11653 } 11654 11655 void VisitCXXNewExpr(CXXNewExpr *E) { 11656 if (E->getOperatorNew()) 11657 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 11658 if (E->getOperatorDelete()) 11659 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11660 Inherited::VisitCXXNewExpr(E); 11661 } 11662 11663 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11664 if (E->getOperatorDelete()) 11665 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11666 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11667 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11668 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11669 S.MarkFunctionReferenced(E->getLocStart(), 11670 S.LookupDestructor(Record)); 11671 } 11672 11673 Inherited::VisitCXXDeleteExpr(E); 11674 } 11675 11676 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11677 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 11678 Inherited::VisitCXXConstructExpr(E); 11679 } 11680 11681 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 11682 Visit(E->getExpr()); 11683 } 11684 11685 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11686 Inherited::VisitImplicitCastExpr(E); 11687 11688 if (E->getCastKind() == CK_LValueToRValue) 11689 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 11690 } 11691 }; 11692 } 11693 11694 /// \brief Mark any declarations that appear within this expression or any 11695 /// potentially-evaluated subexpressions as "referenced". 11696 /// 11697 /// \param SkipLocalVariables If true, don't mark local variables as 11698 /// 'referenced'. 11699 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 11700 bool SkipLocalVariables) { 11701 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 11702 } 11703 11704 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 11705 /// of the program being compiled. 11706 /// 11707 /// This routine emits the given diagnostic when the code currently being 11708 /// type-checked is "potentially evaluated", meaning that there is a 11709 /// possibility that the code will actually be executable. Code in sizeof() 11710 /// expressions, code used only during overload resolution, etc., are not 11711 /// potentially evaluated. This routine will suppress such diagnostics or, 11712 /// in the absolutely nutty case of potentially potentially evaluated 11713 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 11714 /// later. 11715 /// 11716 /// This routine should be used for all diagnostics that describe the run-time 11717 /// behavior of a program, such as passing a non-POD value through an ellipsis. 11718 /// Failure to do so will likely result in spurious diagnostics or failures 11719 /// during overload resolution or within sizeof/alignof/typeof/typeid. 11720 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 11721 const PartialDiagnostic &PD) { 11722 switch (ExprEvalContexts.back().Context) { 11723 case Unevaluated: 11724 // The argument will never be evaluated, so don't complain. 11725 break; 11726 11727 case ConstantEvaluated: 11728 // Relevant diagnostics should be produced by constant evaluation. 11729 break; 11730 11731 case PotentiallyEvaluated: 11732 case PotentiallyEvaluatedIfUsed: 11733 if (Statement && getCurFunctionOrMethodDecl()) { 11734 FunctionScopes.back()->PossiblyUnreachableDiags. 11735 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 11736 } 11737 else 11738 Diag(Loc, PD); 11739 11740 return true; 11741 } 11742 11743 return false; 11744 } 11745 11746 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 11747 CallExpr *CE, FunctionDecl *FD) { 11748 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 11749 return false; 11750 11751 // If we're inside a decltype's expression, don't check for a valid return 11752 // type or construct temporaries until we know whether this is the last call. 11753 if (ExprEvalContexts.back().IsDecltype) { 11754 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 11755 return false; 11756 } 11757 11758 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 11759 FunctionDecl *FD; 11760 CallExpr *CE; 11761 11762 public: 11763 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 11764 : FD(FD), CE(CE) { } 11765 11766 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 11767 if (!FD) { 11768 S.Diag(Loc, diag::err_call_incomplete_return) 11769 << T << CE->getSourceRange(); 11770 return; 11771 } 11772 11773 S.Diag(Loc, diag::err_call_function_incomplete_return) 11774 << CE->getSourceRange() << FD->getDeclName() << T; 11775 S.Diag(FD->getLocation(), 11776 diag::note_function_with_incomplete_return_type_declared_here) 11777 << FD->getDeclName(); 11778 } 11779 } Diagnoser(FD, CE); 11780 11781 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 11782 return true; 11783 11784 return false; 11785 } 11786 11787 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 11788 // will prevent this condition from triggering, which is what we want. 11789 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 11790 SourceLocation Loc; 11791 11792 unsigned diagnostic = diag::warn_condition_is_assignment; 11793 bool IsOrAssign = false; 11794 11795 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 11796 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 11797 return; 11798 11799 IsOrAssign = Op->getOpcode() == BO_OrAssign; 11800 11801 // Greylist some idioms by putting them into a warning subcategory. 11802 if (ObjCMessageExpr *ME 11803 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 11804 Selector Sel = ME->getSelector(); 11805 11806 // self = [<foo> init...] 11807 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 11808 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11809 11810 // <foo> = [<bar> nextObject] 11811 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 11812 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11813 } 11814 11815 Loc = Op->getOperatorLoc(); 11816 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 11817 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 11818 return; 11819 11820 IsOrAssign = Op->getOperator() == OO_PipeEqual; 11821 Loc = Op->getOperatorLoc(); 11822 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 11823 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 11824 else { 11825 // Not an assignment. 11826 return; 11827 } 11828 11829 Diag(Loc, diagnostic) << E->getSourceRange(); 11830 11831 SourceLocation Open = E->getLocStart(); 11832 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 11833 Diag(Loc, diag::note_condition_assign_silence) 11834 << FixItHint::CreateInsertion(Open, "(") 11835 << FixItHint::CreateInsertion(Close, ")"); 11836 11837 if (IsOrAssign) 11838 Diag(Loc, diag::note_condition_or_assign_to_comparison) 11839 << FixItHint::CreateReplacement(Loc, "!="); 11840 else 11841 Diag(Loc, diag::note_condition_assign_to_comparison) 11842 << FixItHint::CreateReplacement(Loc, "=="); 11843 } 11844 11845 /// \brief Redundant parentheses over an equality comparison can indicate 11846 /// that the user intended an assignment used as condition. 11847 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 11848 // Don't warn if the parens came from a macro. 11849 SourceLocation parenLoc = ParenE->getLocStart(); 11850 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 11851 return; 11852 // Don't warn for dependent expressions. 11853 if (ParenE->isTypeDependent()) 11854 return; 11855 11856 Expr *E = ParenE->IgnoreParens(); 11857 11858 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 11859 if (opE->getOpcode() == BO_EQ && 11860 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 11861 == Expr::MLV_Valid) { 11862 SourceLocation Loc = opE->getOperatorLoc(); 11863 11864 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 11865 SourceRange ParenERange = ParenE->getSourceRange(); 11866 Diag(Loc, diag::note_equality_comparison_silence) 11867 << FixItHint::CreateRemoval(ParenERange.getBegin()) 11868 << FixItHint::CreateRemoval(ParenERange.getEnd()); 11869 Diag(Loc, diag::note_equality_comparison_to_assign) 11870 << FixItHint::CreateReplacement(Loc, "="); 11871 } 11872 } 11873 11874 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 11875 DiagnoseAssignmentAsCondition(E); 11876 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 11877 DiagnoseEqualityWithExtraParens(parenE); 11878 11879 ExprResult result = CheckPlaceholderExpr(E); 11880 if (result.isInvalid()) return ExprError(); 11881 E = result.take(); 11882 11883 if (!E->isTypeDependent()) { 11884 if (getLangOpts().CPlusPlus) 11885 return CheckCXXBooleanCondition(E); // C++ 6.4p4 11886 11887 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 11888 if (ERes.isInvalid()) 11889 return ExprError(); 11890 E = ERes.take(); 11891 11892 QualType T = E->getType(); 11893 if (!T->isScalarType()) { // C99 6.8.4.1p1 11894 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 11895 << T << E->getSourceRange(); 11896 return ExprError(); 11897 } 11898 } 11899 11900 return Owned(E); 11901 } 11902 11903 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 11904 Expr *SubExpr) { 11905 if (!SubExpr) 11906 return ExprError(); 11907 11908 return CheckBooleanCondition(SubExpr, Loc); 11909 } 11910 11911 namespace { 11912 /// A visitor for rebuilding a call to an __unknown_any expression 11913 /// to have an appropriate type. 11914 struct RebuildUnknownAnyFunction 11915 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 11916 11917 Sema &S; 11918 11919 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 11920 11921 ExprResult VisitStmt(Stmt *S) { 11922 llvm_unreachable("unexpected statement!"); 11923 } 11924 11925 ExprResult VisitExpr(Expr *E) { 11926 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 11927 << E->getSourceRange(); 11928 return ExprError(); 11929 } 11930 11931 /// Rebuild an expression which simply semantically wraps another 11932 /// expression which it shares the type and value kind of. 11933 template <class T> ExprResult rebuildSugarExpr(T *E) { 11934 ExprResult SubResult = Visit(E->getSubExpr()); 11935 if (SubResult.isInvalid()) return ExprError(); 11936 11937 Expr *SubExpr = SubResult.take(); 11938 E->setSubExpr(SubExpr); 11939 E->setType(SubExpr->getType()); 11940 E->setValueKind(SubExpr->getValueKind()); 11941 assert(E->getObjectKind() == OK_Ordinary); 11942 return E; 11943 } 11944 11945 ExprResult VisitParenExpr(ParenExpr *E) { 11946 return rebuildSugarExpr(E); 11947 } 11948 11949 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11950 return rebuildSugarExpr(E); 11951 } 11952 11953 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11954 ExprResult SubResult = Visit(E->getSubExpr()); 11955 if (SubResult.isInvalid()) return ExprError(); 11956 11957 Expr *SubExpr = SubResult.take(); 11958 E->setSubExpr(SubExpr); 11959 E->setType(S.Context.getPointerType(SubExpr->getType())); 11960 assert(E->getValueKind() == VK_RValue); 11961 assert(E->getObjectKind() == OK_Ordinary); 11962 return E; 11963 } 11964 11965 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 11966 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 11967 11968 E->setType(VD->getType()); 11969 11970 assert(E->getValueKind() == VK_RValue); 11971 if (S.getLangOpts().CPlusPlus && 11972 !(isa<CXXMethodDecl>(VD) && 11973 cast<CXXMethodDecl>(VD)->isInstance())) 11974 E->setValueKind(VK_LValue); 11975 11976 return E; 11977 } 11978 11979 ExprResult VisitMemberExpr(MemberExpr *E) { 11980 return resolveDecl(E, E->getMemberDecl()); 11981 } 11982 11983 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11984 return resolveDecl(E, E->getDecl()); 11985 } 11986 }; 11987 } 11988 11989 /// Given a function expression of unknown-any type, try to rebuild it 11990 /// to have a function type. 11991 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 11992 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 11993 if (Result.isInvalid()) return ExprError(); 11994 return S.DefaultFunctionArrayConversion(Result.take()); 11995 } 11996 11997 namespace { 11998 /// A visitor for rebuilding an expression of type __unknown_anytype 11999 /// into one which resolves the type directly on the referring 12000 /// expression. Strict preservation of the original source 12001 /// structure is not a goal. 12002 struct RebuildUnknownAnyExpr 12003 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12004 12005 Sema &S; 12006 12007 /// The current destination type. 12008 QualType DestType; 12009 12010 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12011 : S(S), DestType(CastType) {} 12012 12013 ExprResult VisitStmt(Stmt *S) { 12014 llvm_unreachable("unexpected statement!"); 12015 } 12016 12017 ExprResult VisitExpr(Expr *E) { 12018 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12019 << E->getSourceRange(); 12020 return ExprError(); 12021 } 12022 12023 ExprResult VisitCallExpr(CallExpr *E); 12024 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12025 12026 /// Rebuild an expression which simply semantically wraps another 12027 /// expression which it shares the type and value kind of. 12028 template <class T> ExprResult rebuildSugarExpr(T *E) { 12029 ExprResult SubResult = Visit(E->getSubExpr()); 12030 if (SubResult.isInvalid()) return ExprError(); 12031 Expr *SubExpr = SubResult.take(); 12032 E->setSubExpr(SubExpr); 12033 E->setType(SubExpr->getType()); 12034 E->setValueKind(SubExpr->getValueKind()); 12035 assert(E->getObjectKind() == OK_Ordinary); 12036 return E; 12037 } 12038 12039 ExprResult VisitParenExpr(ParenExpr *E) { 12040 return rebuildSugarExpr(E); 12041 } 12042 12043 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12044 return rebuildSugarExpr(E); 12045 } 12046 12047 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12048 const PointerType *Ptr = DestType->getAs<PointerType>(); 12049 if (!Ptr) { 12050 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12051 << E->getSourceRange(); 12052 return ExprError(); 12053 } 12054 assert(E->getValueKind() == VK_RValue); 12055 assert(E->getObjectKind() == OK_Ordinary); 12056 E->setType(DestType); 12057 12058 // Build the sub-expression as if it were an object of the pointee type. 12059 DestType = Ptr->getPointeeType(); 12060 ExprResult SubResult = Visit(E->getSubExpr()); 12061 if (SubResult.isInvalid()) return ExprError(); 12062 E->setSubExpr(SubResult.take()); 12063 return E; 12064 } 12065 12066 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12067 12068 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12069 12070 ExprResult VisitMemberExpr(MemberExpr *E) { 12071 return resolveDecl(E, E->getMemberDecl()); 12072 } 12073 12074 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12075 return resolveDecl(E, E->getDecl()); 12076 } 12077 }; 12078 } 12079 12080 /// Rebuilds a call expression which yielded __unknown_anytype. 12081 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12082 Expr *CalleeExpr = E->getCallee(); 12083 12084 enum FnKind { 12085 FK_MemberFunction, 12086 FK_FunctionPointer, 12087 FK_BlockPointer 12088 }; 12089 12090 FnKind Kind; 12091 QualType CalleeType = CalleeExpr->getType(); 12092 if (CalleeType == S.Context.BoundMemberTy) { 12093 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12094 Kind = FK_MemberFunction; 12095 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12096 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12097 CalleeType = Ptr->getPointeeType(); 12098 Kind = FK_FunctionPointer; 12099 } else { 12100 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12101 Kind = FK_BlockPointer; 12102 } 12103 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12104 12105 // Verify that this is a legal result type of a function. 12106 if (DestType->isArrayType() || DestType->isFunctionType()) { 12107 unsigned diagID = diag::err_func_returning_array_function; 12108 if (Kind == FK_BlockPointer) 12109 diagID = diag::err_block_returning_array_function; 12110 12111 S.Diag(E->getExprLoc(), diagID) 12112 << DestType->isFunctionType() << DestType; 12113 return ExprError(); 12114 } 12115 12116 // Otherwise, go ahead and set DestType as the call's result. 12117 E->setType(DestType.getNonLValueExprType(S.Context)); 12118 E->setValueKind(Expr::getValueKindForType(DestType)); 12119 assert(E->getObjectKind() == OK_Ordinary); 12120 12121 // Rebuild the function type, replacing the result type with DestType. 12122 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 12123 DestType = 12124 S.Context.getFunctionType(DestType, 12125 ArrayRef<QualType>(Proto->arg_type_begin(), 12126 Proto->getNumArgs()), 12127 Proto->getExtProtoInfo()); 12128 else 12129 DestType = S.Context.getFunctionNoProtoType(DestType, 12130 FnType->getExtInfo()); 12131 12132 // Rebuild the appropriate pointer-to-function type. 12133 switch (Kind) { 12134 case FK_MemberFunction: 12135 // Nothing to do. 12136 break; 12137 12138 case FK_FunctionPointer: 12139 DestType = S.Context.getPointerType(DestType); 12140 break; 12141 12142 case FK_BlockPointer: 12143 DestType = S.Context.getBlockPointerType(DestType); 12144 break; 12145 } 12146 12147 // Finally, we can recurse. 12148 ExprResult CalleeResult = Visit(CalleeExpr); 12149 if (!CalleeResult.isUsable()) return ExprError(); 12150 E->setCallee(CalleeResult.take()); 12151 12152 // Bind a temporary if necessary. 12153 return S.MaybeBindToTemporary(E); 12154 } 12155 12156 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12157 // Verify that this is a legal result type of a call. 12158 if (DestType->isArrayType() || DestType->isFunctionType()) { 12159 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12160 << DestType->isFunctionType() << DestType; 12161 return ExprError(); 12162 } 12163 12164 // Rewrite the method result type if available. 12165 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12166 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12167 Method->setResultType(DestType); 12168 } 12169 12170 // Change the type of the message. 12171 E->setType(DestType.getNonReferenceType()); 12172 E->setValueKind(Expr::getValueKindForType(DestType)); 12173 12174 return S.MaybeBindToTemporary(E); 12175 } 12176 12177 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12178 // The only case we should ever see here is a function-to-pointer decay. 12179 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12180 assert(E->getValueKind() == VK_RValue); 12181 assert(E->getObjectKind() == OK_Ordinary); 12182 12183 E->setType(DestType); 12184 12185 // Rebuild the sub-expression as the pointee (function) type. 12186 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12187 12188 ExprResult Result = Visit(E->getSubExpr()); 12189 if (!Result.isUsable()) return ExprError(); 12190 12191 E->setSubExpr(Result.take()); 12192 return S.Owned(E); 12193 } else if (E->getCastKind() == CK_LValueToRValue) { 12194 assert(E->getValueKind() == VK_RValue); 12195 assert(E->getObjectKind() == OK_Ordinary); 12196 12197 assert(isa<BlockPointerType>(E->getType())); 12198 12199 E->setType(DestType); 12200 12201 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12202 DestType = S.Context.getLValueReferenceType(DestType); 12203 12204 ExprResult Result = Visit(E->getSubExpr()); 12205 if (!Result.isUsable()) return ExprError(); 12206 12207 E->setSubExpr(Result.take()); 12208 return S.Owned(E); 12209 } else { 12210 llvm_unreachable("Unhandled cast type!"); 12211 } 12212 } 12213 12214 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12215 ExprValueKind ValueKind = VK_LValue; 12216 QualType Type = DestType; 12217 12218 // We know how to make this work for certain kinds of decls: 12219 12220 // - functions 12221 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12222 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12223 DestType = Ptr->getPointeeType(); 12224 ExprResult Result = resolveDecl(E, VD); 12225 if (Result.isInvalid()) return ExprError(); 12226 return S.ImpCastExprToType(Result.take(), Type, 12227 CK_FunctionToPointerDecay, VK_RValue); 12228 } 12229 12230 if (!Type->isFunctionType()) { 12231 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12232 << VD << E->getSourceRange(); 12233 return ExprError(); 12234 } 12235 12236 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12237 if (MD->isInstance()) { 12238 ValueKind = VK_RValue; 12239 Type = S.Context.BoundMemberTy; 12240 } 12241 12242 // Function references aren't l-values in C. 12243 if (!S.getLangOpts().CPlusPlus) 12244 ValueKind = VK_RValue; 12245 12246 // - variables 12247 } else if (isa<VarDecl>(VD)) { 12248 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12249 Type = RefTy->getPointeeType(); 12250 } else if (Type->isFunctionType()) { 12251 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12252 << VD << E->getSourceRange(); 12253 return ExprError(); 12254 } 12255 12256 // - nothing else 12257 } else { 12258 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12259 << VD << E->getSourceRange(); 12260 return ExprError(); 12261 } 12262 12263 VD->setType(DestType); 12264 E->setType(Type); 12265 E->setValueKind(ValueKind); 12266 return S.Owned(E); 12267 } 12268 12269 /// Check a cast of an unknown-any type. We intentionally only 12270 /// trigger this for C-style casts. 12271 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12272 Expr *CastExpr, CastKind &CastKind, 12273 ExprValueKind &VK, CXXCastPath &Path) { 12274 // Rewrite the casted expression from scratch. 12275 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12276 if (!result.isUsable()) return ExprError(); 12277 12278 CastExpr = result.take(); 12279 VK = CastExpr->getValueKind(); 12280 CastKind = CK_NoOp; 12281 12282 return CastExpr; 12283 } 12284 12285 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 12286 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 12287 } 12288 12289 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 12290 Expr *arg, QualType ¶mType) { 12291 // If the syntactic form of the argument is not an explicit cast of 12292 // any sort, just do default argument promotion. 12293 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 12294 if (!castArg) { 12295 ExprResult result = DefaultArgumentPromotion(arg); 12296 if (result.isInvalid()) return ExprError(); 12297 paramType = result.get()->getType(); 12298 return result; 12299 } 12300 12301 // Otherwise, use the type that was written in the explicit cast. 12302 assert(!arg->hasPlaceholderType()); 12303 paramType = castArg->getTypeAsWritten(); 12304 12305 // Copy-initialize a parameter of that type. 12306 InitializedEntity entity = 12307 InitializedEntity::InitializeParameter(Context, paramType, 12308 /*consumed*/ false); 12309 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 12310 } 12311 12312 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 12313 Expr *orig = E; 12314 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 12315 while (true) { 12316 E = E->IgnoreParenImpCasts(); 12317 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 12318 E = call->getCallee(); 12319 diagID = diag::err_uncasted_call_of_unknown_any; 12320 } else { 12321 break; 12322 } 12323 } 12324 12325 SourceLocation loc; 12326 NamedDecl *d; 12327 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 12328 loc = ref->getLocation(); 12329 d = ref->getDecl(); 12330 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 12331 loc = mem->getMemberLoc(); 12332 d = mem->getMemberDecl(); 12333 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 12334 diagID = diag::err_uncasted_call_of_unknown_any; 12335 loc = msg->getSelectorStartLoc(); 12336 d = msg->getMethodDecl(); 12337 if (!d) { 12338 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 12339 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 12340 << orig->getSourceRange(); 12341 return ExprError(); 12342 } 12343 } else { 12344 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12345 << E->getSourceRange(); 12346 return ExprError(); 12347 } 12348 12349 S.Diag(loc, diagID) << d << orig->getSourceRange(); 12350 12351 // Never recoverable. 12352 return ExprError(); 12353 } 12354 12355 /// Check for operands with placeholder types and complain if found. 12356 /// Returns true if there was an error and no recovery was possible. 12357 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 12358 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 12359 if (!placeholderType) return Owned(E); 12360 12361 switch (placeholderType->getKind()) { 12362 12363 // Overloaded expressions. 12364 case BuiltinType::Overload: { 12365 // Try to resolve a single function template specialization. 12366 // This is obligatory. 12367 ExprResult result = Owned(E); 12368 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 12369 return result; 12370 12371 // If that failed, try to recover with a call. 12372 } else { 12373 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 12374 /*complain*/ true); 12375 return result; 12376 } 12377 } 12378 12379 // Bound member functions. 12380 case BuiltinType::BoundMember: { 12381 ExprResult result = Owned(E); 12382 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 12383 /*complain*/ true); 12384 return result; 12385 } 12386 12387 // ARC unbridged casts. 12388 case BuiltinType::ARCUnbridgedCast: { 12389 Expr *realCast = stripARCUnbridgedCast(E); 12390 diagnoseARCUnbridgedCast(realCast); 12391 return Owned(realCast); 12392 } 12393 12394 // Expressions of unknown type. 12395 case BuiltinType::UnknownAny: 12396 return diagnoseUnknownAnyExpr(*this, E); 12397 12398 // Pseudo-objects. 12399 case BuiltinType::PseudoObject: 12400 return checkPseudoObjectRValue(E); 12401 12402 case BuiltinType::BuiltinFn: 12403 Diag(E->getLocStart(), diag::err_builtin_fn_use); 12404 return ExprError(); 12405 12406 // Everything else should be impossible. 12407 #define BUILTIN_TYPE(Id, SingletonId) \ 12408 case BuiltinType::Id: 12409 #define PLACEHOLDER_TYPE(Id, SingletonId) 12410 #include "clang/AST/BuiltinTypes.def" 12411 break; 12412 } 12413 12414 llvm_unreachable("invalid placeholder type!"); 12415 } 12416 12417 bool Sema::CheckCaseExpression(Expr *E) { 12418 if (E->isTypeDependent()) 12419 return true; 12420 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 12421 return E->getType()->isIntegralOrEnumerationType(); 12422 return false; 12423 } 12424 12425 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 12426 ExprResult 12427 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 12428 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 12429 "Unknown Objective-C Boolean value!"); 12430 QualType BoolT = Context.ObjCBuiltinBoolTy; 12431 if (!Context.getBOOLDecl()) { 12432 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 12433 Sema::LookupOrdinaryName); 12434 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 12435 NamedDecl *ND = Result.getFoundDecl(); 12436 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 12437 Context.setBOOLDecl(TD); 12438 } 12439 } 12440 if (Context.getBOOLDecl()) 12441 BoolT = Context.getBOOLType(); 12442 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12443 BoolT, OpLoc)); 12444 } 12445