SemaChecking.cpp revision be22cb84f32cfa6cf0b6bdaf523288b747bb0f18
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// The LLVM Compiler Infrastructure 45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 55f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source 65f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)// License. See LICENSE.TXT for details. 75f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)// 8c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch//===----------------------------------------------------------------------===// 9c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch// 10c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch// This file implements extra semantic analysis beyond what is enforced 115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// by the C type system. 125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 135f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)//===----------------------------------------------------------------------===// 145f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) 155f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/Sema/Initialization.h" 165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/Sema.h" 175f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/Sema/SemaInternal.h" 185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/Initialization.h" 195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/Lookup.h" 205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/ScopeInfo.h" 215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Analysis/Analyses/FormatString.h" 225f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/ASTContext.h" 235f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/CharUnits.h" 245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclCXX.h" 255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclObjC.h" 265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/Expr.h" 275f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/ExprCXX.h" 285f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/ExprObjC.h" 295f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/EvaluatedExprVisitor.h" 305f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/DeclObjC.h" 315f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/StmtCXX.h" 325f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/StmtObjC.h" 335f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/Lex/Preprocessor.h" 345f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "llvm/ADT/BitVector.h" 355f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "llvm/ADT/SmallString.h" 361320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/ADT/STLExtras.h" 375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/raw_ostream.h" 385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/TargetBuiltins.h" 395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/TargetInfo.h" 40eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "clang/Basic/ConvertUTF.h" 412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include <limits> 422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)using namespace clang; 435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace sema; 445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) unsigned ByteNo) const { 475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) PP.getLangOpts(), PP.getTargetInfo()); 495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 51cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)/// Checks that a call expression's argument count is the desired number. 525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// This is useful when doing custom type-checking. Returns true on error. 531320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccistatic bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 541320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci unsigned argCount = call->getNumArgs(); 55cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) if (argCount == desiredArgCount) return false; 56cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) 57cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) if (argCount < desiredArgCount) 58cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 59cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) << 0 /*function call*/ << desiredArgCount << argCount 605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) << call->getSourceRange(); 615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // Highlight all the excess arguments. 635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) call->getArg(argCount - 1)->getLocEnd()); 655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) << 0 /*function call*/ << desiredArgCount << argCount 682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) << call->getArg(1)->getSourceRange(); 692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)} 702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) 715d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// Check that the first argument to __builtin_annotation is an integer 725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// and the second argument is a non-wide string literal. 735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 741320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci if (checkArgCount(S, TheCall, 2)) 755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return true; 765d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 77116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch // First argument should be an integer. 785d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) Expr *ValArg = TheCall->getArg(0); 795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) QualType Ty = ValArg->getType(); 80eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch if (!Ty->isIntegerType()) { 81a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles) S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) << ValArg->getSourceRange(); 835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return true; 845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // Second argument should be a constant string. 87e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 89f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) if (!Literal || !Literal->isAscii()) { 90a3f7b4e666c476898878fa745f637129375cd889Ben Murdoch S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 911e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) << StrArg->getSourceRange(); 921e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) return true; 935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 9458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles) 95a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles) TheCall->setType(Ty); 96f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) return false; 97cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)} 981320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci 991320f92c476a1ad9d19dba2a48c72b75566198e9Primiano TucciExprResult 100cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 101cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) ExprResult TheCallResult(Owned(TheCall)); 1026d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles) 1030de6073388f4e2780db8536178b129cd8f6ab386Torne (Richard Coles) // Find out if any arguments are required to be integer constant expressions. 1041320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci unsigned ICEArguments = 0; 1055f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) ASTContext::GetBuiltinTypeError Error; 1065f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1075f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (Error != ASTContext::GE_None) 1085f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1095f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) 1105f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) // If any arguments are required to be ICE's, check and diagnose. 1115f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1125f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) // Skip arguments not required to be ICE's. 1131320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1145f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) 1155f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) llvm::APSInt Result; 1165f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 117ab8f6f0bd665d3c1ff476eb06c58c42630e462d4Ben Murdoch return true; 1185f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) ICEArguments &= ~(1 << ArgNo); 1195f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) } 120a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) 121effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch switch (BuiltinID) { 1225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case Builtin::BI__builtin___CFStringMakeConstantString: 1235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) assert(TheCall->getNumArgs() == 1 && 1245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) "Wrong # arguments to builtin CFStringMakeConstantString"); 1255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (CheckObjCString(TheCall->getArg(0))) 1265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return ExprError(); 1275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) break; 1282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) case Builtin::BI__builtin_stdarg_start: 1295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case Builtin::BI__builtin_va_start: 1305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (SemaBuiltinVAStart(TheCall)) 1315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return ExprError(); 1325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) break; 1335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case Builtin::BI__builtin_isgreater: 1345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case Builtin::BI__builtin_isgreaterequal: 135eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__builtin_isless: 1365f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_islessequal: 1375f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_islessgreater: 138f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) case Builtin::BI__builtin_isunordered: 1395f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (SemaBuiltinUnorderedCompare(TheCall)) 1405f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return ExprError(); 1415f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) break; 1425f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_fpclassify: 1435f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (SemaBuiltinFPClassification(TheCall, 6)) 1445f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return ExprError(); 1455f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) break; 1465f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_isfinite: 1475f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_isinf: 1485f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_isinf_sign: 1495f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_isnan: 1505f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_isnormal: 1515f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (SemaBuiltinFPClassification(TheCall, 1)) 1525f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return ExprError(); 1535f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) break; 154eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__builtin_shufflevector: 155eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch return SemaBuiltinShuffleVector(TheCall); 156eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch // TheCall will be freed by the smart pointer here, but that's fine, since 157eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch // SemaBuiltinShuffleVector guts it, but then doesn't release it. 158eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__builtin_prefetch: 159eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch if (SemaBuiltinPrefetch(TheCall)) 160eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch return ExprError(); 1611320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci break; 162eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__builtin_object_size: 163eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch if (SemaBuiltinObjectSize(TheCall)) 164eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch return ExprError(); 165eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch break; 166eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__builtin_longjmp: 167116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch if (SemaBuiltinLongjmp(TheCall)) 168116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch return ExprError(); 169116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch break; 170eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch 171eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__builtin_classify_type: 172eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch if (checkArgCount(*this, TheCall, 1)) return true; 173eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch TheCall->setType(Context.IntTy); 174eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch break; 175eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__builtin_constant_p: 176eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch if (checkArgCount(*this, TheCall, 1)) return true; 177eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch TheCall->setType(Context.IntTy); 178eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch break; 179eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_add: 180eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_add_1: 181eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_add_2: 182eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_add_4: 183eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_add_8: 184eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_add_16: 185eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_sub: 186cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_fetch_and_sub_1: 187eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_sub_2: 1881320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci case Builtin::BI__sync_fetch_and_sub_4: 1891320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci case Builtin::BI__sync_fetch_and_sub_8: 190cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_fetch_and_sub_16: 191cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_fetch_and_or: 192cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_fetch_and_or_1: 193cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_fetch_and_or_2: 194cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_fetch_and_or_4: 195eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_or_8: 196eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_or_16: 197eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_and: 198eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_and_1: 199eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_and_2: 200eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_and_4: 201eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_and_8: 202eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_and_16: 203eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_xor: 204eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_xor_1: 205eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_xor_2: 2065d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) case Builtin::BI__sync_fetch_and_xor_4: 207eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_xor_8: 208eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_fetch_and_xor_16: 209eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_add_and_fetch: 210eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_add_and_fetch_1: 2115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) case Builtin::BI__sync_add_and_fetch_2: 2125d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) case Builtin::BI__sync_add_and_fetch_4: 213eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_add_and_fetch_8: 214eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_add_and_fetch_16: 215a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles) case Builtin::BI__sync_sub_and_fetch: 216eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_sub_and_fetch_1: 217eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_sub_and_fetch_2: 218eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_sub_and_fetch_4: 219eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_sub_and_fetch_8: 220eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_sub_and_fetch_16: 221e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch case Builtin::BI__sync_and_and_fetch: 222eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_and_and_fetch_1: 223f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) case Builtin::BI__sync_and_and_fetch_2: 224a3f7b4e666c476898878fa745f637129375cd889Ben Murdoch case Builtin::BI__sync_and_and_fetch_4: 2251e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) case Builtin::BI__sync_and_and_fetch_8: 2261e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles) case Builtin::BI__sync_and_and_fetch_16: 227eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_or_and_fetch: 22858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles) case Builtin::BI__sync_or_and_fetch_1: 229a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles) case Builtin::BI__sync_or_and_fetch_2: 230f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) case Builtin::BI__sync_or_and_fetch_4: 231cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_or_and_fetch_8: 2321320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci case Builtin::BI__sync_or_and_fetch_16: 2331320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci case Builtin::BI__sync_xor_and_fetch: 234cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_xor_and_fetch_1: 235cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles) case Builtin::BI__sync_xor_and_fetch_2: 2366d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles) case Builtin::BI__sync_xor_and_fetch_4: 2370de6073388f4e2780db8536178b129cd8f6ab386Torne (Richard Coles) case Builtin::BI__sync_xor_and_fetch_8: 2381320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci case Builtin::BI__sync_xor_and_fetch_16: 2395f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_val_compare_and_swap: 2405f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_val_compare_and_swap_1: 2415f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_val_compare_and_swap_2: 2425f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_val_compare_and_swap_4: 2435f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_val_compare_and_swap_8: 2445f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_val_compare_and_swap_16: 2455f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_bool_compare_and_swap: 2465f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_bool_compare_and_swap_1: 2471320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci case Builtin::BI__sync_bool_compare_and_swap_2: 2485f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_bool_compare_and_swap_4: 2495f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_bool_compare_and_swap_8: 2505f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_bool_compare_and_swap_16: 251ab8f6f0bd665d3c1ff476eb06c58c42630e462d4Ben Murdoch case Builtin::BI__sync_lock_test_and_set: 2525f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_lock_test_and_set_1: 2535f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__sync_lock_test_and_set_2: 254a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) case Builtin::BI__sync_lock_test_and_set_4: 255effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch case Builtin::BI__sync_lock_test_and_set_8: 256eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_lock_test_and_set_16: 257eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_lock_release: 258eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_lock_release_1: 259eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_lock_release_2: 260eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_lock_release_4: 261eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_lock_release_8: 262eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_lock_release_16: 263eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_swap: 264eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_swap_1: 265eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_swap_2: 266eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_swap_4: 267eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_swap_8: 268eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case Builtin::BI__sync_swap_16: 269eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch return SemaBuiltinAtomicOverloaded(TheCallResult); 270eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#define BUILTIN(ID, TYPE, ATTRS) 2715f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 2725f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI##ID: \ 273f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 2745f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/Basic/Builtins.def" 2755f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case Builtin::BI__builtin_annotation: 2765f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (SemaBuiltinAnnotation(*this, TheCall)) 2775f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return ExprError(); 2785f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) break; 2795f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) } 2805f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) 2815f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) // Since the target specific builtins for each arch overlap, only check those 2825f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) // of the arch we are compiling for. 2835f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (BuiltinID >= Builtin::FirstTSBuiltin) { 2845f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) switch (Context.getTargetInfo().getTriple().getArch()) { 2855f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case llvm::Triple::arm: 2865f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case llvm::Triple::thumb: 2875f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 2885f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return ExprError(); 28990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles) break; 29090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles) case llvm::Triple::mips: 29190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles) case llvm::Triple::mipsel: 2925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case llvm::Triple::mips64: 2935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case llvm::Triple::mips64el: 2945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 295eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch return ExprError(); 2961320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci break; 2975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) default: 2985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) break; 2995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 3005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 3015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 302116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch return TheCallResult; 303116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch} 304116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch 3052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// Get the valid immediate range for the specified NEON type code. 3062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)static unsigned RFT(unsigned t, bool shift = false) { 3075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) NeonTypeFlags Type(t); 308eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch int IsQuad = Type.isQuad(); 309eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch switch (Type.getEltType()) { 310eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case NeonTypeFlags::Int8: 311eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch case NeonTypeFlags::Poly8: 312a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) return shift ? 7 : (8 << IsQuad) - 1; 3135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case NeonTypeFlags::Int16: 3145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) case NeonTypeFlags::Poly16: 3155f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return shift ? 15 : (4 << IsQuad) - 1; 3165f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case NeonTypeFlags::Int32: 3175f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return shift ? 31 : (2 << IsQuad) - 1; 3185f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case NeonTypeFlags::Int64: 3195f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return shift ? 63 : (1 << IsQuad) - 1; 3205f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case NeonTypeFlags::Float16: 3215f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) assert(!shift && "cannot shift float types!"); 3225f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return (4 << IsQuad) - 1; 3235f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) case NeonTypeFlags::Float32: 3245f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) assert(!shift && "cannot shift float types!"); 3255f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) return (2 << IsQuad) - 1; 326c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch } 3275f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) llvm_unreachable("Invalid NeonTypeFlag!"); 328} 329 330/// getNeonEltType - Return the QualType corresponding to the elements of 331/// the vector type specified by the NeonTypeFlags. This is used to check 332/// the pointer arguments for Neon load/store intrinsics. 333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 334 switch (Flags.getEltType()) { 335 case NeonTypeFlags::Int8: 336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 337 case NeonTypeFlags::Int16: 338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 339 case NeonTypeFlags::Int32: 340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 341 case NeonTypeFlags::Int64: 342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 343 case NeonTypeFlags::Poly8: 344 return Context.SignedCharTy; 345 case NeonTypeFlags::Poly16: 346 return Context.ShortTy; 347 case NeonTypeFlags::Float16: 348 return Context.UnsignedShortTy; 349 case NeonTypeFlags::Float32: 350 return Context.FloatTy; 351 } 352 llvm_unreachable("Invalid NeonTypeFlag!"); 353} 354 355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 356 llvm::APSInt Result; 357 358 uint64_t mask = 0; 359 unsigned TV = 0; 360 int PtrArgNum = -1; 361 bool HasConstPtr = false; 362 switch (BuiltinID) { 363#define GET_NEON_OVERLOAD_CHECK 364#include "clang/Basic/arm_neon.inc" 365#undef GET_NEON_OVERLOAD_CHECK 366 } 367 368 // For NEON intrinsics which are overloaded on vector element type, validate 369 // the immediate which specifies which variant to emit. 370 unsigned ImmArg = TheCall->getNumArgs()-1; 371 if (mask) { 372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 373 return true; 374 375 TV = Result.getLimitedValue(64); 376 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 378 << TheCall->getArg(ImmArg)->getSourceRange(); 379 } 380 381 if (PtrArgNum >= 0) { 382 // Check that pointer arguments have the specified type. 383 Expr *Arg = TheCall->getArg(PtrArgNum); 384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 385 Arg = ICE->getSubExpr(); 386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 387 QualType RHSTy = RHS.get()->getType(); 388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 389 if (HasConstPtr) 390 EltTy = EltTy.withConst(); 391 QualType LHSTy = Context.getPointerType(EltTy); 392 AssignConvertType ConvTy; 393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 394 if (RHS.isInvalid()) 395 return true; 396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 397 RHS.get(), AA_Assigning)) 398 return true; 399 } 400 401 // For NEON intrinsics which take an immediate value as part of the 402 // instruction, range check them here. 403 unsigned i = 0, l = 0, u = 0; 404 switch (BuiltinID) { 405 default: return false; 406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 408 case ARM::BI__builtin_arm_vcvtr_f: 409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 410#define GET_NEON_IMMEDIATE_CHECK 411#include "clang/Basic/arm_neon.inc" 412#undef GET_NEON_IMMEDIATE_CHECK 413 }; 414 415 // We can't check the value of a dependent argument. 416 if (TheCall->getArg(i)->isTypeDependent() || 417 TheCall->getArg(i)->isValueDependent()) 418 return false; 419 420 // Check that the immediate argument is actually a constant. 421 if (SemaBuiltinConstantArg(TheCall, i, Result)) 422 return true; 423 424 // Range check against the upper/lower values for this isntruction. 425 unsigned Val = Result.getZExtValue(); 426 if (Val < l || Val > (u + l)) 427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 428 << l << u+l << TheCall->getArg(i)->getSourceRange(); 429 430 // FIXME: VFP Intrinsics should error if VFP not present. 431 return false; 432} 433 434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 435 unsigned i = 0, l = 0, u = 0; 436 switch (BuiltinID) { 437 default: return false; 438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 445 }; 446 447 // We can't check the value of a dependent argument. 448 if (TheCall->getArg(i)->isTypeDependent() || 449 TheCall->getArg(i)->isValueDependent()) 450 return false; 451 452 // Check that the immediate argument is actually a constant. 453 llvm::APSInt Result; 454 if (SemaBuiltinConstantArg(TheCall, i, Result)) 455 return true; 456 457 // Range check against the upper/lower values for this instruction. 458 unsigned Val = Result.getZExtValue(); 459 if (Val < l || Val > u) 460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 461 << l << u << TheCall->getArg(i)->getSourceRange(); 462 463 return false; 464} 465 466/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 467/// parameter with the FormatAttr's correct format_idx and firstDataArg. 468/// Returns true when the format fits the function and the FormatStringInfo has 469/// been populated. 470bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 471 FormatStringInfo *FSI) { 472 FSI->HasVAListArg = Format->getFirstArg() == 0; 473 FSI->FormatIdx = Format->getFormatIdx() - 1; 474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 475 476 // The way the format attribute works in GCC, the implicit this argument 477 // of member functions is counted. However, it doesn't appear in our own 478 // lists, so decrement format_idx in that case. 479 if (IsCXXMember) { 480 if(FSI->FormatIdx == 0) 481 return false; 482 --FSI->FormatIdx; 483 if (FSI->FirstDataArg != 0) 484 --FSI->FirstDataArg; 485 } 486 return true; 487} 488 489/// Handles the checks for format strings, non-POD arguments to vararg 490/// functions, and NULL arguments passed to non-NULL parameters. 491void Sema::checkCall(NamedDecl *FDecl, Expr **Args, 492 unsigned NumArgs, 493 unsigned NumProtoArgs, 494 bool IsMemberFunction, 495 SourceLocation Loc, 496 SourceRange Range, 497 VariadicCallType CallType) { 498 // FIXME: This mechanism should be abstracted to be less fragile and 499 // more efficient. For example, just map function ids to custom 500 // handlers. 501 502 // Printf and scanf checking. 503 bool HandledFormatString = false; 504 for (specific_attr_iterator<FormatAttr> 505 I = FDecl->specific_attr_begin<FormatAttr>(), 506 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I) 507 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType, 508 Loc, Range)) 509 HandledFormatString = true; 510 511 // Refuse POD arguments that weren't caught by the format string 512 // checks above. 513 if (!HandledFormatString && CallType != VariadicDoesNotApply) 514 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx) 515 variadicArgumentPODCheck(Args[ArgIdx], CallType); 516 517 for (specific_attr_iterator<NonNullAttr> 518 I = FDecl->specific_attr_begin<NonNullAttr>(), 519 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) 520 CheckNonNullArguments(*I, Args, Loc); 521 522 // Type safety checking. 523 for (specific_attr_iterator<ArgumentWithTypeTagAttr> 524 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(), 525 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) { 526 CheckArgumentWithTypeTag(*i, Args); 527 } 528} 529 530/// CheckConstructorCall - Check a constructor call for correctness and safety 531/// properties not enforced by the C type system. 532void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args, 533 unsigned NumArgs, 534 const FunctionProtoType *Proto, 535 SourceLocation Loc) { 536 VariadicCallType CallType = 537 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 538 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(), 539 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType); 540} 541 542/// CheckFunctionCall - Check a direct function call for various correctness 543/// and safety properties not strictly enforced by the C type system. 544bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 545 const FunctionProtoType *Proto) { 546 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall); 547 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 548 TheCall->getCallee()); 549 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0; 550 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs, 551 IsMemberFunction, TheCall->getRParenLoc(), 552 TheCall->getCallee()->getSourceRange(), CallType); 553 554 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 555 // None of the checks below are needed for functions that don't have 556 // simple names (e.g., C++ conversion functions). 557 if (!FnInfo) 558 return false; 559 560 unsigned CMId = FDecl->getMemoryFunctionKind(); 561 if (CMId == 0) 562 return false; 563 564 // Handle memory setting and copying functions. 565 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 566 CheckStrlcpycatArguments(TheCall, FnInfo); 567 else if (CMId == Builtin::BIstrncat) 568 CheckStrncatArguments(TheCall, FnInfo); 569 else 570 CheckMemaccessArguments(TheCall, CMId, FnInfo); 571 572 return false; 573} 574 575bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 576 Expr **Args, unsigned NumArgs) { 577 VariadicCallType CallType = 578 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 579 580 checkCall(Method, Args, NumArgs, Method->param_size(), 581 /*IsMemberFunction=*/false, 582 lbrac, Method->getSourceRange(), CallType); 583 584 return false; 585} 586 587bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall, 588 const FunctionProtoType *Proto) { 589 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 590 if (!V) 591 return false; 592 593 QualType Ty = V->getType(); 594 if (!Ty->isBlockPointerType()) 595 return false; 596 597 VariadicCallType CallType = 598 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ; 599 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0; 600 601 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(), 602 NumProtoArgs, /*IsMemberFunction=*/false, 603 TheCall->getRParenLoc(), 604 TheCall->getCallee()->getSourceRange(), CallType); 605 606 return false; 607} 608 609ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 610 AtomicExpr::AtomicOp Op) { 611 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 612 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 613 614 // All these operations take one of the following forms: 615 enum { 616 // C __c11_atomic_init(A *, C) 617 Init, 618 // C __c11_atomic_load(A *, int) 619 Load, 620 // void __atomic_load(A *, CP, int) 621 Copy, 622 // C __c11_atomic_add(A *, M, int) 623 Arithmetic, 624 // C __atomic_exchange_n(A *, CP, int) 625 Xchg, 626 // void __atomic_exchange(A *, C *, CP, int) 627 GNUXchg, 628 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 629 C11CmpXchg, 630 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 631 GNUCmpXchg 632 } Form = Init; 633 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 634 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 635 // where: 636 // C is an appropriate type, 637 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 638 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 639 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 640 // the int parameters are for orderings. 641 642 assert(AtomicExpr::AO__c11_atomic_init == 0 && 643 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 644 && "need to update code for modified C11 atomics"); 645 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 646 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 647 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 648 Op == AtomicExpr::AO__atomic_store_n || 649 Op == AtomicExpr::AO__atomic_exchange_n || 650 Op == AtomicExpr::AO__atomic_compare_exchange_n; 651 bool IsAddSub = false; 652 653 switch (Op) { 654 case AtomicExpr::AO__c11_atomic_init: 655 Form = Init; 656 break; 657 658 case AtomicExpr::AO__c11_atomic_load: 659 case AtomicExpr::AO__atomic_load_n: 660 Form = Load; 661 break; 662 663 case AtomicExpr::AO__c11_atomic_store: 664 case AtomicExpr::AO__atomic_load: 665 case AtomicExpr::AO__atomic_store: 666 case AtomicExpr::AO__atomic_store_n: 667 Form = Copy; 668 break; 669 670 case AtomicExpr::AO__c11_atomic_fetch_add: 671 case AtomicExpr::AO__c11_atomic_fetch_sub: 672 case AtomicExpr::AO__atomic_fetch_add: 673 case AtomicExpr::AO__atomic_fetch_sub: 674 case AtomicExpr::AO__atomic_add_fetch: 675 case AtomicExpr::AO__atomic_sub_fetch: 676 IsAddSub = true; 677 // Fall through. 678 case AtomicExpr::AO__c11_atomic_fetch_and: 679 case AtomicExpr::AO__c11_atomic_fetch_or: 680 case AtomicExpr::AO__c11_atomic_fetch_xor: 681 case AtomicExpr::AO__atomic_fetch_and: 682 case AtomicExpr::AO__atomic_fetch_or: 683 case AtomicExpr::AO__atomic_fetch_xor: 684 case AtomicExpr::AO__atomic_fetch_nand: 685 case AtomicExpr::AO__atomic_and_fetch: 686 case AtomicExpr::AO__atomic_or_fetch: 687 case AtomicExpr::AO__atomic_xor_fetch: 688 case AtomicExpr::AO__atomic_nand_fetch: 689 Form = Arithmetic; 690 break; 691 692 case AtomicExpr::AO__c11_atomic_exchange: 693 case AtomicExpr::AO__atomic_exchange_n: 694 Form = Xchg; 695 break; 696 697 case AtomicExpr::AO__atomic_exchange: 698 Form = GNUXchg; 699 break; 700 701 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 702 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 703 Form = C11CmpXchg; 704 break; 705 706 case AtomicExpr::AO__atomic_compare_exchange: 707 case AtomicExpr::AO__atomic_compare_exchange_n: 708 Form = GNUCmpXchg; 709 break; 710 } 711 712 // Check we have the right number of arguments. 713 if (TheCall->getNumArgs() < NumArgs[Form]) { 714 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 715 << 0 << NumArgs[Form] << TheCall->getNumArgs() 716 << TheCall->getCallee()->getSourceRange(); 717 return ExprError(); 718 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 719 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 720 diag::err_typecheck_call_too_many_args) 721 << 0 << NumArgs[Form] << TheCall->getNumArgs() 722 << TheCall->getCallee()->getSourceRange(); 723 return ExprError(); 724 } 725 726 // Inspect the first argument of the atomic operation. 727 Expr *Ptr = TheCall->getArg(0); 728 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 729 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 730 if (!pointerType) { 731 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 732 << Ptr->getType() << Ptr->getSourceRange(); 733 return ExprError(); 734 } 735 736 // For a __c11 builtin, this should be a pointer to an _Atomic type. 737 QualType AtomTy = pointerType->getPointeeType(); // 'A' 738 QualType ValType = AtomTy; // 'C' 739 if (IsC11) { 740 if (!AtomTy->isAtomicType()) { 741 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 742 << Ptr->getType() << Ptr->getSourceRange(); 743 return ExprError(); 744 } 745 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 746 } 747 748 // For an arithmetic operation, the implied arithmetic must be well-formed. 749 if (Form == Arithmetic) { 750 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 751 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 752 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 753 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 754 return ExprError(); 755 } 756 if (!IsAddSub && !ValType->isIntegerType()) { 757 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 758 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 759 return ExprError(); 760 } 761 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 762 // For __atomic_*_n operations, the value type must be a scalar integral or 763 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 764 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 765 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 766 return ExprError(); 767 } 768 769 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) { 770 // For GNU atomics, require a trivially-copyable type. This is not part of 771 // the GNU atomics specification, but we enforce it for sanity. 772 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 773 << Ptr->getType() << Ptr->getSourceRange(); 774 return ExprError(); 775 } 776 777 // FIXME: For any builtin other than a load, the ValType must not be 778 // const-qualified. 779 780 switch (ValType.getObjCLifetime()) { 781 case Qualifiers::OCL_None: 782 case Qualifiers::OCL_ExplicitNone: 783 // okay 784 break; 785 786 case Qualifiers::OCL_Weak: 787 case Qualifiers::OCL_Strong: 788 case Qualifiers::OCL_Autoreleasing: 789 // FIXME: Can this happen? By this point, ValType should be known 790 // to be trivially copyable. 791 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 792 << ValType << Ptr->getSourceRange(); 793 return ExprError(); 794 } 795 796 QualType ResultType = ValType; 797 if (Form == Copy || Form == GNUXchg || Form == Init) 798 ResultType = Context.VoidTy; 799 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 800 ResultType = Context.BoolTy; 801 802 // The type of a parameter passed 'by value'. In the GNU atomics, such 803 // arguments are actually passed as pointers. 804 QualType ByValType = ValType; // 'CP' 805 if (!IsC11 && !IsN) 806 ByValType = Ptr->getType(); 807 808 // The first argument --- the pointer --- has a fixed type; we 809 // deduce the types of the rest of the arguments accordingly. Walk 810 // the remaining arguments, converting them to the deduced value type. 811 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 812 QualType Ty; 813 if (i < NumVals[Form] + 1) { 814 switch (i) { 815 case 1: 816 // The second argument is the non-atomic operand. For arithmetic, this 817 // is always passed by value, and for a compare_exchange it is always 818 // passed by address. For the rest, GNU uses by-address and C11 uses 819 // by-value. 820 assert(Form != Load); 821 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 822 Ty = ValType; 823 else if (Form == Copy || Form == Xchg) 824 Ty = ByValType; 825 else if (Form == Arithmetic) 826 Ty = Context.getPointerDiffType(); 827 else 828 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 829 break; 830 case 2: 831 // The third argument to compare_exchange / GNU exchange is a 832 // (pointer to a) desired value. 833 Ty = ByValType; 834 break; 835 case 3: 836 // The fourth argument to GNU compare_exchange is a 'weak' flag. 837 Ty = Context.BoolTy; 838 break; 839 } 840 } else { 841 // The order(s) are always converted to int. 842 Ty = Context.IntTy; 843 } 844 845 InitializedEntity Entity = 846 InitializedEntity::InitializeParameter(Context, Ty, false); 847 ExprResult Arg = TheCall->getArg(i); 848 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 849 if (Arg.isInvalid()) 850 return true; 851 TheCall->setArg(i, Arg.get()); 852 } 853 854 // Permute the arguments into a 'consistent' order. 855 SmallVector<Expr*, 5> SubExprs; 856 SubExprs.push_back(Ptr); 857 switch (Form) { 858 case Init: 859 // Note, AtomicExpr::getVal1() has a special case for this atomic. 860 SubExprs.push_back(TheCall->getArg(1)); // Val1 861 break; 862 case Load: 863 SubExprs.push_back(TheCall->getArg(1)); // Order 864 break; 865 case Copy: 866 case Arithmetic: 867 case Xchg: 868 SubExprs.push_back(TheCall->getArg(2)); // Order 869 SubExprs.push_back(TheCall->getArg(1)); // Val1 870 break; 871 case GNUXchg: 872 // Note, AtomicExpr::getVal2() has a special case for this atomic. 873 SubExprs.push_back(TheCall->getArg(3)); // Order 874 SubExprs.push_back(TheCall->getArg(1)); // Val1 875 SubExprs.push_back(TheCall->getArg(2)); // Val2 876 break; 877 case C11CmpXchg: 878 SubExprs.push_back(TheCall->getArg(3)); // Order 879 SubExprs.push_back(TheCall->getArg(1)); // Val1 880 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 881 SubExprs.push_back(TheCall->getArg(2)); // Val2 882 break; 883 case GNUCmpXchg: 884 SubExprs.push_back(TheCall->getArg(4)); // Order 885 SubExprs.push_back(TheCall->getArg(1)); // Val1 886 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 887 SubExprs.push_back(TheCall->getArg(2)); // Val2 888 SubExprs.push_back(TheCall->getArg(3)); // Weak 889 break; 890 } 891 892 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 893 SubExprs, ResultType, Op, 894 TheCall->getRParenLoc())); 895} 896 897 898/// checkBuiltinArgument - Given a call to a builtin function, perform 899/// normal type-checking on the given argument, updating the call in 900/// place. This is useful when a builtin function requires custom 901/// type-checking for some of its arguments but not necessarily all of 902/// them. 903/// 904/// Returns true on error. 905static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 906 FunctionDecl *Fn = E->getDirectCallee(); 907 assert(Fn && "builtin call without direct callee!"); 908 909 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 910 InitializedEntity Entity = 911 InitializedEntity::InitializeParameter(S.Context, Param); 912 913 ExprResult Arg = E->getArg(0); 914 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 915 if (Arg.isInvalid()) 916 return true; 917 918 E->setArg(ArgIndex, Arg.take()); 919 return false; 920} 921 922/// SemaBuiltinAtomicOverloaded - We have a call to a function like 923/// __sync_fetch_and_add, which is an overloaded function based on the pointer 924/// type of its first argument. The main ActOnCallExpr routines have already 925/// promoted the types of arguments because all of these calls are prototyped as 926/// void(...). 927/// 928/// This function goes through and does final semantic checking for these 929/// builtins, 930ExprResult 931Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 932 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 933 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 934 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 935 936 // Ensure that we have at least one argument to do type inference from. 937 if (TheCall->getNumArgs() < 1) { 938 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 939 << 0 << 1 << TheCall->getNumArgs() 940 << TheCall->getCallee()->getSourceRange(); 941 return ExprError(); 942 } 943 944 // Inspect the first argument of the atomic builtin. This should always be 945 // a pointer type, whose element is an integral scalar or pointer type. 946 // Because it is a pointer type, we don't have to worry about any implicit 947 // casts here. 948 // FIXME: We don't allow floating point scalars as input. 949 Expr *FirstArg = TheCall->getArg(0); 950 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 951 if (FirstArgResult.isInvalid()) 952 return ExprError(); 953 FirstArg = FirstArgResult.take(); 954 TheCall->setArg(0, FirstArg); 955 956 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 957 if (!pointerType) { 958 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 959 << FirstArg->getType() << FirstArg->getSourceRange(); 960 return ExprError(); 961 } 962 963 QualType ValType = pointerType->getPointeeType(); 964 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 965 !ValType->isBlockPointerType()) { 966 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 967 << FirstArg->getType() << FirstArg->getSourceRange(); 968 return ExprError(); 969 } 970 971 switch (ValType.getObjCLifetime()) { 972 case Qualifiers::OCL_None: 973 case Qualifiers::OCL_ExplicitNone: 974 // okay 975 break; 976 977 case Qualifiers::OCL_Weak: 978 case Qualifiers::OCL_Strong: 979 case Qualifiers::OCL_Autoreleasing: 980 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 981 << ValType << FirstArg->getSourceRange(); 982 return ExprError(); 983 } 984 985 // Strip any qualifiers off ValType. 986 ValType = ValType.getUnqualifiedType(); 987 988 // The majority of builtins return a value, but a few have special return 989 // types, so allow them to override appropriately below. 990 QualType ResultType = ValType; 991 992 // We need to figure out which concrete builtin this maps onto. For example, 993 // __sync_fetch_and_add with a 2 byte object turns into 994 // __sync_fetch_and_add_2. 995#define BUILTIN_ROW(x) \ 996 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 997 Builtin::BI##x##_8, Builtin::BI##x##_16 } 998 999 static const unsigned BuiltinIndices[][5] = { 1000 BUILTIN_ROW(__sync_fetch_and_add), 1001 BUILTIN_ROW(__sync_fetch_and_sub), 1002 BUILTIN_ROW(__sync_fetch_and_or), 1003 BUILTIN_ROW(__sync_fetch_and_and), 1004 BUILTIN_ROW(__sync_fetch_and_xor), 1005 1006 BUILTIN_ROW(__sync_add_and_fetch), 1007 BUILTIN_ROW(__sync_sub_and_fetch), 1008 BUILTIN_ROW(__sync_and_and_fetch), 1009 BUILTIN_ROW(__sync_or_and_fetch), 1010 BUILTIN_ROW(__sync_xor_and_fetch), 1011 1012 BUILTIN_ROW(__sync_val_compare_and_swap), 1013 BUILTIN_ROW(__sync_bool_compare_and_swap), 1014 BUILTIN_ROW(__sync_lock_test_and_set), 1015 BUILTIN_ROW(__sync_lock_release), 1016 BUILTIN_ROW(__sync_swap) 1017 }; 1018#undef BUILTIN_ROW 1019 1020 // Determine the index of the size. 1021 unsigned SizeIndex; 1022 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 1023 case 1: SizeIndex = 0; break; 1024 case 2: SizeIndex = 1; break; 1025 case 4: SizeIndex = 2; break; 1026 case 8: SizeIndex = 3; break; 1027 case 16: SizeIndex = 4; break; 1028 default: 1029 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 1030 << FirstArg->getType() << FirstArg->getSourceRange(); 1031 return ExprError(); 1032 } 1033 1034 // Each of these builtins has one pointer argument, followed by some number of 1035 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 1036 // that we ignore. Find out which row of BuiltinIndices to read from as well 1037 // as the number of fixed args. 1038 unsigned BuiltinID = FDecl->getBuiltinID(); 1039 unsigned BuiltinIndex, NumFixed = 1; 1040 switch (BuiltinID) { 1041 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 1042 case Builtin::BI__sync_fetch_and_add: 1043 case Builtin::BI__sync_fetch_and_add_1: 1044 case Builtin::BI__sync_fetch_and_add_2: 1045 case Builtin::BI__sync_fetch_and_add_4: 1046 case Builtin::BI__sync_fetch_and_add_8: 1047 case Builtin::BI__sync_fetch_and_add_16: 1048 BuiltinIndex = 0; 1049 break; 1050 1051 case Builtin::BI__sync_fetch_and_sub: 1052 case Builtin::BI__sync_fetch_and_sub_1: 1053 case Builtin::BI__sync_fetch_and_sub_2: 1054 case Builtin::BI__sync_fetch_and_sub_4: 1055 case Builtin::BI__sync_fetch_and_sub_8: 1056 case Builtin::BI__sync_fetch_and_sub_16: 1057 BuiltinIndex = 1; 1058 break; 1059 1060 case Builtin::BI__sync_fetch_and_or: 1061 case Builtin::BI__sync_fetch_and_or_1: 1062 case Builtin::BI__sync_fetch_and_or_2: 1063 case Builtin::BI__sync_fetch_and_or_4: 1064 case Builtin::BI__sync_fetch_and_or_8: 1065 case Builtin::BI__sync_fetch_and_or_16: 1066 BuiltinIndex = 2; 1067 break; 1068 1069 case Builtin::BI__sync_fetch_and_and: 1070 case Builtin::BI__sync_fetch_and_and_1: 1071 case Builtin::BI__sync_fetch_and_and_2: 1072 case Builtin::BI__sync_fetch_and_and_4: 1073 case Builtin::BI__sync_fetch_and_and_8: 1074 case Builtin::BI__sync_fetch_and_and_16: 1075 BuiltinIndex = 3; 1076 break; 1077 1078 case Builtin::BI__sync_fetch_and_xor: 1079 case Builtin::BI__sync_fetch_and_xor_1: 1080 case Builtin::BI__sync_fetch_and_xor_2: 1081 case Builtin::BI__sync_fetch_and_xor_4: 1082 case Builtin::BI__sync_fetch_and_xor_8: 1083 case Builtin::BI__sync_fetch_and_xor_16: 1084 BuiltinIndex = 4; 1085 break; 1086 1087 case Builtin::BI__sync_add_and_fetch: 1088 case Builtin::BI__sync_add_and_fetch_1: 1089 case Builtin::BI__sync_add_and_fetch_2: 1090 case Builtin::BI__sync_add_and_fetch_4: 1091 case Builtin::BI__sync_add_and_fetch_8: 1092 case Builtin::BI__sync_add_and_fetch_16: 1093 BuiltinIndex = 5; 1094 break; 1095 1096 case Builtin::BI__sync_sub_and_fetch: 1097 case Builtin::BI__sync_sub_and_fetch_1: 1098 case Builtin::BI__sync_sub_and_fetch_2: 1099 case Builtin::BI__sync_sub_and_fetch_4: 1100 case Builtin::BI__sync_sub_and_fetch_8: 1101 case Builtin::BI__sync_sub_and_fetch_16: 1102 BuiltinIndex = 6; 1103 break; 1104 1105 case Builtin::BI__sync_and_and_fetch: 1106 case Builtin::BI__sync_and_and_fetch_1: 1107 case Builtin::BI__sync_and_and_fetch_2: 1108 case Builtin::BI__sync_and_and_fetch_4: 1109 case Builtin::BI__sync_and_and_fetch_8: 1110 case Builtin::BI__sync_and_and_fetch_16: 1111 BuiltinIndex = 7; 1112 break; 1113 1114 case Builtin::BI__sync_or_and_fetch: 1115 case Builtin::BI__sync_or_and_fetch_1: 1116 case Builtin::BI__sync_or_and_fetch_2: 1117 case Builtin::BI__sync_or_and_fetch_4: 1118 case Builtin::BI__sync_or_and_fetch_8: 1119 case Builtin::BI__sync_or_and_fetch_16: 1120 BuiltinIndex = 8; 1121 break; 1122 1123 case Builtin::BI__sync_xor_and_fetch: 1124 case Builtin::BI__sync_xor_and_fetch_1: 1125 case Builtin::BI__sync_xor_and_fetch_2: 1126 case Builtin::BI__sync_xor_and_fetch_4: 1127 case Builtin::BI__sync_xor_and_fetch_8: 1128 case Builtin::BI__sync_xor_and_fetch_16: 1129 BuiltinIndex = 9; 1130 break; 1131 1132 case Builtin::BI__sync_val_compare_and_swap: 1133 case Builtin::BI__sync_val_compare_and_swap_1: 1134 case Builtin::BI__sync_val_compare_and_swap_2: 1135 case Builtin::BI__sync_val_compare_and_swap_4: 1136 case Builtin::BI__sync_val_compare_and_swap_8: 1137 case Builtin::BI__sync_val_compare_and_swap_16: 1138 BuiltinIndex = 10; 1139 NumFixed = 2; 1140 break; 1141 1142 case Builtin::BI__sync_bool_compare_and_swap: 1143 case Builtin::BI__sync_bool_compare_and_swap_1: 1144 case Builtin::BI__sync_bool_compare_and_swap_2: 1145 case Builtin::BI__sync_bool_compare_and_swap_4: 1146 case Builtin::BI__sync_bool_compare_and_swap_8: 1147 case Builtin::BI__sync_bool_compare_and_swap_16: 1148 BuiltinIndex = 11; 1149 NumFixed = 2; 1150 ResultType = Context.BoolTy; 1151 break; 1152 1153 case Builtin::BI__sync_lock_test_and_set: 1154 case Builtin::BI__sync_lock_test_and_set_1: 1155 case Builtin::BI__sync_lock_test_and_set_2: 1156 case Builtin::BI__sync_lock_test_and_set_4: 1157 case Builtin::BI__sync_lock_test_and_set_8: 1158 case Builtin::BI__sync_lock_test_and_set_16: 1159 BuiltinIndex = 12; 1160 break; 1161 1162 case Builtin::BI__sync_lock_release: 1163 case Builtin::BI__sync_lock_release_1: 1164 case Builtin::BI__sync_lock_release_2: 1165 case Builtin::BI__sync_lock_release_4: 1166 case Builtin::BI__sync_lock_release_8: 1167 case Builtin::BI__sync_lock_release_16: 1168 BuiltinIndex = 13; 1169 NumFixed = 0; 1170 ResultType = Context.VoidTy; 1171 break; 1172 1173 case Builtin::BI__sync_swap: 1174 case Builtin::BI__sync_swap_1: 1175 case Builtin::BI__sync_swap_2: 1176 case Builtin::BI__sync_swap_4: 1177 case Builtin::BI__sync_swap_8: 1178 case Builtin::BI__sync_swap_16: 1179 BuiltinIndex = 14; 1180 break; 1181 } 1182 1183 // Now that we know how many fixed arguments we expect, first check that we 1184 // have at least that many. 1185 if (TheCall->getNumArgs() < 1+NumFixed) { 1186 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1187 << 0 << 1+NumFixed << TheCall->getNumArgs() 1188 << TheCall->getCallee()->getSourceRange(); 1189 return ExprError(); 1190 } 1191 1192 // Get the decl for the concrete builtin from this, we can tell what the 1193 // concrete integer type we should convert to is. 1194 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1195 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1196 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 1197 FunctionDecl *NewBuiltinDecl = 1198 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 1199 TUScope, false, DRE->getLocStart())); 1200 1201 // The first argument --- the pointer --- has a fixed type; we 1202 // deduce the types of the rest of the arguments accordingly. Walk 1203 // the remaining arguments, converting them to the deduced value type. 1204 for (unsigned i = 0; i != NumFixed; ++i) { 1205 ExprResult Arg = TheCall->getArg(i+1); 1206 1207 // GCC does an implicit conversion to the pointer or integer ValType. This 1208 // can fail in some cases (1i -> int**), check for this error case now. 1209 // Initialize the argument. 1210 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1211 ValType, /*consume*/ false); 1212 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1213 if (Arg.isInvalid()) 1214 return ExprError(); 1215 1216 // Okay, we have something that *can* be converted to the right type. Check 1217 // to see if there is a potentially weird extension going on here. This can 1218 // happen when you do an atomic operation on something like an char* and 1219 // pass in 42. The 42 gets converted to char. This is even more strange 1220 // for things like 45.123 -> char, etc. 1221 // FIXME: Do this check. 1222 TheCall->setArg(i+1, Arg.take()); 1223 } 1224 1225 ASTContext& Context = this->getASTContext(); 1226 1227 // Create a new DeclRefExpr to refer to the new decl. 1228 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1229 Context, 1230 DRE->getQualifierLoc(), 1231 SourceLocation(), 1232 NewBuiltinDecl, 1233 /*enclosing*/ false, 1234 DRE->getLocation(), 1235 NewBuiltinDecl->getType(), 1236 DRE->getValueKind()); 1237 1238 // Set the callee in the CallExpr. 1239 // FIXME: This leaks the original parens and implicit casts. 1240 ExprResult PromotedCall = UsualUnaryConversions(NewDRE); 1241 if (PromotedCall.isInvalid()) 1242 return ExprError(); 1243 TheCall->setCallee(PromotedCall.take()); 1244 1245 // Change the result type of the call to match the original value type. This 1246 // is arbitrary, but the codegen for these builtins ins design to handle it 1247 // gracefully. 1248 TheCall->setType(ResultType); 1249 1250 return TheCallResult; 1251} 1252 1253/// CheckObjCString - Checks that the argument to the builtin 1254/// CFString constructor is correct 1255/// Note: It might also make sense to do the UTF-16 conversion here (would 1256/// simplify the backend). 1257bool Sema::CheckObjCString(Expr *Arg) { 1258 Arg = Arg->IgnoreParenCasts(); 1259 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1260 1261 if (!Literal || !Literal->isAscii()) { 1262 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1263 << Arg->getSourceRange(); 1264 return true; 1265 } 1266 1267 if (Literal->containsNonAsciiOrNull()) { 1268 StringRef String = Literal->getString(); 1269 unsigned NumBytes = String.size(); 1270 SmallVector<UTF16, 128> ToBuf(NumBytes); 1271 const UTF8 *FromPtr = (UTF8 *)String.data(); 1272 UTF16 *ToPtr = &ToBuf[0]; 1273 1274 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1275 &ToPtr, ToPtr + NumBytes, 1276 strictConversion); 1277 // Check for conversion failure. 1278 if (Result != conversionOK) 1279 Diag(Arg->getLocStart(), 1280 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1281 } 1282 return false; 1283} 1284 1285/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1286/// Emit an error and return true on failure, return false on success. 1287bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1288 Expr *Fn = TheCall->getCallee(); 1289 if (TheCall->getNumArgs() > 2) { 1290 Diag(TheCall->getArg(2)->getLocStart(), 1291 diag::err_typecheck_call_too_many_args) 1292 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1293 << Fn->getSourceRange() 1294 << SourceRange(TheCall->getArg(2)->getLocStart(), 1295 (*(TheCall->arg_end()-1))->getLocEnd()); 1296 return true; 1297 } 1298 1299 if (TheCall->getNumArgs() < 2) { 1300 return Diag(TheCall->getLocEnd(), 1301 diag::err_typecheck_call_too_few_args_at_least) 1302 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1303 } 1304 1305 // Type-check the first argument normally. 1306 if (checkBuiltinArgument(*this, TheCall, 0)) 1307 return true; 1308 1309 // Determine whether the current function is variadic or not. 1310 BlockScopeInfo *CurBlock = getCurBlock(); 1311 bool isVariadic; 1312 if (CurBlock) 1313 isVariadic = CurBlock->TheDecl->isVariadic(); 1314 else if (FunctionDecl *FD = getCurFunctionDecl()) 1315 isVariadic = FD->isVariadic(); 1316 else 1317 isVariadic = getCurMethodDecl()->isVariadic(); 1318 1319 if (!isVariadic) { 1320 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1321 return true; 1322 } 1323 1324 // Verify that the second argument to the builtin is the last argument of the 1325 // current function or method. 1326 bool SecondArgIsLastNamedArgument = false; 1327 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1328 1329 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1330 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1331 // FIXME: This isn't correct for methods (results in bogus warning). 1332 // Get the last formal in the current function. 1333 const ParmVarDecl *LastArg; 1334 if (CurBlock) 1335 LastArg = *(CurBlock->TheDecl->param_end()-1); 1336 else if (FunctionDecl *FD = getCurFunctionDecl()) 1337 LastArg = *(FD->param_end()-1); 1338 else 1339 LastArg = *(getCurMethodDecl()->param_end()-1); 1340 SecondArgIsLastNamedArgument = PV == LastArg; 1341 } 1342 } 1343 1344 if (!SecondArgIsLastNamedArgument) 1345 Diag(TheCall->getArg(1)->getLocStart(), 1346 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1347 return false; 1348} 1349 1350/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1351/// friends. This is declared to take (...), so we have to check everything. 1352bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1353 if (TheCall->getNumArgs() < 2) 1354 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1355 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1356 if (TheCall->getNumArgs() > 2) 1357 return Diag(TheCall->getArg(2)->getLocStart(), 1358 diag::err_typecheck_call_too_many_args) 1359 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1360 << SourceRange(TheCall->getArg(2)->getLocStart(), 1361 (*(TheCall->arg_end()-1))->getLocEnd()); 1362 1363 ExprResult OrigArg0 = TheCall->getArg(0); 1364 ExprResult OrigArg1 = TheCall->getArg(1); 1365 1366 // Do standard promotions between the two arguments, returning their common 1367 // type. 1368 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1369 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1370 return true; 1371 1372 // Make sure any conversions are pushed back into the call; this is 1373 // type safe since unordered compare builtins are declared as "_Bool 1374 // foo(...)". 1375 TheCall->setArg(0, OrigArg0.get()); 1376 TheCall->setArg(1, OrigArg1.get()); 1377 1378 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1379 return false; 1380 1381 // If the common type isn't a real floating type, then the arguments were 1382 // invalid for this operation. 1383 if (Res.isNull() || !Res->isRealFloatingType()) 1384 return Diag(OrigArg0.get()->getLocStart(), 1385 diag::err_typecheck_call_invalid_ordered_compare) 1386 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1387 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1388 1389 return false; 1390} 1391 1392/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1393/// __builtin_isnan and friends. This is declared to take (...), so we have 1394/// to check everything. We expect the last argument to be a floating point 1395/// value. 1396bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1397 if (TheCall->getNumArgs() < NumArgs) 1398 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1399 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1400 if (TheCall->getNumArgs() > NumArgs) 1401 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1402 diag::err_typecheck_call_too_many_args) 1403 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1404 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1405 (*(TheCall->arg_end()-1))->getLocEnd()); 1406 1407 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1408 1409 if (OrigArg->isTypeDependent()) 1410 return false; 1411 1412 // This operation requires a non-_Complex floating-point number. 1413 if (!OrigArg->getType()->isRealFloatingType()) 1414 return Diag(OrigArg->getLocStart(), 1415 diag::err_typecheck_call_invalid_unary_fp) 1416 << OrigArg->getType() << OrigArg->getSourceRange(); 1417 1418 // If this is an implicit conversion from float -> double, remove it. 1419 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1420 Expr *CastArg = Cast->getSubExpr(); 1421 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1422 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1423 "promotion from float to double is the only expected cast here"); 1424 Cast->setSubExpr(0); 1425 TheCall->setArg(NumArgs-1, CastArg); 1426 } 1427 } 1428 1429 return false; 1430} 1431 1432/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1433// This is declared to take (...), so we have to check everything. 1434ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1435 if (TheCall->getNumArgs() < 2) 1436 return ExprError(Diag(TheCall->getLocEnd(), 1437 diag::err_typecheck_call_too_few_args_at_least) 1438 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1439 << TheCall->getSourceRange()); 1440 1441 // Determine which of the following types of shufflevector we're checking: 1442 // 1) unary, vector mask: (lhs, mask) 1443 // 2) binary, vector mask: (lhs, rhs, mask) 1444 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1445 QualType resType = TheCall->getArg(0)->getType(); 1446 unsigned numElements = 0; 1447 1448 if (!TheCall->getArg(0)->isTypeDependent() && 1449 !TheCall->getArg(1)->isTypeDependent()) { 1450 QualType LHSType = TheCall->getArg(0)->getType(); 1451 QualType RHSType = TheCall->getArg(1)->getType(); 1452 1453 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 1454 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 1455 << SourceRange(TheCall->getArg(0)->getLocStart(), 1456 TheCall->getArg(1)->getLocEnd()); 1457 return ExprError(); 1458 } 1459 1460 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1461 unsigned numResElements = TheCall->getNumArgs() - 2; 1462 1463 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1464 // with mask. If so, verify that RHS is an integer vector type with the 1465 // same number of elts as lhs. 1466 if (TheCall->getNumArgs() == 2) { 1467 if (!RHSType->hasIntegerRepresentation() || 1468 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1469 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1470 << SourceRange(TheCall->getArg(1)->getLocStart(), 1471 TheCall->getArg(1)->getLocEnd()); 1472 numResElements = numElements; 1473 } 1474 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1475 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1476 << SourceRange(TheCall->getArg(0)->getLocStart(), 1477 TheCall->getArg(1)->getLocEnd()); 1478 return ExprError(); 1479 } else if (numElements != numResElements) { 1480 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1481 resType = Context.getVectorType(eltType, numResElements, 1482 VectorType::GenericVector); 1483 } 1484 } 1485 1486 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1487 if (TheCall->getArg(i)->isTypeDependent() || 1488 TheCall->getArg(i)->isValueDependent()) 1489 continue; 1490 1491 llvm::APSInt Result(32); 1492 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1493 return ExprError(Diag(TheCall->getLocStart(), 1494 diag::err_shufflevector_nonconstant_argument) 1495 << TheCall->getArg(i)->getSourceRange()); 1496 1497 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1498 return ExprError(Diag(TheCall->getLocStart(), 1499 diag::err_shufflevector_argument_too_large) 1500 << TheCall->getArg(i)->getSourceRange()); 1501 } 1502 1503 SmallVector<Expr*, 32> exprs; 1504 1505 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1506 exprs.push_back(TheCall->getArg(i)); 1507 TheCall->setArg(i, 0); 1508 } 1509 1510 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType, 1511 TheCall->getCallee()->getLocStart(), 1512 TheCall->getRParenLoc())); 1513} 1514 1515/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1516// This is declared to take (const void*, ...) and can take two 1517// optional constant int args. 1518bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1519 unsigned NumArgs = TheCall->getNumArgs(); 1520 1521 if (NumArgs > 3) 1522 return Diag(TheCall->getLocEnd(), 1523 diag::err_typecheck_call_too_many_args_at_most) 1524 << 0 /*function call*/ << 3 << NumArgs 1525 << TheCall->getSourceRange(); 1526 1527 // Argument 0 is checked for us and the remaining arguments must be 1528 // constant integers. 1529 for (unsigned i = 1; i != NumArgs; ++i) { 1530 Expr *Arg = TheCall->getArg(i); 1531 1532 // We can't check the value of a dependent argument. 1533 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1534 continue; 1535 1536 llvm::APSInt Result; 1537 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1538 return true; 1539 1540 // FIXME: gcc issues a warning and rewrites these to 0. These 1541 // seems especially odd for the third argument since the default 1542 // is 3. 1543 if (i == 1) { 1544 if (Result.getLimitedValue() > 1) 1545 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1546 << "0" << "1" << Arg->getSourceRange(); 1547 } else { 1548 if (Result.getLimitedValue() > 3) 1549 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1550 << "0" << "3" << Arg->getSourceRange(); 1551 } 1552 } 1553 1554 return false; 1555} 1556 1557/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1558/// TheCall is a constant expression. 1559bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1560 llvm::APSInt &Result) { 1561 Expr *Arg = TheCall->getArg(ArgNum); 1562 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1563 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1564 1565 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1566 1567 if (!Arg->isIntegerConstantExpr(Result, Context)) 1568 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1569 << FDecl->getDeclName() << Arg->getSourceRange(); 1570 1571 return false; 1572} 1573 1574/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1575/// int type). This simply type checks that type is one of the defined 1576/// constants (0-3). 1577// For compatibility check 0-3, llvm only handles 0 and 2. 1578bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1579 llvm::APSInt Result; 1580 1581 // We can't check the value of a dependent argument. 1582 if (TheCall->getArg(1)->isTypeDependent() || 1583 TheCall->getArg(1)->isValueDependent()) 1584 return false; 1585 1586 // Check constant-ness first. 1587 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1588 return true; 1589 1590 Expr *Arg = TheCall->getArg(1); 1591 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1592 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1593 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1594 } 1595 1596 return false; 1597} 1598 1599/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1600/// This checks that val is a constant 1. 1601bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1602 Expr *Arg = TheCall->getArg(1); 1603 llvm::APSInt Result; 1604 1605 // TODO: This is less than ideal. Overload this to take a value. 1606 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1607 return true; 1608 1609 if (Result != 1) 1610 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1611 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1612 1613 return false; 1614} 1615 1616// Determine if an expression is a string literal or constant string. 1617// If this function returns false on the arguments to a function expecting a 1618// format string, we will usually need to emit a warning. 1619// True string literals are then checked by CheckFormatString. 1620Sema::StringLiteralCheckType 1621Sema::checkFormatStringExpr(const Expr *E, Expr **Args, 1622 unsigned NumArgs, bool HasVAListArg, 1623 unsigned format_idx, unsigned firstDataArg, 1624 FormatStringType Type, VariadicCallType CallType, 1625 bool inFunctionCall) { 1626 tryAgain: 1627 if (E->isTypeDependent() || E->isValueDependent()) 1628 return SLCT_NotALiteral; 1629 1630 E = E->IgnoreParenCasts(); 1631 1632 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 1633 // Technically -Wformat-nonliteral does not warn about this case. 1634 // The behavior of printf and friends in this case is implementation 1635 // dependent. Ideally if the format string cannot be null then 1636 // it should have a 'nonnull' attribute in the function prototype. 1637 return SLCT_CheckedLiteral; 1638 1639 switch (E->getStmtClass()) { 1640 case Stmt::BinaryConditionalOperatorClass: 1641 case Stmt::ConditionalOperatorClass: { 1642 // The expression is a literal if both sub-expressions were, and it was 1643 // completely checked only if both sub-expressions were checked. 1644 const AbstractConditionalOperator *C = 1645 cast<AbstractConditionalOperator>(E); 1646 StringLiteralCheckType Left = 1647 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs, 1648 HasVAListArg, format_idx, firstDataArg, 1649 Type, CallType, inFunctionCall); 1650 if (Left == SLCT_NotALiteral) 1651 return SLCT_NotALiteral; 1652 StringLiteralCheckType Right = 1653 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs, 1654 HasVAListArg, format_idx, firstDataArg, 1655 Type, CallType, inFunctionCall); 1656 return Left < Right ? Left : Right; 1657 } 1658 1659 case Stmt::ImplicitCastExprClass: { 1660 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1661 goto tryAgain; 1662 } 1663 1664 case Stmt::OpaqueValueExprClass: 1665 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1666 E = src; 1667 goto tryAgain; 1668 } 1669 return SLCT_NotALiteral; 1670 1671 case Stmt::PredefinedExprClass: 1672 // While __func__, etc., are technically not string literals, they 1673 // cannot contain format specifiers and thus are not a security 1674 // liability. 1675 return SLCT_UncheckedLiteral; 1676 1677 case Stmt::DeclRefExprClass: { 1678 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1679 1680 // As an exception, do not flag errors for variables binding to 1681 // const string literals. 1682 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1683 bool isConstant = false; 1684 QualType T = DR->getType(); 1685 1686 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1687 isConstant = AT->getElementType().isConstant(Context); 1688 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1689 isConstant = T.isConstant(Context) && 1690 PT->getPointeeType().isConstant(Context); 1691 } else if (T->isObjCObjectPointerType()) { 1692 // In ObjC, there is usually no "const ObjectPointer" type, 1693 // so don't check if the pointee type is constant. 1694 isConstant = T.isConstant(Context); 1695 } 1696 1697 if (isConstant) { 1698 if (const Expr *Init = VD->getAnyInitializer()) { 1699 // Look through initializers like const char c[] = { "foo" } 1700 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 1701 if (InitList->isStringLiteralInit()) 1702 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 1703 } 1704 return checkFormatStringExpr(Init, Args, NumArgs, 1705 HasVAListArg, format_idx, 1706 firstDataArg, Type, CallType, 1707 /*inFunctionCall*/false); 1708 } 1709 } 1710 1711 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1712 // special check to see if the format string is a function parameter 1713 // of the function calling the printf function. If the function 1714 // has an attribute indicating it is a printf-like function, then we 1715 // should suppress warnings concerning non-literals being used in a call 1716 // to a vprintf function. For example: 1717 // 1718 // void 1719 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1720 // va_list ap; 1721 // va_start(ap, fmt); 1722 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1723 // ... 1724 // 1725 if (HasVAListArg) { 1726 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 1727 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 1728 int PVIndex = PV->getFunctionScopeIndex() + 1; 1729 for (specific_attr_iterator<FormatAttr> 1730 i = ND->specific_attr_begin<FormatAttr>(), 1731 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) { 1732 FormatAttr *PVFormat = *i; 1733 // adjust for implicit parameter 1734 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1735 if (MD->isInstance()) 1736 ++PVIndex; 1737 // We also check if the formats are compatible. 1738 // We can't pass a 'scanf' string to a 'printf' function. 1739 if (PVIndex == PVFormat->getFormatIdx() && 1740 Type == GetFormatStringType(PVFormat)) 1741 return SLCT_UncheckedLiteral; 1742 } 1743 } 1744 } 1745 } 1746 } 1747 1748 return SLCT_NotALiteral; 1749 } 1750 1751 case Stmt::CallExprClass: 1752 case Stmt::CXXMemberCallExprClass: { 1753 const CallExpr *CE = cast<CallExpr>(E); 1754 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 1755 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 1756 unsigned ArgIndex = FA->getFormatIdx(); 1757 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1758 if (MD->isInstance()) 1759 --ArgIndex; 1760 const Expr *Arg = CE->getArg(ArgIndex - 1); 1761 1762 return checkFormatStringExpr(Arg, Args, NumArgs, 1763 HasVAListArg, format_idx, firstDataArg, 1764 Type, CallType, inFunctionCall); 1765 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 1766 unsigned BuiltinID = FD->getBuiltinID(); 1767 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 1768 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 1769 const Expr *Arg = CE->getArg(0); 1770 return checkFormatStringExpr(Arg, Args, NumArgs, 1771 HasVAListArg, format_idx, 1772 firstDataArg, Type, CallType, 1773 inFunctionCall); 1774 } 1775 } 1776 } 1777 1778 return SLCT_NotALiteral; 1779 } 1780 case Stmt::ObjCStringLiteralClass: 1781 case Stmt::StringLiteralClass: { 1782 const StringLiteral *StrE = NULL; 1783 1784 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1785 StrE = ObjCFExpr->getString(); 1786 else 1787 StrE = cast<StringLiteral>(E); 1788 1789 if (StrE) { 1790 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx, 1791 firstDataArg, Type, inFunctionCall, CallType); 1792 return SLCT_CheckedLiteral; 1793 } 1794 1795 return SLCT_NotALiteral; 1796 } 1797 1798 default: 1799 return SLCT_NotALiteral; 1800 } 1801} 1802 1803void 1804Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1805 const Expr * const *ExprArgs, 1806 SourceLocation CallSiteLoc) { 1807 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1808 e = NonNull->args_end(); 1809 i != e; ++i) { 1810 const Expr *ArgExpr = ExprArgs[*i]; 1811 if (ArgExpr->isNullPointerConstant(Context, 1812 Expr::NPC_ValueDependentIsNotNull)) 1813 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1814 } 1815} 1816 1817Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 1818 return llvm::StringSwitch<FormatStringType>(Format->getType()) 1819 .Case("scanf", FST_Scanf) 1820 .Cases("printf", "printf0", FST_Printf) 1821 .Cases("NSString", "CFString", FST_NSString) 1822 .Case("strftime", FST_Strftime) 1823 .Case("strfmon", FST_Strfmon) 1824 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 1825 .Default(FST_Unknown); 1826} 1827 1828/// CheckFormatArguments - Check calls to printf and scanf (and similar 1829/// functions) for correct use of format strings. 1830/// Returns true if a format string has been fully checked. 1831bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args, 1832 unsigned NumArgs, bool IsCXXMember, 1833 VariadicCallType CallType, 1834 SourceLocation Loc, SourceRange Range) { 1835 FormatStringInfo FSI; 1836 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 1837 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx, 1838 FSI.FirstDataArg, GetFormatStringType(Format), 1839 CallType, Loc, Range); 1840 return false; 1841} 1842 1843bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs, 1844 bool HasVAListArg, unsigned format_idx, 1845 unsigned firstDataArg, FormatStringType Type, 1846 VariadicCallType CallType, 1847 SourceLocation Loc, SourceRange Range) { 1848 // CHECK: printf/scanf-like function is called with no format string. 1849 if (format_idx >= NumArgs) { 1850 Diag(Loc, diag::warn_missing_format_string) << Range; 1851 return false; 1852 } 1853 1854 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 1855 1856 // CHECK: format string is not a string literal. 1857 // 1858 // Dynamically generated format strings are difficult to 1859 // automatically vet at compile time. Requiring that format strings 1860 // are string literals: (1) permits the checking of format strings by 1861 // the compiler and thereby (2) can practically remove the source of 1862 // many format string exploits. 1863 1864 // Format string can be either ObjC string (e.g. @"%d") or 1865 // C string (e.g. "%d") 1866 // ObjC string uses the same format specifiers as C string, so we can use 1867 // the same format string checking logic for both ObjC and C strings. 1868 StringLiteralCheckType CT = 1869 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg, 1870 format_idx, firstDataArg, Type, CallType); 1871 if (CT != SLCT_NotALiteral) 1872 // Literal format string found, check done! 1873 return CT == SLCT_CheckedLiteral; 1874 1875 // Strftime is particular as it always uses a single 'time' argument, 1876 // so it is safe to pass a non-literal string. 1877 if (Type == FST_Strftime) 1878 return false; 1879 1880 // Do not emit diag when the string param is a macro expansion and the 1881 // format is either NSString or CFString. This is a hack to prevent 1882 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 1883 // which are usually used in place of NS and CF string literals. 1884 if (Type == FST_NSString && 1885 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 1886 return false; 1887 1888 // If there are no arguments specified, warn with -Wformat-security, otherwise 1889 // warn only with -Wformat-nonliteral. 1890 if (NumArgs == format_idx+1) 1891 Diag(Args[format_idx]->getLocStart(), 1892 diag::warn_format_nonliteral_noargs) 1893 << OrigFormatExpr->getSourceRange(); 1894 else 1895 Diag(Args[format_idx]->getLocStart(), 1896 diag::warn_format_nonliteral) 1897 << OrigFormatExpr->getSourceRange(); 1898 return false; 1899} 1900 1901namespace { 1902class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1903protected: 1904 Sema &S; 1905 const StringLiteral *FExpr; 1906 const Expr *OrigFormatExpr; 1907 const unsigned FirstDataArg; 1908 const unsigned NumDataArgs; 1909 const char *Beg; // Start of format string. 1910 const bool HasVAListArg; 1911 const Expr * const *Args; 1912 const unsigned NumArgs; 1913 unsigned FormatIdx; 1914 llvm::BitVector CoveredArgs; 1915 bool usesPositionalArgs; 1916 bool atFirstArg; 1917 bool inFunctionCall; 1918 Sema::VariadicCallType CallType; 1919public: 1920 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1921 const Expr *origFormatExpr, unsigned firstDataArg, 1922 unsigned numDataArgs, const char *beg, bool hasVAListArg, 1923 Expr **args, unsigned numArgs, 1924 unsigned formatIdx, bool inFunctionCall, 1925 Sema::VariadicCallType callType) 1926 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1927 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 1928 Beg(beg), HasVAListArg(hasVAListArg), 1929 Args(args), NumArgs(numArgs), FormatIdx(formatIdx), 1930 usesPositionalArgs(false), atFirstArg(true), 1931 inFunctionCall(inFunctionCall), CallType(callType) { 1932 CoveredArgs.resize(numDataArgs); 1933 CoveredArgs.reset(); 1934 } 1935 1936 void DoneProcessing(); 1937 1938 void HandleIncompleteSpecifier(const char *startSpecifier, 1939 unsigned specifierLen); 1940 1941 void HandleNonStandardLengthModifier( 1942 const analyze_format_string::LengthModifier &LM, 1943 const char *startSpecifier, unsigned specifierLen); 1944 1945 void HandleNonStandardConversionSpecifier( 1946 const analyze_format_string::ConversionSpecifier &CS, 1947 const char *startSpecifier, unsigned specifierLen); 1948 1949 void HandleNonStandardConversionSpecification( 1950 const analyze_format_string::LengthModifier &LM, 1951 const analyze_format_string::ConversionSpecifier &CS, 1952 const char *startSpecifier, unsigned specifierLen); 1953 1954 virtual void HandlePosition(const char *startPos, unsigned posLen); 1955 1956 virtual void HandleInvalidPosition(const char *startSpecifier, 1957 unsigned specifierLen, 1958 analyze_format_string::PositionContext p); 1959 1960 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1961 1962 void HandleNullChar(const char *nullCharacter); 1963 1964 template <typename Range> 1965 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1966 const Expr *ArgumentExpr, 1967 PartialDiagnostic PDiag, 1968 SourceLocation StringLoc, 1969 bool IsStringLocation, Range StringRange, 1970 FixItHint Fixit = FixItHint()); 1971 1972protected: 1973 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1974 const char *startSpec, 1975 unsigned specifierLen, 1976 const char *csStart, unsigned csLen); 1977 1978 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 1979 const char *startSpec, 1980 unsigned specifierLen); 1981 1982 SourceRange getFormatStringRange(); 1983 CharSourceRange getSpecifierRange(const char *startSpecifier, 1984 unsigned specifierLen); 1985 SourceLocation getLocationOfByte(const char *x); 1986 1987 const Expr *getDataArg(unsigned i) const; 1988 1989 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1990 const analyze_format_string::ConversionSpecifier &CS, 1991 const char *startSpecifier, unsigned specifierLen, 1992 unsigned argIndex); 1993 1994 template <typename Range> 1995 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 1996 bool IsStringLocation, Range StringRange, 1997 FixItHint Fixit = FixItHint()); 1998 1999 void CheckPositionalAndNonpositionalArgs( 2000 const analyze_format_string::FormatSpecifier *FS); 2001}; 2002} 2003 2004SourceRange CheckFormatHandler::getFormatStringRange() { 2005 return OrigFormatExpr->getSourceRange(); 2006} 2007 2008CharSourceRange CheckFormatHandler:: 2009getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 2010 SourceLocation Start = getLocationOfByte(startSpecifier); 2011 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 2012 2013 // Advance the end SourceLocation by one due to half-open ranges. 2014 End = End.getLocWithOffset(1); 2015 2016 return CharSourceRange::getCharRange(Start, End); 2017} 2018 2019SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 2020 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 2021} 2022 2023void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 2024 unsigned specifierLen){ 2025 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 2026 getLocationOfByte(startSpecifier), 2027 /*IsStringLocation*/true, 2028 getSpecifierRange(startSpecifier, specifierLen)); 2029} 2030 2031void CheckFormatHandler::HandleNonStandardLengthModifier( 2032 const analyze_format_string::LengthModifier &LM, 2033 const char *startSpecifier, unsigned specifierLen) { 2034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString() 2035 << 0, 2036 getLocationOfByte(LM.getStart()), 2037 /*IsStringLocation*/true, 2038 getSpecifierRange(startSpecifier, specifierLen)); 2039} 2040 2041void CheckFormatHandler::HandleNonStandardConversionSpecifier( 2042 const analyze_format_string::ConversionSpecifier &CS, 2043 const char *startSpecifier, unsigned specifierLen) { 2044 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString() 2045 << 1, 2046 getLocationOfByte(CS.getStart()), 2047 /*IsStringLocation*/true, 2048 getSpecifierRange(startSpecifier, specifierLen)); 2049} 2050 2051void CheckFormatHandler::HandleNonStandardConversionSpecification( 2052 const analyze_format_string::LengthModifier &LM, 2053 const analyze_format_string::ConversionSpecifier &CS, 2054 const char *startSpecifier, unsigned specifierLen) { 2055 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec) 2056 << LM.toString() << CS.toString(), 2057 getLocationOfByte(LM.getStart()), 2058 /*IsStringLocation*/true, 2059 getSpecifierRange(startSpecifier, specifierLen)); 2060} 2061 2062void CheckFormatHandler::HandlePosition(const char *startPos, 2063 unsigned posLen) { 2064 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 2065 getLocationOfByte(startPos), 2066 /*IsStringLocation*/true, 2067 getSpecifierRange(startPos, posLen)); 2068} 2069 2070void 2071CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 2072 analyze_format_string::PositionContext p) { 2073 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 2074 << (unsigned) p, 2075 getLocationOfByte(startPos), /*IsStringLocation*/true, 2076 getSpecifierRange(startPos, posLen)); 2077} 2078 2079void CheckFormatHandler::HandleZeroPosition(const char *startPos, 2080 unsigned posLen) { 2081 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 2082 getLocationOfByte(startPos), 2083 /*IsStringLocation*/true, 2084 getSpecifierRange(startPos, posLen)); 2085} 2086 2087void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 2088 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 2089 // The presence of a null character is likely an error. 2090 EmitFormatDiagnostic( 2091 S.PDiag(diag::warn_printf_format_string_contains_null_char), 2092 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 2093 getFormatStringRange()); 2094 } 2095} 2096 2097// Note that this may return NULL if there was an error parsing or building 2098// one of the argument expressions. 2099const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 2100 return Args[FirstDataArg + i]; 2101} 2102 2103void CheckFormatHandler::DoneProcessing() { 2104 // Does the number of data arguments exceed the number of 2105 // format conversions in the format string? 2106 if (!HasVAListArg) { 2107 // Find any arguments that weren't covered. 2108 CoveredArgs.flip(); 2109 signed notCoveredArg = CoveredArgs.find_first(); 2110 if (notCoveredArg >= 0) { 2111 assert((unsigned)notCoveredArg < NumDataArgs); 2112 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) { 2113 SourceLocation Loc = E->getLocStart(); 2114 if (!S.getSourceManager().isInSystemMacro(Loc)) { 2115 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 2116 Loc, /*IsStringLocation*/false, 2117 getFormatStringRange()); 2118 } 2119 } 2120 } 2121 } 2122} 2123 2124bool 2125CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 2126 SourceLocation Loc, 2127 const char *startSpec, 2128 unsigned specifierLen, 2129 const char *csStart, 2130 unsigned csLen) { 2131 2132 bool keepGoing = true; 2133 if (argIndex < NumDataArgs) { 2134 // Consider the argument coverered, even though the specifier doesn't 2135 // make sense. 2136 CoveredArgs.set(argIndex); 2137 } 2138 else { 2139 // If argIndex exceeds the number of data arguments we 2140 // don't issue a warning because that is just a cascade of warnings (and 2141 // they may have intended '%%' anyway). We don't want to continue processing 2142 // the format string after this point, however, as we will like just get 2143 // gibberish when trying to match arguments. 2144 keepGoing = false; 2145 } 2146 2147 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2148 << StringRef(csStart, csLen), 2149 Loc, /*IsStringLocation*/true, 2150 getSpecifierRange(startSpec, specifierLen)); 2151 2152 return keepGoing; 2153} 2154 2155void 2156CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2157 const char *startSpec, 2158 unsigned specifierLen) { 2159 EmitFormatDiagnostic( 2160 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2161 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2162} 2163 2164bool 2165CheckFormatHandler::CheckNumArgs( 2166 const analyze_format_string::FormatSpecifier &FS, 2167 const analyze_format_string::ConversionSpecifier &CS, 2168 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2169 2170 if (argIndex >= NumDataArgs) { 2171 PartialDiagnostic PDiag = FS.usesPositionalArg() 2172 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2173 << (argIndex+1) << NumDataArgs) 2174 : S.PDiag(diag::warn_printf_insufficient_data_args); 2175 EmitFormatDiagnostic( 2176 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2177 getSpecifierRange(startSpecifier, specifierLen)); 2178 return false; 2179 } 2180 return true; 2181} 2182 2183template<typename Range> 2184void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2185 SourceLocation Loc, 2186 bool IsStringLocation, 2187 Range StringRange, 2188 FixItHint FixIt) { 2189 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2190 Loc, IsStringLocation, StringRange, FixIt); 2191} 2192 2193/// \brief If the format string is not within the funcion call, emit a note 2194/// so that the function call and string are in diagnostic messages. 2195/// 2196/// \param InFunctionCall if true, the format string is within the function 2197/// call and only one diagnostic message will be produced. Otherwise, an 2198/// extra note will be emitted pointing to location of the format string. 2199/// 2200/// \param ArgumentExpr the expression that is passed as the format string 2201/// argument in the function call. Used for getting locations when two 2202/// diagnostics are emitted. 2203/// 2204/// \param PDiag the callee should already have provided any strings for the 2205/// diagnostic message. This function only adds locations and fixits 2206/// to diagnostics. 2207/// 2208/// \param Loc primary location for diagnostic. If two diagnostics are 2209/// required, one will be at Loc and a new SourceLocation will be created for 2210/// the other one. 2211/// 2212/// \param IsStringLocation if true, Loc points to the format string should be 2213/// used for the note. Otherwise, Loc points to the argument list and will 2214/// be used with PDiag. 2215/// 2216/// \param StringRange some or all of the string to highlight. This is 2217/// templated so it can accept either a CharSourceRange or a SourceRange. 2218/// 2219/// \param FixIt optional fix it hint for the format string. 2220template<typename Range> 2221void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2222 const Expr *ArgumentExpr, 2223 PartialDiagnostic PDiag, 2224 SourceLocation Loc, 2225 bool IsStringLocation, 2226 Range StringRange, 2227 FixItHint FixIt) { 2228 if (InFunctionCall) 2229 S.Diag(Loc, PDiag) << StringRange << FixIt; 2230 else { 2231 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2232 << ArgumentExpr->getSourceRange(); 2233 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2234 diag::note_format_string_defined) 2235 << StringRange << FixIt; 2236 } 2237} 2238 2239//===--- CHECK: Printf format string checking ------------------------------===// 2240 2241namespace { 2242class CheckPrintfHandler : public CheckFormatHandler { 2243 bool ObjCContext; 2244public: 2245 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2246 const Expr *origFormatExpr, unsigned firstDataArg, 2247 unsigned numDataArgs, bool isObjC, 2248 const char *beg, bool hasVAListArg, 2249 Expr **Args, unsigned NumArgs, 2250 unsigned formatIdx, bool inFunctionCall, 2251 Sema::VariadicCallType CallType) 2252 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2253 numDataArgs, beg, hasVAListArg, Args, NumArgs, 2254 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC) 2255 {} 2256 2257 2258 bool HandleInvalidPrintfConversionSpecifier( 2259 const analyze_printf::PrintfSpecifier &FS, 2260 const char *startSpecifier, 2261 unsigned specifierLen); 2262 2263 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2264 const char *startSpecifier, 2265 unsigned specifierLen); 2266 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 2267 const char *StartSpecifier, 2268 unsigned SpecifierLen, 2269 const Expr *E); 2270 2271 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2272 const char *startSpecifier, unsigned specifierLen); 2273 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2274 const analyze_printf::OptionalAmount &Amt, 2275 unsigned type, 2276 const char *startSpecifier, unsigned specifierLen); 2277 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2278 const analyze_printf::OptionalFlag &flag, 2279 const char *startSpecifier, unsigned specifierLen); 2280 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2281 const analyze_printf::OptionalFlag &ignoredFlag, 2282 const analyze_printf::OptionalFlag &flag, 2283 const char *startSpecifier, unsigned specifierLen); 2284 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 2285 const Expr *E, const CharSourceRange &CSR); 2286 2287}; 2288} 2289 2290bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2291 const analyze_printf::PrintfSpecifier &FS, 2292 const char *startSpecifier, 2293 unsigned specifierLen) { 2294 const analyze_printf::PrintfConversionSpecifier &CS = 2295 FS.getConversionSpecifier(); 2296 2297 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2298 getLocationOfByte(CS.getStart()), 2299 startSpecifier, specifierLen, 2300 CS.getStart(), CS.getLength()); 2301} 2302 2303bool CheckPrintfHandler::HandleAmount( 2304 const analyze_format_string::OptionalAmount &Amt, 2305 unsigned k, const char *startSpecifier, 2306 unsigned specifierLen) { 2307 2308 if (Amt.hasDataArgument()) { 2309 if (!HasVAListArg) { 2310 unsigned argIndex = Amt.getArgIndex(); 2311 if (argIndex >= NumDataArgs) { 2312 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2313 << k, 2314 getLocationOfByte(Amt.getStart()), 2315 /*IsStringLocation*/true, 2316 getSpecifierRange(startSpecifier, specifierLen)); 2317 // Don't do any more checking. We will just emit 2318 // spurious errors. 2319 return false; 2320 } 2321 2322 // Type check the data argument. It should be an 'int'. 2323 // Although not in conformance with C99, we also allow the argument to be 2324 // an 'unsigned int' as that is a reasonably safe case. GCC also 2325 // doesn't emit a warning for that case. 2326 CoveredArgs.set(argIndex); 2327 const Expr *Arg = getDataArg(argIndex); 2328 if (!Arg) 2329 return false; 2330 2331 QualType T = Arg->getType(); 2332 2333 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 2334 assert(AT.isValid()); 2335 2336 if (!AT.matchesType(S.Context, T)) { 2337 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2338 << k << AT.getRepresentativeTypeName(S.Context) 2339 << T << Arg->getSourceRange(), 2340 getLocationOfByte(Amt.getStart()), 2341 /*IsStringLocation*/true, 2342 getSpecifierRange(startSpecifier, specifierLen)); 2343 // Don't do any more checking. We will just emit 2344 // spurious errors. 2345 return false; 2346 } 2347 } 2348 } 2349 return true; 2350} 2351 2352void CheckPrintfHandler::HandleInvalidAmount( 2353 const analyze_printf::PrintfSpecifier &FS, 2354 const analyze_printf::OptionalAmount &Amt, 2355 unsigned type, 2356 const char *startSpecifier, 2357 unsigned specifierLen) { 2358 const analyze_printf::PrintfConversionSpecifier &CS = 2359 FS.getConversionSpecifier(); 2360 2361 FixItHint fixit = 2362 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2363 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2364 Amt.getConstantLength())) 2365 : FixItHint(); 2366 2367 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2368 << type << CS.toString(), 2369 getLocationOfByte(Amt.getStart()), 2370 /*IsStringLocation*/true, 2371 getSpecifierRange(startSpecifier, specifierLen), 2372 fixit); 2373} 2374 2375void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2376 const analyze_printf::OptionalFlag &flag, 2377 const char *startSpecifier, 2378 unsigned specifierLen) { 2379 // Warn about pointless flag with a fixit removal. 2380 const analyze_printf::PrintfConversionSpecifier &CS = 2381 FS.getConversionSpecifier(); 2382 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2383 << flag.toString() << CS.toString(), 2384 getLocationOfByte(flag.getPosition()), 2385 /*IsStringLocation*/true, 2386 getSpecifierRange(startSpecifier, specifierLen), 2387 FixItHint::CreateRemoval( 2388 getSpecifierRange(flag.getPosition(), 1))); 2389} 2390 2391void CheckPrintfHandler::HandleIgnoredFlag( 2392 const analyze_printf::PrintfSpecifier &FS, 2393 const analyze_printf::OptionalFlag &ignoredFlag, 2394 const analyze_printf::OptionalFlag &flag, 2395 const char *startSpecifier, 2396 unsigned specifierLen) { 2397 // Warn about ignored flag with a fixit removal. 2398 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2399 << ignoredFlag.toString() << flag.toString(), 2400 getLocationOfByte(ignoredFlag.getPosition()), 2401 /*IsStringLocation*/true, 2402 getSpecifierRange(startSpecifier, specifierLen), 2403 FixItHint::CreateRemoval( 2404 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2405} 2406 2407// Determines if the specified is a C++ class or struct containing 2408// a member with the specified name and kind (e.g. a CXXMethodDecl named 2409// "c_str()"). 2410template<typename MemberKind> 2411static llvm::SmallPtrSet<MemberKind*, 1> 2412CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 2413 const RecordType *RT = Ty->getAs<RecordType>(); 2414 llvm::SmallPtrSet<MemberKind*, 1> Results; 2415 2416 if (!RT) 2417 return Results; 2418 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 2419 if (!RD) 2420 return Results; 2421 2422 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(), 2423 Sema::LookupMemberName); 2424 2425 // We just need to include all members of the right kind turned up by the 2426 // filter, at this point. 2427 if (S.LookupQualifiedName(R, RT->getDecl())) 2428 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2429 NamedDecl *decl = (*I)->getUnderlyingDecl(); 2430 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 2431 Results.insert(FK); 2432 } 2433 return Results; 2434} 2435 2436// Check if a (w)string was passed when a (w)char* was needed, and offer a 2437// better diagnostic if so. AT is assumed to be valid. 2438// Returns true when a c_str() conversion method is found. 2439bool CheckPrintfHandler::checkForCStrMembers( 2440 const analyze_printf::ArgType &AT, const Expr *E, 2441 const CharSourceRange &CSR) { 2442 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 2443 2444 MethodSet Results = 2445 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 2446 2447 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 2448 MI != ME; ++MI) { 2449 const CXXMethodDecl *Method = *MI; 2450 if (Method->getNumParams() == 0 && 2451 AT.matchesType(S.Context, Method->getResultType())) { 2452 // FIXME: Suggest parens if the expression needs them. 2453 SourceLocation EndLoc = 2454 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()); 2455 S.Diag(E->getLocStart(), diag::note_printf_c_str) 2456 << "c_str()" 2457 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 2458 return true; 2459 } 2460 } 2461 2462 return false; 2463} 2464 2465bool 2466CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2467 &FS, 2468 const char *startSpecifier, 2469 unsigned specifierLen) { 2470 2471 using namespace analyze_format_string; 2472 using namespace analyze_printf; 2473 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2474 2475 if (FS.consumesDataArgument()) { 2476 if (atFirstArg) { 2477 atFirstArg = false; 2478 usesPositionalArgs = FS.usesPositionalArg(); 2479 } 2480 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2481 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2482 startSpecifier, specifierLen); 2483 return false; 2484 } 2485 } 2486 2487 // First check if the field width, precision, and conversion specifier 2488 // have matching data arguments. 2489 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2490 startSpecifier, specifierLen)) { 2491 return false; 2492 } 2493 2494 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2495 startSpecifier, specifierLen)) { 2496 return false; 2497 } 2498 2499 if (!CS.consumesDataArgument()) { 2500 // FIXME: Technically specifying a precision or field width here 2501 // makes no sense. Worth issuing a warning at some point. 2502 return true; 2503 } 2504 2505 // Consume the argument. 2506 unsigned argIndex = FS.getArgIndex(); 2507 if (argIndex < NumDataArgs) { 2508 // The check to see if the argIndex is valid will come later. 2509 // We set the bit here because we may exit early from this 2510 // function if we encounter some other error. 2511 CoveredArgs.set(argIndex); 2512 } 2513 2514 // Check for using an Objective-C specific conversion specifier 2515 // in a non-ObjC literal. 2516 if (!ObjCContext && CS.isObjCArg()) { 2517 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2518 specifierLen); 2519 } 2520 2521 // Check for invalid use of field width 2522 if (!FS.hasValidFieldWidth()) { 2523 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2524 startSpecifier, specifierLen); 2525 } 2526 2527 // Check for invalid use of precision 2528 if (!FS.hasValidPrecision()) { 2529 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2530 startSpecifier, specifierLen); 2531 } 2532 2533 // Check each flag does not conflict with any other component. 2534 if (!FS.hasValidThousandsGroupingPrefix()) 2535 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2536 if (!FS.hasValidLeadingZeros()) 2537 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2538 if (!FS.hasValidPlusPrefix()) 2539 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2540 if (!FS.hasValidSpacePrefix()) 2541 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2542 if (!FS.hasValidAlternativeForm()) 2543 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2544 if (!FS.hasValidLeftJustified()) 2545 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2546 2547 // Check that flags are not ignored by another flag 2548 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2549 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2550 startSpecifier, specifierLen); 2551 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2552 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2553 startSpecifier, specifierLen); 2554 2555 // Check the length modifier is valid with the given conversion specifier. 2556 const LengthModifier &LM = FS.getLengthModifier(); 2557 if (!FS.hasValidLengthModifier()) 2558 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2559 << LM.toString() << CS.toString(), 2560 getLocationOfByte(LM.getStart()), 2561 /*IsStringLocation*/true, 2562 getSpecifierRange(startSpecifier, specifierLen), 2563 FixItHint::CreateRemoval( 2564 getSpecifierRange(LM.getStart(), 2565 LM.getLength()))); 2566 if (!FS.hasStandardLengthModifier()) 2567 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2568 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2569 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2570 if (!FS.hasStandardLengthConversionCombination()) 2571 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2572 specifierLen); 2573 2574 // The remaining checks depend on the data arguments. 2575 if (HasVAListArg) 2576 return true; 2577 2578 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2579 return false; 2580 2581 const Expr *Arg = getDataArg(argIndex); 2582 if (!Arg) 2583 return true; 2584 2585 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 2586} 2587 2588bool 2589CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 2590 const char *StartSpecifier, 2591 unsigned SpecifierLen, 2592 const Expr *E) { 2593 using namespace analyze_format_string; 2594 using namespace analyze_printf; 2595 // Now type check the data expression that matches the 2596 // format specifier. 2597 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 2598 ObjCContext); 2599 if (AT.isValid() && !AT.matchesType(S.Context, E->getType())) { 2600 // Look through argument promotions for our error message's reported type. 2601 // This includes the integral and floating promotions, but excludes array 2602 // and function pointer decay; seeing that an argument intended to be a 2603 // string has type 'char [6]' is probably more confusing than 'char *'. 2604 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2605 if (ICE->getCastKind() == CK_IntegralCast || 2606 ICE->getCastKind() == CK_FloatingCast) { 2607 E = ICE->getSubExpr(); 2608 2609 // Check if we didn't match because of an implicit cast from a 'char' 2610 // or 'short' to an 'int'. This is done because printf is a varargs 2611 // function. 2612 if (ICE->getType() == S.Context.IntTy || 2613 ICE->getType() == S.Context.UnsignedIntTy) { 2614 // All further checking is done on the subexpression. 2615 if (AT.matchesType(S.Context, E->getType())) 2616 return true; 2617 } 2618 } 2619 } 2620 2621 // We may be able to offer a FixItHint if it is a supported type. 2622 PrintfSpecifier fixedFS = FS; 2623 bool success = fixedFS.fixType(E->getType(), S.getLangOpts(), 2624 S.Context, ObjCContext); 2625 2626 if (success) { 2627 // Get the fix string from the fixed format specifier 2628 SmallString<16> buf; 2629 llvm::raw_svector_ostream os(buf); 2630 fixedFS.toString(os); 2631 2632 EmitFormatDiagnostic( 2633 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2634 << AT.getRepresentativeTypeName(S.Context) << E->getType() 2635 << E->getSourceRange(), 2636 E->getLocStart(), 2637 /*IsStringLocation*/false, 2638 getSpecifierRange(StartSpecifier, SpecifierLen), 2639 FixItHint::CreateReplacement( 2640 getSpecifierRange(StartSpecifier, SpecifierLen), 2641 os.str())); 2642 } else { 2643 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 2644 SpecifierLen); 2645 // Since the warning for passing non-POD types to variadic functions 2646 // was deferred until now, we emit a warning for non-POD 2647 // arguments here. 2648 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) { 2649 unsigned DiagKind; 2650 if (E->getType()->isObjCObjectType()) 2651 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format; 2652 else 2653 DiagKind = diag::warn_non_pod_vararg_with_format_string; 2654 2655 EmitFormatDiagnostic( 2656 S.PDiag(DiagKind) 2657 << S.getLangOpts().CPlusPlus0x 2658 << E->getType() 2659 << CallType 2660 << AT.getRepresentativeTypeName(S.Context) 2661 << CSR 2662 << E->getSourceRange(), 2663 E->getLocStart(), /*IsStringLocation*/false, CSR); 2664 2665 checkForCStrMembers(AT, E, CSR); 2666 } else 2667 EmitFormatDiagnostic( 2668 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2669 << AT.getRepresentativeTypeName(S.Context) << E->getType() 2670 << CSR 2671 << E->getSourceRange(), 2672 E->getLocStart(), /*IsStringLocation*/false, CSR); 2673 } 2674 } 2675 2676 return true; 2677} 2678 2679//===--- CHECK: Scanf format string checking ------------------------------===// 2680 2681namespace { 2682class CheckScanfHandler : public CheckFormatHandler { 2683public: 2684 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2685 const Expr *origFormatExpr, unsigned firstDataArg, 2686 unsigned numDataArgs, const char *beg, bool hasVAListArg, 2687 Expr **Args, unsigned NumArgs, 2688 unsigned formatIdx, bool inFunctionCall, 2689 Sema::VariadicCallType CallType) 2690 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2691 numDataArgs, beg, hasVAListArg, 2692 Args, NumArgs, formatIdx, inFunctionCall, CallType) 2693 {} 2694 2695 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2696 const char *startSpecifier, 2697 unsigned specifierLen); 2698 2699 bool HandleInvalidScanfConversionSpecifier( 2700 const analyze_scanf::ScanfSpecifier &FS, 2701 const char *startSpecifier, 2702 unsigned specifierLen); 2703 2704 void HandleIncompleteScanList(const char *start, const char *end); 2705}; 2706} 2707 2708void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2709 const char *end) { 2710 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2711 getLocationOfByte(end), /*IsStringLocation*/true, 2712 getSpecifierRange(start, end - start)); 2713} 2714 2715bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2716 const analyze_scanf::ScanfSpecifier &FS, 2717 const char *startSpecifier, 2718 unsigned specifierLen) { 2719 2720 const analyze_scanf::ScanfConversionSpecifier &CS = 2721 FS.getConversionSpecifier(); 2722 2723 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2724 getLocationOfByte(CS.getStart()), 2725 startSpecifier, specifierLen, 2726 CS.getStart(), CS.getLength()); 2727} 2728 2729bool CheckScanfHandler::HandleScanfSpecifier( 2730 const analyze_scanf::ScanfSpecifier &FS, 2731 const char *startSpecifier, 2732 unsigned specifierLen) { 2733 2734 using namespace analyze_scanf; 2735 using namespace analyze_format_string; 2736 2737 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2738 2739 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2740 // be used to decide if we are using positional arguments consistently. 2741 if (FS.consumesDataArgument()) { 2742 if (atFirstArg) { 2743 atFirstArg = false; 2744 usesPositionalArgs = FS.usesPositionalArg(); 2745 } 2746 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2747 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2748 startSpecifier, specifierLen); 2749 return false; 2750 } 2751 } 2752 2753 // Check if the field with is non-zero. 2754 const OptionalAmount &Amt = FS.getFieldWidth(); 2755 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2756 if (Amt.getConstantAmount() == 0) { 2757 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2758 Amt.getConstantLength()); 2759 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2760 getLocationOfByte(Amt.getStart()), 2761 /*IsStringLocation*/true, R, 2762 FixItHint::CreateRemoval(R)); 2763 } 2764 } 2765 2766 if (!FS.consumesDataArgument()) { 2767 // FIXME: Technically specifying a precision or field width here 2768 // makes no sense. Worth issuing a warning at some point. 2769 return true; 2770 } 2771 2772 // Consume the argument. 2773 unsigned argIndex = FS.getArgIndex(); 2774 if (argIndex < NumDataArgs) { 2775 // The check to see if the argIndex is valid will come later. 2776 // We set the bit here because we may exit early from this 2777 // function if we encounter some other error. 2778 CoveredArgs.set(argIndex); 2779 } 2780 2781 // Check the length modifier is valid with the given conversion specifier. 2782 const LengthModifier &LM = FS.getLengthModifier(); 2783 if (!FS.hasValidLengthModifier()) { 2784 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength()); 2785 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2786 << LM.toString() << CS.toString() 2787 << getSpecifierRange(startSpecifier, specifierLen), 2788 getLocationOfByte(LM.getStart()), 2789 /*IsStringLocation*/true, R, 2790 FixItHint::CreateRemoval(R)); 2791 } 2792 2793 if (!FS.hasStandardLengthModifier()) 2794 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2795 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2796 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2797 if (!FS.hasStandardLengthConversionCombination()) 2798 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2799 specifierLen); 2800 2801 // The remaining checks depend on the data arguments. 2802 if (HasVAListArg) 2803 return true; 2804 2805 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2806 return false; 2807 2808 // Check that the argument type matches the format specifier. 2809 const Expr *Ex = getDataArg(argIndex); 2810 if (!Ex) 2811 return true; 2812 2813 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 2814 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) { 2815 ScanfSpecifier fixedFS = FS; 2816 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2817 S.Context); 2818 2819 if (success) { 2820 // Get the fix string from the fixed format specifier. 2821 SmallString<128> buf; 2822 llvm::raw_svector_ostream os(buf); 2823 fixedFS.toString(os); 2824 2825 EmitFormatDiagnostic( 2826 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2827 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 2828 << Ex->getSourceRange(), 2829 Ex->getLocStart(), 2830 /*IsStringLocation*/false, 2831 getSpecifierRange(startSpecifier, specifierLen), 2832 FixItHint::CreateReplacement( 2833 getSpecifierRange(startSpecifier, specifierLen), 2834 os.str())); 2835 } else { 2836 EmitFormatDiagnostic( 2837 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2838 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 2839 << Ex->getSourceRange(), 2840 Ex->getLocStart(), 2841 /*IsStringLocation*/false, 2842 getSpecifierRange(startSpecifier, specifierLen)); 2843 } 2844 } 2845 2846 return true; 2847} 2848 2849void Sema::CheckFormatString(const StringLiteral *FExpr, 2850 const Expr *OrigFormatExpr, 2851 Expr **Args, unsigned NumArgs, 2852 bool HasVAListArg, unsigned format_idx, 2853 unsigned firstDataArg, FormatStringType Type, 2854 bool inFunctionCall, VariadicCallType CallType) { 2855 2856 // CHECK: is the format string a wide literal? 2857 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 2858 CheckFormatHandler::EmitFormatDiagnostic( 2859 *this, inFunctionCall, Args[format_idx], 2860 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 2861 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2862 return; 2863 } 2864 2865 // Str - The format string. NOTE: this is NOT null-terminated! 2866 StringRef StrRef = FExpr->getString(); 2867 const char *Str = StrRef.data(); 2868 unsigned StrLen = StrRef.size(); 2869 const unsigned numDataArgs = NumArgs - firstDataArg; 2870 2871 // CHECK: empty format string? 2872 if (StrLen == 0 && numDataArgs > 0) { 2873 CheckFormatHandler::EmitFormatDiagnostic( 2874 *this, inFunctionCall, Args[format_idx], 2875 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 2876 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2877 return; 2878 } 2879 2880 if (Type == FST_Printf || Type == FST_NSString) { 2881 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2882 numDataArgs, (Type == FST_NSString), 2883 Str, HasVAListArg, Args, NumArgs, format_idx, 2884 inFunctionCall, CallType); 2885 2886 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 2887 getLangOpts())) 2888 H.DoneProcessing(); 2889 } else if (Type == FST_Scanf) { 2890 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 2891 Str, HasVAListArg, Args, NumArgs, format_idx, 2892 inFunctionCall, CallType); 2893 2894 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 2895 getLangOpts())) 2896 H.DoneProcessing(); 2897 } // TODO: handle other formats 2898} 2899 2900//===--- CHECK: Standard memory functions ---------------------------------===// 2901 2902/// \brief Determine whether the given type is a dynamic class type (e.g., 2903/// whether it has a vtable). 2904static bool isDynamicClassType(QualType T) { 2905 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 2906 if (CXXRecordDecl *Definition = Record->getDefinition()) 2907 if (Definition->isDynamicClass()) 2908 return true; 2909 2910 return false; 2911} 2912 2913/// \brief If E is a sizeof expression, returns its argument expression, 2914/// otherwise returns NULL. 2915static const Expr *getSizeOfExprArg(const Expr* E) { 2916 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2917 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2918 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 2919 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 2920 2921 return 0; 2922} 2923 2924/// \brief If E is a sizeof expression, returns its argument type. 2925static QualType getSizeOfArgType(const Expr* E) { 2926 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2927 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2928 if (SizeOf->getKind() == clang::UETT_SizeOf) 2929 return SizeOf->getTypeOfArgument(); 2930 2931 return QualType(); 2932} 2933 2934/// \brief Check for dangerous or invalid arguments to memset(). 2935/// 2936/// This issues warnings on known problematic, dangerous or unspecified 2937/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2938/// function calls. 2939/// 2940/// \param Call The call expression to diagnose. 2941void Sema::CheckMemaccessArguments(const CallExpr *Call, 2942 unsigned BId, 2943 IdentifierInfo *FnName) { 2944 assert(BId != 0); 2945 2946 // It is possible to have a non-standard definition of memset. Validate 2947 // we have enough arguments, and if not, abort further checking. 2948 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 2949 if (Call->getNumArgs() < ExpectedNumArgs) 2950 return; 2951 2952 unsigned LastArg = (BId == Builtin::BImemset || 2953 BId == Builtin::BIstrndup ? 1 : 2); 2954 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 2955 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 2956 2957 // We have special checking when the length is a sizeof expression. 2958 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 2959 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 2960 llvm::FoldingSetNodeID SizeOfArgID; 2961 2962 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 2963 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 2964 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 2965 2966 QualType DestTy = Dest->getType(); 2967 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 2968 QualType PointeeTy = DestPtrTy->getPointeeType(); 2969 2970 // Never warn about void type pointers. This can be used to suppress 2971 // false positives. 2972 if (PointeeTy->isVoidType()) 2973 continue; 2974 2975 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 2976 // actually comparing the expressions for equality. Because computing the 2977 // expression IDs can be expensive, we only do this if the diagnostic is 2978 // enabled. 2979 if (SizeOfArg && 2980 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 2981 SizeOfArg->getExprLoc())) { 2982 // We only compute IDs for expressions if the warning is enabled, and 2983 // cache the sizeof arg's ID. 2984 if (SizeOfArgID == llvm::FoldingSetNodeID()) 2985 SizeOfArg->Profile(SizeOfArgID, Context, true); 2986 llvm::FoldingSetNodeID DestID; 2987 Dest->Profile(DestID, Context, true); 2988 if (DestID == SizeOfArgID) { 2989 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 2990 // over sizeof(src) as well. 2991 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 2992 StringRef ReadableName = FnName->getName(); 2993 2994 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 2995 if (UnaryOp->getOpcode() == UO_AddrOf) 2996 ActionIdx = 1; // If its an address-of operator, just remove it. 2997 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 2998 ActionIdx = 2; // If the pointee's size is sizeof(char), 2999 // suggest an explicit length. 3000 3001 // If the function is defined as a builtin macro, do not show macro 3002 // expansion. 3003 SourceLocation SL = SizeOfArg->getExprLoc(); 3004 SourceRange DSR = Dest->getSourceRange(); 3005 SourceRange SSR = SizeOfArg->getSourceRange(); 3006 SourceManager &SM = PP.getSourceManager(); 3007 3008 if (SM.isMacroArgExpansion(SL)) { 3009 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 3010 SL = SM.getSpellingLoc(SL); 3011 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 3012 SM.getSpellingLoc(DSR.getEnd())); 3013 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 3014 SM.getSpellingLoc(SSR.getEnd())); 3015 } 3016 3017 DiagRuntimeBehavior(SL, SizeOfArg, 3018 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 3019 << ReadableName 3020 << PointeeTy 3021 << DestTy 3022 << DSR 3023 << SSR); 3024 DiagRuntimeBehavior(SL, SizeOfArg, 3025 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 3026 << ActionIdx 3027 << SSR); 3028 3029 break; 3030 } 3031 } 3032 3033 // Also check for cases where the sizeof argument is the exact same 3034 // type as the memory argument, and where it points to a user-defined 3035 // record type. 3036 if (SizeOfArgTy != QualType()) { 3037 if (PointeeTy->isRecordType() && 3038 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 3039 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 3040 PDiag(diag::warn_sizeof_pointer_type_memaccess) 3041 << FnName << SizeOfArgTy << ArgIdx 3042 << PointeeTy << Dest->getSourceRange() 3043 << LenExpr->getSourceRange()); 3044 break; 3045 } 3046 } 3047 3048 // Always complain about dynamic classes. 3049 if (isDynamicClassType(PointeeTy)) { 3050 3051 unsigned OperationType = 0; 3052 // "overwritten" if we're warning about the destination for any call 3053 // but memcmp; otherwise a verb appropriate to the call. 3054 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 3055 if (BId == Builtin::BImemcpy) 3056 OperationType = 1; 3057 else if(BId == Builtin::BImemmove) 3058 OperationType = 2; 3059 else if (BId == Builtin::BImemcmp) 3060 OperationType = 3; 3061 } 3062 3063 DiagRuntimeBehavior( 3064 Dest->getExprLoc(), Dest, 3065 PDiag(diag::warn_dyn_class_memaccess) 3066 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 3067 << FnName << PointeeTy 3068 << OperationType 3069 << Call->getCallee()->getSourceRange()); 3070 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 3071 BId != Builtin::BImemset) 3072 DiagRuntimeBehavior( 3073 Dest->getExprLoc(), Dest, 3074 PDiag(diag::warn_arc_object_memaccess) 3075 << ArgIdx << FnName << PointeeTy 3076 << Call->getCallee()->getSourceRange()); 3077 else 3078 continue; 3079 3080 DiagRuntimeBehavior( 3081 Dest->getExprLoc(), Dest, 3082 PDiag(diag::note_bad_memaccess_silence) 3083 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 3084 break; 3085 } 3086 } 3087} 3088 3089// A little helper routine: ignore addition and subtraction of integer literals. 3090// This intentionally does not ignore all integer constant expressions because 3091// we don't want to remove sizeof(). 3092static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 3093 Ex = Ex->IgnoreParenCasts(); 3094 3095 for (;;) { 3096 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 3097 if (!BO || !BO->isAdditiveOp()) 3098 break; 3099 3100 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 3101 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 3102 3103 if (isa<IntegerLiteral>(RHS)) 3104 Ex = LHS; 3105 else if (isa<IntegerLiteral>(LHS)) 3106 Ex = RHS; 3107 else 3108 break; 3109 } 3110 3111 return Ex; 3112} 3113 3114static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 3115 ASTContext &Context) { 3116 // Only handle constant-sized or VLAs, but not flexible members. 3117 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 3118 // Only issue the FIXIT for arrays of size > 1. 3119 if (CAT->getSize().getSExtValue() <= 1) 3120 return false; 3121 } else if (!Ty->isVariableArrayType()) { 3122 return false; 3123 } 3124 return true; 3125} 3126 3127// Warn if the user has made the 'size' argument to strlcpy or strlcat 3128// be the size of the source, instead of the destination. 3129void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 3130 IdentifierInfo *FnName) { 3131 3132 // Don't crash if the user has the wrong number of arguments 3133 if (Call->getNumArgs() != 3) 3134 return; 3135 3136 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 3137 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 3138 const Expr *CompareWithSrc = NULL; 3139 3140 // Look for 'strlcpy(dst, x, sizeof(x))' 3141 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 3142 CompareWithSrc = Ex; 3143 else { 3144 // Look for 'strlcpy(dst, x, strlen(x))' 3145 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 3146 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 3147 && SizeCall->getNumArgs() == 1) 3148 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 3149 } 3150 } 3151 3152 if (!CompareWithSrc) 3153 return; 3154 3155 // Determine if the argument to sizeof/strlen is equal to the source 3156 // argument. In principle there's all kinds of things you could do 3157 // here, for instance creating an == expression and evaluating it with 3158 // EvaluateAsBooleanCondition, but this uses a more direct technique: 3159 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 3160 if (!SrcArgDRE) 3161 return; 3162 3163 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 3164 if (!CompareWithSrcDRE || 3165 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 3166 return; 3167 3168 const Expr *OriginalSizeArg = Call->getArg(2); 3169 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 3170 << OriginalSizeArg->getSourceRange() << FnName; 3171 3172 // Output a FIXIT hint if the destination is an array (rather than a 3173 // pointer to an array). This could be enhanced to handle some 3174 // pointers if we know the actual size, like if DstArg is 'array+2' 3175 // we could say 'sizeof(array)-2'. 3176 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 3177 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 3178 return; 3179 3180 SmallString<128> sizeString; 3181 llvm::raw_svector_ostream OS(sizeString); 3182 OS << "sizeof("; 3183 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3184 OS << ")"; 3185 3186 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 3187 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 3188 OS.str()); 3189} 3190 3191/// Check if two expressions refer to the same declaration. 3192static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 3193 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 3194 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 3195 return D1->getDecl() == D2->getDecl(); 3196 return false; 3197} 3198 3199static const Expr *getStrlenExprArg(const Expr *E) { 3200 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 3201 const FunctionDecl *FD = CE->getDirectCallee(); 3202 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 3203 return 0; 3204 return CE->getArg(0)->IgnoreParenCasts(); 3205 } 3206 return 0; 3207} 3208 3209// Warn on anti-patterns as the 'size' argument to strncat. 3210// The correct size argument should look like following: 3211// strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 3212void Sema::CheckStrncatArguments(const CallExpr *CE, 3213 IdentifierInfo *FnName) { 3214 // Don't crash if the user has the wrong number of arguments. 3215 if (CE->getNumArgs() < 3) 3216 return; 3217 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 3218 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 3219 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 3220 3221 // Identify common expressions, which are wrongly used as the size argument 3222 // to strncat and may lead to buffer overflows. 3223 unsigned PatternType = 0; 3224 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 3225 // - sizeof(dst) 3226 if (referToTheSameDecl(SizeOfArg, DstArg)) 3227 PatternType = 1; 3228 // - sizeof(src) 3229 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 3230 PatternType = 2; 3231 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 3232 if (BE->getOpcode() == BO_Sub) { 3233 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 3234 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 3235 // - sizeof(dst) - strlen(dst) 3236 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 3237 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 3238 PatternType = 1; 3239 // - sizeof(src) - (anything) 3240 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 3241 PatternType = 2; 3242 } 3243 } 3244 3245 if (PatternType == 0) 3246 return; 3247 3248 // Generate the diagnostic. 3249 SourceLocation SL = LenArg->getLocStart(); 3250 SourceRange SR = LenArg->getSourceRange(); 3251 SourceManager &SM = PP.getSourceManager(); 3252 3253 // If the function is defined as a builtin macro, do not show macro expansion. 3254 if (SM.isMacroArgExpansion(SL)) { 3255 SL = SM.getSpellingLoc(SL); 3256 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 3257 SM.getSpellingLoc(SR.getEnd())); 3258 } 3259 3260 // Check if the destination is an array (rather than a pointer to an array). 3261 QualType DstTy = DstArg->getType(); 3262 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 3263 Context); 3264 if (!isKnownSizeArray) { 3265 if (PatternType == 1) 3266 Diag(SL, diag::warn_strncat_wrong_size) << SR; 3267 else 3268 Diag(SL, diag::warn_strncat_src_size) << SR; 3269 return; 3270 } 3271 3272 if (PatternType == 1) 3273 Diag(SL, diag::warn_strncat_large_size) << SR; 3274 else 3275 Diag(SL, diag::warn_strncat_src_size) << SR; 3276 3277 SmallString<128> sizeString; 3278 llvm::raw_svector_ostream OS(sizeString); 3279 OS << "sizeof("; 3280 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3281 OS << ") - "; 3282 OS << "strlen("; 3283 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3284 OS << ") - 1"; 3285 3286 Diag(SL, diag::note_strncat_wrong_size) 3287 << FixItHint::CreateReplacement(SR, OS.str()); 3288} 3289 3290//===--- CHECK: Return Address of Stack Variable --------------------------===// 3291 3292static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3293 Decl *ParentDecl); 3294static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 3295 Decl *ParentDecl); 3296 3297/// CheckReturnStackAddr - Check if a return statement returns the address 3298/// of a stack variable. 3299void 3300Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 3301 SourceLocation ReturnLoc) { 3302 3303 Expr *stackE = 0; 3304 SmallVector<DeclRefExpr *, 8> refVars; 3305 3306 // Perform checking for returned stack addresses, local blocks, 3307 // label addresses or references to temporaries. 3308 if (lhsType->isPointerType() || 3309 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 3310 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0); 3311 } else if (lhsType->isReferenceType()) { 3312 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0); 3313 } 3314 3315 if (stackE == 0) 3316 return; // Nothing suspicious was found. 3317 3318 SourceLocation diagLoc; 3319 SourceRange diagRange; 3320 if (refVars.empty()) { 3321 diagLoc = stackE->getLocStart(); 3322 diagRange = stackE->getSourceRange(); 3323 } else { 3324 // We followed through a reference variable. 'stackE' contains the 3325 // problematic expression but we will warn at the return statement pointing 3326 // at the reference variable. We will later display the "trail" of 3327 // reference variables using notes. 3328 diagLoc = refVars[0]->getLocStart(); 3329 diagRange = refVars[0]->getSourceRange(); 3330 } 3331 3332 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 3333 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 3334 : diag::warn_ret_stack_addr) 3335 << DR->getDecl()->getDeclName() << diagRange; 3336 } else if (isa<BlockExpr>(stackE)) { // local block. 3337 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 3338 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 3339 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 3340 } else { // local temporary. 3341 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 3342 : diag::warn_ret_local_temp_addr) 3343 << diagRange; 3344 } 3345 3346 // Display the "trail" of reference variables that we followed until we 3347 // found the problematic expression using notes. 3348 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 3349 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 3350 // If this var binds to another reference var, show the range of the next 3351 // var, otherwise the var binds to the problematic expression, in which case 3352 // show the range of the expression. 3353 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 3354 : stackE->getSourceRange(); 3355 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 3356 << VD->getDeclName() << range; 3357 } 3358} 3359 3360/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 3361/// check if the expression in a return statement evaluates to an address 3362/// to a location on the stack, a local block, an address of a label, or a 3363/// reference to local temporary. The recursion is used to traverse the 3364/// AST of the return expression, with recursion backtracking when we 3365/// encounter a subexpression that (1) clearly does not lead to one of the 3366/// above problematic expressions (2) is something we cannot determine leads to 3367/// a problematic expression based on such local checking. 3368/// 3369/// Both EvalAddr and EvalVal follow through reference variables to evaluate 3370/// the expression that they point to. Such variables are added to the 3371/// 'refVars' vector so that we know what the reference variable "trail" was. 3372/// 3373/// EvalAddr processes expressions that are pointers that are used as 3374/// references (and not L-values). EvalVal handles all other values. 3375/// At the base case of the recursion is a check for the above problematic 3376/// expressions. 3377/// 3378/// This implementation handles: 3379/// 3380/// * pointer-to-pointer casts 3381/// * implicit conversions from array references to pointers 3382/// * taking the address of fields 3383/// * arbitrary interplay between "&" and "*" operators 3384/// * pointer arithmetic from an address of a stack variable 3385/// * taking the address of an array element where the array is on the stack 3386static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3387 Decl *ParentDecl) { 3388 if (E->isTypeDependent()) 3389 return NULL; 3390 3391 // We should only be called for evaluating pointer expressions. 3392 assert((E->getType()->isAnyPointerType() || 3393 E->getType()->isBlockPointerType() || 3394 E->getType()->isObjCQualifiedIdType()) && 3395 "EvalAddr only works on pointers"); 3396 3397 E = E->IgnoreParens(); 3398 3399 // Our "symbolic interpreter" is just a dispatch off the currently 3400 // viewed AST node. We then recursively traverse the AST by calling 3401 // EvalAddr and EvalVal appropriately. 3402 switch (E->getStmtClass()) { 3403 case Stmt::DeclRefExprClass: { 3404 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3405 3406 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 3407 // If this is a reference variable, follow through to the expression that 3408 // it points to. 3409 if (V->hasLocalStorage() && 3410 V->getType()->isReferenceType() && V->hasInit()) { 3411 // Add the reference variable to the "trail". 3412 refVars.push_back(DR); 3413 return EvalAddr(V->getInit(), refVars, ParentDecl); 3414 } 3415 3416 return NULL; 3417 } 3418 3419 case Stmt::UnaryOperatorClass: { 3420 // The only unary operator that make sense to handle here 3421 // is AddrOf. All others don't make sense as pointers. 3422 UnaryOperator *U = cast<UnaryOperator>(E); 3423 3424 if (U->getOpcode() == UO_AddrOf) 3425 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 3426 else 3427 return NULL; 3428 } 3429 3430 case Stmt::BinaryOperatorClass: { 3431 // Handle pointer arithmetic. All other binary operators are not valid 3432 // in this context. 3433 BinaryOperator *B = cast<BinaryOperator>(E); 3434 BinaryOperatorKind op = B->getOpcode(); 3435 3436 if (op != BO_Add && op != BO_Sub) 3437 return NULL; 3438 3439 Expr *Base = B->getLHS(); 3440 3441 // Determine which argument is the real pointer base. It could be 3442 // the RHS argument instead of the LHS. 3443 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 3444 3445 assert (Base->getType()->isPointerType()); 3446 return EvalAddr(Base, refVars, ParentDecl); 3447 } 3448 3449 // For conditional operators we need to see if either the LHS or RHS are 3450 // valid DeclRefExpr*s. If one of them is valid, we return it. 3451 case Stmt::ConditionalOperatorClass: { 3452 ConditionalOperator *C = cast<ConditionalOperator>(E); 3453 3454 // Handle the GNU extension for missing LHS. 3455 if (Expr *lhsExpr = C->getLHS()) { 3456 // In C++, we can have a throw-expression, which has 'void' type. 3457 if (!lhsExpr->getType()->isVoidType()) 3458 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl)) 3459 return LHS; 3460 } 3461 3462 // In C++, we can have a throw-expression, which has 'void' type. 3463 if (C->getRHS()->getType()->isVoidType()) 3464 return NULL; 3465 3466 return EvalAddr(C->getRHS(), refVars, ParentDecl); 3467 } 3468 3469 case Stmt::BlockExprClass: 3470 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 3471 return E; // local block. 3472 return NULL; 3473 3474 case Stmt::AddrLabelExprClass: 3475 return E; // address of label. 3476 3477 case Stmt::ExprWithCleanupsClass: 3478 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 3479 ParentDecl); 3480 3481 // For casts, we need to handle conversions from arrays to 3482 // pointer values, and pointer-to-pointer conversions. 3483 case Stmt::ImplicitCastExprClass: 3484 case Stmt::CStyleCastExprClass: 3485 case Stmt::CXXFunctionalCastExprClass: 3486 case Stmt::ObjCBridgedCastExprClass: 3487 case Stmt::CXXStaticCastExprClass: 3488 case Stmt::CXXDynamicCastExprClass: 3489 case Stmt::CXXConstCastExprClass: 3490 case Stmt::CXXReinterpretCastExprClass: { 3491 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 3492 switch (cast<CastExpr>(E)->getCastKind()) { 3493 case CK_BitCast: 3494 case CK_LValueToRValue: 3495 case CK_NoOp: 3496 case CK_BaseToDerived: 3497 case CK_DerivedToBase: 3498 case CK_UncheckedDerivedToBase: 3499 case CK_Dynamic: 3500 case CK_CPointerToObjCPointerCast: 3501 case CK_BlockPointerToObjCPointerCast: 3502 case CK_AnyPointerToBlockPointerCast: 3503 return EvalAddr(SubExpr, refVars, ParentDecl); 3504 3505 case CK_ArrayToPointerDecay: 3506 return EvalVal(SubExpr, refVars, ParentDecl); 3507 3508 default: 3509 return 0; 3510 } 3511 } 3512 3513 case Stmt::MaterializeTemporaryExprClass: 3514 if (Expr *Result = EvalAddr( 3515 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3516 refVars, ParentDecl)) 3517 return Result; 3518 3519 return E; 3520 3521 // Everything else: we simply don't reason about them. 3522 default: 3523 return NULL; 3524 } 3525} 3526 3527 3528/// EvalVal - This function is complements EvalAddr in the mutual recursion. 3529/// See the comments for EvalAddr for more details. 3530static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3531 Decl *ParentDecl) { 3532do { 3533 // We should only be called for evaluating non-pointer expressions, or 3534 // expressions with a pointer type that are not used as references but instead 3535 // are l-values (e.g., DeclRefExpr with a pointer type). 3536 3537 // Our "symbolic interpreter" is just a dispatch off the currently 3538 // viewed AST node. We then recursively traverse the AST by calling 3539 // EvalAddr and EvalVal appropriately. 3540 3541 E = E->IgnoreParens(); 3542 switch (E->getStmtClass()) { 3543 case Stmt::ImplicitCastExprClass: { 3544 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 3545 if (IE->getValueKind() == VK_LValue) { 3546 E = IE->getSubExpr(); 3547 continue; 3548 } 3549 return NULL; 3550 } 3551 3552 case Stmt::ExprWithCleanupsClass: 3553 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 3554 3555 case Stmt::DeclRefExprClass: { 3556 // When we hit a DeclRefExpr we are looking at code that refers to a 3557 // variable's name. If it's not a reference variable we check if it has 3558 // local storage within the function, and if so, return the expression. 3559 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3560 3561 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 3562 // Check if it refers to itself, e.g. "int& i = i;". 3563 if (V == ParentDecl) 3564 return DR; 3565 3566 if (V->hasLocalStorage()) { 3567 if (!V->getType()->isReferenceType()) 3568 return DR; 3569 3570 // Reference variable, follow through to the expression that 3571 // it points to. 3572 if (V->hasInit()) { 3573 // Add the reference variable to the "trail". 3574 refVars.push_back(DR); 3575 return EvalVal(V->getInit(), refVars, V); 3576 } 3577 } 3578 } 3579 3580 return NULL; 3581 } 3582 3583 case Stmt::UnaryOperatorClass: { 3584 // The only unary operator that make sense to handle here 3585 // is Deref. All others don't resolve to a "name." This includes 3586 // handling all sorts of rvalues passed to a unary operator. 3587 UnaryOperator *U = cast<UnaryOperator>(E); 3588 3589 if (U->getOpcode() == UO_Deref) 3590 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 3591 3592 return NULL; 3593 } 3594 3595 case Stmt::ArraySubscriptExprClass: { 3596 // Array subscripts are potential references to data on the stack. We 3597 // retrieve the DeclRefExpr* for the array variable if it indeed 3598 // has local storage. 3599 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 3600 } 3601 3602 case Stmt::ConditionalOperatorClass: { 3603 // For conditional operators we need to see if either the LHS or RHS are 3604 // non-NULL Expr's. If one is non-NULL, we return it. 3605 ConditionalOperator *C = cast<ConditionalOperator>(E); 3606 3607 // Handle the GNU extension for missing LHS. 3608 if (Expr *lhsExpr = C->getLHS()) 3609 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl)) 3610 return LHS; 3611 3612 return EvalVal(C->getRHS(), refVars, ParentDecl); 3613 } 3614 3615 // Accesses to members are potential references to data on the stack. 3616 case Stmt::MemberExprClass: { 3617 MemberExpr *M = cast<MemberExpr>(E); 3618 3619 // Check for indirect access. We only want direct field accesses. 3620 if (M->isArrow()) 3621 return NULL; 3622 3623 // Check whether the member type is itself a reference, in which case 3624 // we're not going to refer to the member, but to what the member refers to. 3625 if (M->getMemberDecl()->getType()->isReferenceType()) 3626 return NULL; 3627 3628 return EvalVal(M->getBase(), refVars, ParentDecl); 3629 } 3630 3631 case Stmt::MaterializeTemporaryExprClass: 3632 if (Expr *Result = EvalVal( 3633 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3634 refVars, ParentDecl)) 3635 return Result; 3636 3637 return E; 3638 3639 default: 3640 // Check that we don't return or take the address of a reference to a 3641 // temporary. This is only useful in C++. 3642 if (!E->isTypeDependent() && E->isRValue()) 3643 return E; 3644 3645 // Everything else: we simply don't reason about them. 3646 return NULL; 3647 } 3648} while (true); 3649} 3650 3651//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3652 3653/// Check for comparisons of floating point operands using != and ==. 3654/// Issue a warning if these are no self-comparisons, as they are not likely 3655/// to do what the programmer intended. 3656void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3657 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3658 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3659 3660 // Special case: check for x == x (which is OK). 3661 // Do not emit warnings for such cases. 3662 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3663 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3664 if (DRL->getDecl() == DRR->getDecl()) 3665 return; 3666 3667 3668 // Special case: check for comparisons against literals that can be exactly 3669 // represented by APFloat. In such cases, do not emit a warning. This 3670 // is a heuristic: often comparison against such literals are used to 3671 // detect if a value in a variable has not changed. This clearly can 3672 // lead to false negatives. 3673 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3674 if (FLL->isExact()) 3675 return; 3676 } else 3677 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 3678 if (FLR->isExact()) 3679 return; 3680 3681 // Check for comparisons with builtin types. 3682 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3683 if (CL->isBuiltinCall()) 3684 return; 3685 3686 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3687 if (CR->isBuiltinCall()) 3688 return; 3689 3690 // Emit the diagnostic. 3691 Diag(Loc, diag::warn_floatingpoint_eq) 3692 << LHS->getSourceRange() << RHS->getSourceRange(); 3693} 3694 3695//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3696//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3697 3698namespace { 3699 3700/// Structure recording the 'active' range of an integer-valued 3701/// expression. 3702struct IntRange { 3703 /// The number of bits active in the int. 3704 unsigned Width; 3705 3706 /// True if the int is known not to have negative values. 3707 bool NonNegative; 3708 3709 IntRange(unsigned Width, bool NonNegative) 3710 : Width(Width), NonNegative(NonNegative) 3711 {} 3712 3713 /// Returns the range of the bool type. 3714 static IntRange forBoolType() { 3715 return IntRange(1, true); 3716 } 3717 3718 /// Returns the range of an opaque value of the given integral type. 3719 static IntRange forValueOfType(ASTContext &C, QualType T) { 3720 return forValueOfCanonicalType(C, 3721 T->getCanonicalTypeInternal().getTypePtr()); 3722 } 3723 3724 /// Returns the range of an opaque value of a canonical integral type. 3725 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3726 assert(T->isCanonicalUnqualified()); 3727 3728 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3729 T = VT->getElementType().getTypePtr(); 3730 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3731 T = CT->getElementType().getTypePtr(); 3732 3733 // For enum types, use the known bit width of the enumerators. 3734 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3735 EnumDecl *Enum = ET->getDecl(); 3736 if (!Enum->isCompleteDefinition()) 3737 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3738 3739 unsigned NumPositive = Enum->getNumPositiveBits(); 3740 unsigned NumNegative = Enum->getNumNegativeBits(); 3741 3742 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3743 } 3744 3745 const BuiltinType *BT = cast<BuiltinType>(T); 3746 assert(BT->isInteger()); 3747 3748 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3749 } 3750 3751 /// Returns the "target" range of a canonical integral type, i.e. 3752 /// the range of values expressible in the type. 3753 /// 3754 /// This matches forValueOfCanonicalType except that enums have the 3755 /// full range of their type, not the range of their enumerators. 3756 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3757 assert(T->isCanonicalUnqualified()); 3758 3759 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3760 T = VT->getElementType().getTypePtr(); 3761 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3762 T = CT->getElementType().getTypePtr(); 3763 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3764 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3765 3766 const BuiltinType *BT = cast<BuiltinType>(T); 3767 assert(BT->isInteger()); 3768 3769 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3770 } 3771 3772 /// Returns the supremum of two ranges: i.e. their conservative merge. 3773 static IntRange join(IntRange L, IntRange R) { 3774 return IntRange(std::max(L.Width, R.Width), 3775 L.NonNegative && R.NonNegative); 3776 } 3777 3778 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3779 static IntRange meet(IntRange L, IntRange R) { 3780 return IntRange(std::min(L.Width, R.Width), 3781 L.NonNegative || R.NonNegative); 3782 } 3783}; 3784 3785static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 3786 unsigned MaxWidth) { 3787 if (value.isSigned() && value.isNegative()) 3788 return IntRange(value.getMinSignedBits(), false); 3789 3790 if (value.getBitWidth() > MaxWidth) 3791 value = value.trunc(MaxWidth); 3792 3793 // isNonNegative() just checks the sign bit without considering 3794 // signedness. 3795 return IntRange(value.getActiveBits(), true); 3796} 3797 3798static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3799 unsigned MaxWidth) { 3800 if (result.isInt()) 3801 return GetValueRange(C, result.getInt(), MaxWidth); 3802 3803 if (result.isVector()) { 3804 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3805 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3806 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3807 R = IntRange::join(R, El); 3808 } 3809 return R; 3810 } 3811 3812 if (result.isComplexInt()) { 3813 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3814 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3815 return IntRange::join(R, I); 3816 } 3817 3818 // This can happen with lossless casts to intptr_t of "based" lvalues. 3819 // Assume it might use arbitrary bits. 3820 // FIXME: The only reason we need to pass the type in here is to get 3821 // the sign right on this one case. It would be nice if APValue 3822 // preserved this. 3823 assert(result.isLValue() || result.isAddrLabelDiff()); 3824 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 3825} 3826 3827/// Pseudo-evaluate the given integer expression, estimating the 3828/// range of values it might take. 3829/// 3830/// \param MaxWidth - the width to which the value will be truncated 3831static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 3832 E = E->IgnoreParens(); 3833 3834 // Try a full evaluation first. 3835 Expr::EvalResult result; 3836 if (E->EvaluateAsRValue(result, C)) 3837 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 3838 3839 // I think we only want to look through implicit casts here; if the 3840 // user has an explicit widening cast, we should treat the value as 3841 // being of the new, wider type. 3842 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 3843 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 3844 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 3845 3846 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 3847 3848 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 3849 3850 // Assume that non-integer casts can span the full range of the type. 3851 if (!isIntegerCast) 3852 return OutputTypeRange; 3853 3854 IntRange SubRange 3855 = GetExprRange(C, CE->getSubExpr(), 3856 std::min(MaxWidth, OutputTypeRange.Width)); 3857 3858 // Bail out if the subexpr's range is as wide as the cast type. 3859 if (SubRange.Width >= OutputTypeRange.Width) 3860 return OutputTypeRange; 3861 3862 // Otherwise, we take the smaller width, and we're non-negative if 3863 // either the output type or the subexpr is. 3864 return IntRange(SubRange.Width, 3865 SubRange.NonNegative || OutputTypeRange.NonNegative); 3866 } 3867 3868 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3869 // If we can fold the condition, just take that operand. 3870 bool CondResult; 3871 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 3872 return GetExprRange(C, CondResult ? CO->getTrueExpr() 3873 : CO->getFalseExpr(), 3874 MaxWidth); 3875 3876 // Otherwise, conservatively merge. 3877 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 3878 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 3879 return IntRange::join(L, R); 3880 } 3881 3882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3883 switch (BO->getOpcode()) { 3884 3885 // Boolean-valued operations are single-bit and positive. 3886 case BO_LAnd: 3887 case BO_LOr: 3888 case BO_LT: 3889 case BO_GT: 3890 case BO_LE: 3891 case BO_GE: 3892 case BO_EQ: 3893 case BO_NE: 3894 return IntRange::forBoolType(); 3895 3896 // The type of the assignments is the type of the LHS, so the RHS 3897 // is not necessarily the same type. 3898 case BO_MulAssign: 3899 case BO_DivAssign: 3900 case BO_RemAssign: 3901 case BO_AddAssign: 3902 case BO_SubAssign: 3903 case BO_XorAssign: 3904 case BO_OrAssign: 3905 // TODO: bitfields? 3906 return IntRange::forValueOfType(C, E->getType()); 3907 3908 // Simple assignments just pass through the RHS, which will have 3909 // been coerced to the LHS type. 3910 case BO_Assign: 3911 // TODO: bitfields? 3912 return GetExprRange(C, BO->getRHS(), MaxWidth); 3913 3914 // Operations with opaque sources are black-listed. 3915 case BO_PtrMemD: 3916 case BO_PtrMemI: 3917 return IntRange::forValueOfType(C, E->getType()); 3918 3919 // Bitwise-and uses the *infinum* of the two source ranges. 3920 case BO_And: 3921 case BO_AndAssign: 3922 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 3923 GetExprRange(C, BO->getRHS(), MaxWidth)); 3924 3925 // Left shift gets black-listed based on a judgement call. 3926 case BO_Shl: 3927 // ...except that we want to treat '1 << (blah)' as logically 3928 // positive. It's an important idiom. 3929 if (IntegerLiteral *I 3930 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 3931 if (I->getValue() == 1) { 3932 IntRange R = IntRange::forValueOfType(C, E->getType()); 3933 return IntRange(R.Width, /*NonNegative*/ true); 3934 } 3935 } 3936 // fallthrough 3937 3938 case BO_ShlAssign: 3939 return IntRange::forValueOfType(C, E->getType()); 3940 3941 // Right shift by a constant can narrow its left argument. 3942 case BO_Shr: 3943 case BO_ShrAssign: { 3944 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3945 3946 // If the shift amount is a positive constant, drop the width by 3947 // that much. 3948 llvm::APSInt shift; 3949 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 3950 shift.isNonNegative()) { 3951 unsigned zext = shift.getZExtValue(); 3952 if (zext >= L.Width) 3953 L.Width = (L.NonNegative ? 0 : 1); 3954 else 3955 L.Width -= zext; 3956 } 3957 3958 return L; 3959 } 3960 3961 // Comma acts as its right operand. 3962 case BO_Comma: 3963 return GetExprRange(C, BO->getRHS(), MaxWidth); 3964 3965 // Black-list pointer subtractions. 3966 case BO_Sub: 3967 if (BO->getLHS()->getType()->isPointerType()) 3968 return IntRange::forValueOfType(C, E->getType()); 3969 break; 3970 3971 // The width of a division result is mostly determined by the size 3972 // of the LHS. 3973 case BO_Div: { 3974 // Don't 'pre-truncate' the operands. 3975 unsigned opWidth = C.getIntWidth(E->getType()); 3976 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3977 3978 // If the divisor is constant, use that. 3979 llvm::APSInt divisor; 3980 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 3981 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 3982 if (log2 >= L.Width) 3983 L.Width = (L.NonNegative ? 0 : 1); 3984 else 3985 L.Width = std::min(L.Width - log2, MaxWidth); 3986 return L; 3987 } 3988 3989 // Otherwise, just use the LHS's width. 3990 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3991 return IntRange(L.Width, L.NonNegative && R.NonNegative); 3992 } 3993 3994 // The result of a remainder can't be larger than the result of 3995 // either side. 3996 case BO_Rem: { 3997 // Don't 'pre-truncate' the operands. 3998 unsigned opWidth = C.getIntWidth(E->getType()); 3999 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 4000 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 4001 4002 IntRange meet = IntRange::meet(L, R); 4003 meet.Width = std::min(meet.Width, MaxWidth); 4004 return meet; 4005 } 4006 4007 // The default behavior is okay for these. 4008 case BO_Mul: 4009 case BO_Add: 4010 case BO_Xor: 4011 case BO_Or: 4012 break; 4013 } 4014 4015 // The default case is to treat the operation as if it were closed 4016 // on the narrowest type that encompasses both operands. 4017 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 4018 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 4019 return IntRange::join(L, R); 4020 } 4021 4022 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 4023 switch (UO->getOpcode()) { 4024 // Boolean-valued operations are white-listed. 4025 case UO_LNot: 4026 return IntRange::forBoolType(); 4027 4028 // Operations with opaque sources are black-listed. 4029 case UO_Deref: 4030 case UO_AddrOf: // should be impossible 4031 return IntRange::forValueOfType(C, E->getType()); 4032 4033 default: 4034 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 4035 } 4036 } 4037 4038 if (dyn_cast<OffsetOfExpr>(E)) { 4039 IntRange::forValueOfType(C, E->getType()); 4040 } 4041 4042 if (FieldDecl *BitField = E->getBitField()) 4043 return IntRange(BitField->getBitWidthValue(C), 4044 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 4045 4046 return IntRange::forValueOfType(C, E->getType()); 4047} 4048 4049static IntRange GetExprRange(ASTContext &C, Expr *E) { 4050 return GetExprRange(C, E, C.getIntWidth(E->getType())); 4051} 4052 4053/// Checks whether the given value, which currently has the given 4054/// source semantics, has the same value when coerced through the 4055/// target semantics. 4056static bool IsSameFloatAfterCast(const llvm::APFloat &value, 4057 const llvm::fltSemantics &Src, 4058 const llvm::fltSemantics &Tgt) { 4059 llvm::APFloat truncated = value; 4060 4061 bool ignored; 4062 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 4063 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 4064 4065 return truncated.bitwiseIsEqual(value); 4066} 4067 4068/// Checks whether the given value, which currently has the given 4069/// source semantics, has the same value when coerced through the 4070/// target semantics. 4071/// 4072/// The value might be a vector of floats (or a complex number). 4073static bool IsSameFloatAfterCast(const APValue &value, 4074 const llvm::fltSemantics &Src, 4075 const llvm::fltSemantics &Tgt) { 4076 if (value.isFloat()) 4077 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 4078 4079 if (value.isVector()) { 4080 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 4081 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 4082 return false; 4083 return true; 4084 } 4085 4086 assert(value.isComplexFloat()); 4087 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 4088 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 4089} 4090 4091static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 4092 4093static bool IsZero(Sema &S, Expr *E) { 4094 // Suppress cases where we are comparing against an enum constant. 4095 if (const DeclRefExpr *DR = 4096 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 4097 if (isa<EnumConstantDecl>(DR->getDecl())) 4098 return false; 4099 4100 // Suppress cases where the '0' value is expanded from a macro. 4101 if (E->getLocStart().isMacroID()) 4102 return false; 4103 4104 llvm::APSInt Value; 4105 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 4106} 4107 4108static bool HasEnumType(Expr *E) { 4109 // Strip off implicit integral promotions. 4110 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 4111 if (ICE->getCastKind() != CK_IntegralCast && 4112 ICE->getCastKind() != CK_NoOp) 4113 break; 4114 E = ICE->getSubExpr(); 4115 } 4116 4117 return E->getType()->isEnumeralType(); 4118} 4119 4120static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 4121 BinaryOperatorKind op = E->getOpcode(); 4122 if (E->isValueDependent()) 4123 return; 4124 4125 if (op == BO_LT && IsZero(S, E->getRHS())) { 4126 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4127 << "< 0" << "false" << HasEnumType(E->getLHS()) 4128 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4129 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 4130 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4131 << ">= 0" << "true" << HasEnumType(E->getLHS()) 4132 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4133 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 4134 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4135 << "0 >" << "false" << HasEnumType(E->getRHS()) 4136 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4137 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 4138 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4139 << "0 <=" << "true" << HasEnumType(E->getRHS()) 4140 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4141 } 4142} 4143 4144/// Analyze the operands of the given comparison. Implements the 4145/// fallback case from AnalyzeComparison. 4146static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 4147 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4148 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4149} 4150 4151/// \brief Implements -Wsign-compare. 4152/// 4153/// \param E the binary operator to check for warnings 4154static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 4155 // The type the comparison is being performed in. 4156 QualType T = E->getLHS()->getType(); 4157 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 4158 && "comparison with mismatched types"); 4159 4160 // We don't do anything special if this isn't an unsigned integral 4161 // comparison: we're only interested in integral comparisons, and 4162 // signed comparisons only happen in cases we don't care to warn about. 4163 // 4164 // We also don't care about value-dependent expressions or expressions 4165 // whose result is a constant. 4166 if (!T->hasUnsignedIntegerRepresentation() 4167 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 4168 return AnalyzeImpConvsInComparison(S, E); 4169 4170 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 4171 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 4172 4173 // Check to see if one of the (unmodified) operands is of different 4174 // signedness. 4175 Expr *signedOperand, *unsignedOperand; 4176 if (LHS->getType()->hasSignedIntegerRepresentation()) { 4177 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 4178 "unsigned comparison between two signed integer expressions?"); 4179 signedOperand = LHS; 4180 unsignedOperand = RHS; 4181 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 4182 signedOperand = RHS; 4183 unsignedOperand = LHS; 4184 } else { 4185 CheckTrivialUnsignedComparison(S, E); 4186 return AnalyzeImpConvsInComparison(S, E); 4187 } 4188 4189 // Otherwise, calculate the effective range of the signed operand. 4190 IntRange signedRange = GetExprRange(S.Context, signedOperand); 4191 4192 // Go ahead and analyze implicit conversions in the operands. Note 4193 // that we skip the implicit conversions on both sides. 4194 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 4195 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 4196 4197 // If the signed range is non-negative, -Wsign-compare won't fire, 4198 // but we should still check for comparisons which are always true 4199 // or false. 4200 if (signedRange.NonNegative) 4201 return CheckTrivialUnsignedComparison(S, E); 4202 4203 // For (in)equality comparisons, if the unsigned operand is a 4204 // constant which cannot collide with a overflowed signed operand, 4205 // then reinterpreting the signed operand as unsigned will not 4206 // change the result of the comparison. 4207 if (E->isEqualityOp()) { 4208 unsigned comparisonWidth = S.Context.getIntWidth(T); 4209 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 4210 4211 // We should never be unable to prove that the unsigned operand is 4212 // non-negative. 4213 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 4214 4215 if (unsignedRange.Width < comparisonWidth) 4216 return; 4217 } 4218 4219 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 4220 S.PDiag(diag::warn_mixed_sign_comparison) 4221 << LHS->getType() << RHS->getType() 4222 << LHS->getSourceRange() << RHS->getSourceRange()); 4223} 4224 4225/// Analyzes an attempt to assign the given value to a bitfield. 4226/// 4227/// Returns true if there was something fishy about the attempt. 4228static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 4229 SourceLocation InitLoc) { 4230 assert(Bitfield->isBitField()); 4231 if (Bitfield->isInvalidDecl()) 4232 return false; 4233 4234 // White-list bool bitfields. 4235 if (Bitfield->getType()->isBooleanType()) 4236 return false; 4237 4238 // Ignore value- or type-dependent expressions. 4239 if (Bitfield->getBitWidth()->isValueDependent() || 4240 Bitfield->getBitWidth()->isTypeDependent() || 4241 Init->isValueDependent() || 4242 Init->isTypeDependent()) 4243 return false; 4244 4245 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 4246 4247 llvm::APSInt Value; 4248 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 4249 return false; 4250 4251 unsigned OriginalWidth = Value.getBitWidth(); 4252 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 4253 4254 if (OriginalWidth <= FieldWidth) 4255 return false; 4256 4257 // Compute the value which the bitfield will contain. 4258 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 4259 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 4260 4261 // Check whether the stored value is equal to the original value. 4262 TruncatedValue = TruncatedValue.extend(OriginalWidth); 4263 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 4264 return false; 4265 4266 // Special-case bitfields of width 1: booleans are naturally 0/1, and 4267 // therefore don't strictly fit into a signed bitfield of width 1. 4268 if (FieldWidth == 1 && Value == 1) 4269 return false; 4270 4271 std::string PrettyValue = Value.toString(10); 4272 std::string PrettyTrunc = TruncatedValue.toString(10); 4273 4274 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 4275 << PrettyValue << PrettyTrunc << OriginalInit->getType() 4276 << Init->getSourceRange(); 4277 4278 return true; 4279} 4280 4281/// Analyze the given simple or compound assignment for warning-worthy 4282/// operations. 4283static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 4284 // Just recurse on the LHS. 4285 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4286 4287 // We want to recurse on the RHS as normal unless we're assigning to 4288 // a bitfield. 4289 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 4290 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 4291 E->getOperatorLoc())) { 4292 // Recurse, ignoring any implicit conversions on the RHS. 4293 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 4294 E->getOperatorLoc()); 4295 } 4296 } 4297 4298 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4299} 4300 4301/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4302static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 4303 SourceLocation CContext, unsigned diag, 4304 bool pruneControlFlow = false) { 4305 if (pruneControlFlow) { 4306 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4307 S.PDiag(diag) 4308 << SourceType << T << E->getSourceRange() 4309 << SourceRange(CContext)); 4310 return; 4311 } 4312 S.Diag(E->getExprLoc(), diag) 4313 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 4314} 4315 4316/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4317static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 4318 SourceLocation CContext, unsigned diag, 4319 bool pruneControlFlow = false) { 4320 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 4321} 4322 4323/// Diagnose an implicit cast from a literal expression. Does not warn when the 4324/// cast wouldn't lose information. 4325void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 4326 SourceLocation CContext) { 4327 // Try to convert the literal exactly to an integer. If we can, don't warn. 4328 bool isExact = false; 4329 const llvm::APFloat &Value = FL->getValue(); 4330 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 4331 T->hasUnsignedIntegerRepresentation()); 4332 if (Value.convertToInteger(IntegerValue, 4333 llvm::APFloat::rmTowardZero, &isExact) 4334 == llvm::APFloat::opOK && isExact) 4335 return; 4336 4337 SmallString<16> PrettySourceValue; 4338 Value.toString(PrettySourceValue); 4339 SmallString<16> PrettyTargetValue; 4340 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 4341 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 4342 else 4343 IntegerValue.toString(PrettyTargetValue); 4344 4345 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 4346 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 4347 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 4348} 4349 4350std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 4351 if (!Range.Width) return "0"; 4352 4353 llvm::APSInt ValueInRange = Value; 4354 ValueInRange.setIsSigned(!Range.NonNegative); 4355 ValueInRange = ValueInRange.trunc(Range.Width); 4356 return ValueInRange.toString(10); 4357} 4358 4359void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 4360 SourceLocation CC, bool *ICContext = 0) { 4361 if (E->isTypeDependent() || E->isValueDependent()) return; 4362 4363 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 4364 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 4365 if (Source == Target) return; 4366 if (Target->isDependentType()) return; 4367 4368 // If the conversion context location is invalid don't complain. We also 4369 // don't want to emit a warning if the issue occurs from the expansion of 4370 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 4371 // delay this check as long as possible. Once we detect we are in that 4372 // scenario, we just return. 4373 if (CC.isInvalid()) 4374 return; 4375 4376 // Diagnose implicit casts to bool. 4377 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 4378 if (isa<StringLiteral>(E)) 4379 // Warn on string literal to bool. Checks for string literals in logical 4380 // expressions, for instances, assert(0 && "error here"), is prevented 4381 // by a check in AnalyzeImplicitConversions(). 4382 return DiagnoseImpCast(S, E, T, CC, 4383 diag::warn_impcast_string_literal_to_bool); 4384 if (Source->isFunctionType()) { 4385 // Warn on function to bool. Checks free functions and static member 4386 // functions. Weakly imported functions are excluded from the check, 4387 // since it's common to test their value to check whether the linker 4388 // found a definition for them. 4389 ValueDecl *D = 0; 4390 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 4391 D = R->getDecl(); 4392 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 4393 D = M->getMemberDecl(); 4394 } 4395 4396 if (D && !D->isWeak()) { 4397 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 4398 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 4399 << F << E->getSourceRange() << SourceRange(CC); 4400 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 4401 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 4402 QualType ReturnType; 4403 UnresolvedSet<4> NonTemplateOverloads; 4404 S.isExprCallable(*E, ReturnType, NonTemplateOverloads); 4405 if (!ReturnType.isNull() 4406 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 4407 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 4408 << FixItHint::CreateInsertion( 4409 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 4410 return; 4411 } 4412 } 4413 } 4414 } 4415 4416 // Strip vector types. 4417 if (isa<VectorType>(Source)) { 4418 if (!isa<VectorType>(Target)) { 4419 if (S.SourceMgr.isInSystemMacro(CC)) 4420 return; 4421 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 4422 } 4423 4424 // If the vector cast is cast between two vectors of the same size, it is 4425 // a bitcast, not a conversion. 4426 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 4427 return; 4428 4429 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 4430 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 4431 } 4432 4433 // Strip complex types. 4434 if (isa<ComplexType>(Source)) { 4435 if (!isa<ComplexType>(Target)) { 4436 if (S.SourceMgr.isInSystemMacro(CC)) 4437 return; 4438 4439 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 4440 } 4441 4442 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 4443 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 4444 } 4445 4446 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 4447 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 4448 4449 // If the source is floating point... 4450 if (SourceBT && SourceBT->isFloatingPoint()) { 4451 // ...and the target is floating point... 4452 if (TargetBT && TargetBT->isFloatingPoint()) { 4453 // ...then warn if we're dropping FP rank. 4454 4455 // Builtin FP kinds are ordered by increasing FP rank. 4456 if (SourceBT->getKind() > TargetBT->getKind()) { 4457 // Don't warn about float constants that are precisely 4458 // representable in the target type. 4459 Expr::EvalResult result; 4460 if (E->EvaluateAsRValue(result, S.Context)) { 4461 // Value might be a float, a float vector, or a float complex. 4462 if (IsSameFloatAfterCast(result.Val, 4463 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 4464 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 4465 return; 4466 } 4467 4468 if (S.SourceMgr.isInSystemMacro(CC)) 4469 return; 4470 4471 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 4472 } 4473 return; 4474 } 4475 4476 // If the target is integral, always warn. 4477 if (TargetBT && TargetBT->isInteger()) { 4478 if (S.SourceMgr.isInSystemMacro(CC)) 4479 return; 4480 4481 Expr *InnerE = E->IgnoreParenImpCasts(); 4482 // We also want to warn on, e.g., "int i = -1.234" 4483 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 4484 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 4485 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 4486 4487 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 4488 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 4489 } else { 4490 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 4491 } 4492 } 4493 4494 return; 4495 } 4496 4497 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 4498 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType() 4499 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) { 4500 SourceLocation Loc = E->getSourceRange().getBegin(); 4501 if (Loc.isMacroID()) 4502 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 4503 if (!Loc.isMacroID() || CC.isMacroID()) 4504 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 4505 << T << clang::SourceRange(CC) 4506 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T)); 4507 } 4508 4509 if (!Source->isIntegerType() || !Target->isIntegerType()) 4510 return; 4511 4512 // TODO: remove this early return once the false positives for constant->bool 4513 // in templates, macros, etc, are reduced or removed. 4514 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 4515 return; 4516 4517 IntRange SourceRange = GetExprRange(S.Context, E); 4518 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 4519 4520 if (SourceRange.Width > TargetRange.Width) { 4521 // If the source is a constant, use a default-on diagnostic. 4522 // TODO: this should happen for bitfield stores, too. 4523 llvm::APSInt Value(32); 4524 if (E->isIntegerConstantExpr(Value, S.Context)) { 4525 if (S.SourceMgr.isInSystemMacro(CC)) 4526 return; 4527 4528 std::string PrettySourceValue = Value.toString(10); 4529 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 4530 4531 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4532 S.PDiag(diag::warn_impcast_integer_precision_constant) 4533 << PrettySourceValue << PrettyTargetValue 4534 << E->getType() << T << E->getSourceRange() 4535 << clang::SourceRange(CC)); 4536 return; 4537 } 4538 4539 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 4540 if (S.SourceMgr.isInSystemMacro(CC)) 4541 return; 4542 4543 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 4544 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 4545 /* pruneControlFlow */ true); 4546 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 4547 } 4548 4549 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 4550 (!TargetRange.NonNegative && SourceRange.NonNegative && 4551 SourceRange.Width == TargetRange.Width)) { 4552 4553 if (S.SourceMgr.isInSystemMacro(CC)) 4554 return; 4555 4556 unsigned DiagID = diag::warn_impcast_integer_sign; 4557 4558 // Traditionally, gcc has warned about this under -Wsign-compare. 4559 // We also want to warn about it in -Wconversion. 4560 // So if -Wconversion is off, use a completely identical diagnostic 4561 // in the sign-compare group. 4562 // The conditional-checking code will 4563 if (ICContext) { 4564 DiagID = diag::warn_impcast_integer_sign_conditional; 4565 *ICContext = true; 4566 } 4567 4568 return DiagnoseImpCast(S, E, T, CC, DiagID); 4569 } 4570 4571 // Diagnose conversions between different enumeration types. 4572 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 4573 // type, to give us better diagnostics. 4574 QualType SourceType = E->getType(); 4575 if (!S.getLangOpts().CPlusPlus) { 4576 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4577 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4578 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 4579 SourceType = S.Context.getTypeDeclType(Enum); 4580 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 4581 } 4582 } 4583 4584 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 4585 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 4586 if ((SourceEnum->getDecl()->getIdentifier() || 4587 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 4588 (TargetEnum->getDecl()->getIdentifier() || 4589 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 4590 SourceEnum != TargetEnum) { 4591 if (S.SourceMgr.isInSystemMacro(CC)) 4592 return; 4593 4594 return DiagnoseImpCast(S, E, SourceType, T, CC, 4595 diag::warn_impcast_different_enum_types); 4596 } 4597 4598 return; 4599} 4600 4601void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4602 SourceLocation CC, QualType T); 4603 4604void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 4605 SourceLocation CC, bool &ICContext) { 4606 E = E->IgnoreParenImpCasts(); 4607 4608 if (isa<ConditionalOperator>(E)) 4609 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 4610 4611 AnalyzeImplicitConversions(S, E, CC); 4612 if (E->getType() != T) 4613 return CheckImplicitConversion(S, E, T, CC, &ICContext); 4614 return; 4615} 4616 4617void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4618 SourceLocation CC, QualType T) { 4619 AnalyzeImplicitConversions(S, E->getCond(), CC); 4620 4621 bool Suspicious = false; 4622 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 4623 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 4624 4625 // If -Wconversion would have warned about either of the candidates 4626 // for a signedness conversion to the context type... 4627 if (!Suspicious) return; 4628 4629 // ...but it's currently ignored... 4630 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 4631 CC)) 4632 return; 4633 4634 // ...then check whether it would have warned about either of the 4635 // candidates for a signedness conversion to the condition type. 4636 if (E->getType() == T) return; 4637 4638 Suspicious = false; 4639 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 4640 E->getType(), CC, &Suspicious); 4641 if (!Suspicious) 4642 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 4643 E->getType(), CC, &Suspicious); 4644} 4645 4646/// AnalyzeImplicitConversions - Find and report any interesting 4647/// implicit conversions in the given expression. There are a couple 4648/// of competing diagnostics here, -Wconversion and -Wsign-compare. 4649void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 4650 QualType T = OrigE->getType(); 4651 Expr *E = OrigE->IgnoreParenImpCasts(); 4652 4653 if (E->isTypeDependent() || E->isValueDependent()) 4654 return; 4655 4656 // For conditional operators, we analyze the arguments as if they 4657 // were being fed directly into the output. 4658 if (isa<ConditionalOperator>(E)) { 4659 ConditionalOperator *CO = cast<ConditionalOperator>(E); 4660 CheckConditionalOperator(S, CO, CC, T); 4661 return; 4662 } 4663 4664 // Go ahead and check any implicit conversions we might have skipped. 4665 // The non-canonical typecheck is just an optimization; 4666 // CheckImplicitConversion will filter out dead implicit conversions. 4667 if (E->getType() != T) 4668 CheckImplicitConversion(S, E, T, CC); 4669 4670 // Now continue drilling into this expression. 4671 4672 // Skip past explicit casts. 4673 if (isa<ExplicitCastExpr>(E)) { 4674 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4675 return AnalyzeImplicitConversions(S, E, CC); 4676 } 4677 4678 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4679 // Do a somewhat different check with comparison operators. 4680 if (BO->isComparisonOp()) 4681 return AnalyzeComparison(S, BO); 4682 4683 // And with simple assignments. 4684 if (BO->getOpcode() == BO_Assign) 4685 return AnalyzeAssignment(S, BO); 4686 } 4687 4688 // These break the otherwise-useful invariant below. Fortunately, 4689 // we don't really need to recurse into them, because any internal 4690 // expressions should have been analyzed already when they were 4691 // built into statements. 4692 if (isa<StmtExpr>(E)) return; 4693 4694 // Don't descend into unevaluated contexts. 4695 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 4696 4697 // Now just recurse over the expression's children. 4698 CC = E->getExprLoc(); 4699 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 4700 bool IsLogicalOperator = BO && BO->isLogicalOp(); 4701 for (Stmt::child_range I = E->children(); I; ++I) { 4702 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 4703 if (!ChildExpr) 4704 continue; 4705 4706 if (IsLogicalOperator && 4707 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 4708 // Ignore checking string literals that are in logical operators. 4709 continue; 4710 AnalyzeImplicitConversions(S, ChildExpr, CC); 4711 } 4712} 4713 4714} // end anonymous namespace 4715 4716/// Diagnoses "dangerous" implicit conversions within the given 4717/// expression (which is a full expression). Implements -Wconversion 4718/// and -Wsign-compare. 4719/// 4720/// \param CC the "context" location of the implicit conversion, i.e. 4721/// the most location of the syntactic entity requiring the implicit 4722/// conversion 4723void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 4724 // Don't diagnose in unevaluated contexts. 4725 if (isUnevaluatedContext()) 4726 return; 4727 4728 // Don't diagnose for value- or type-dependent expressions. 4729 if (E->isTypeDependent() || E->isValueDependent()) 4730 return; 4731 4732 // Check for array bounds violations in cases where the check isn't triggered 4733 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 4734 // ArraySubscriptExpr is on the RHS of a variable initialization. 4735 CheckArrayAccess(E); 4736 4737 // This is not the right CC for (e.g.) a variable initialization. 4738 AnalyzeImplicitConversions(*this, E, CC); 4739} 4740 4741void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 4742 FieldDecl *BitField, 4743 Expr *Init) { 4744 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 4745} 4746 4747/// CheckParmsForFunctionDef - Check that the parameters of the given 4748/// function are appropriate for the definition of a function. This 4749/// takes care of any checks that cannot be performed on the 4750/// declaration itself, e.g., that the types of each of the function 4751/// parameters are complete. 4752bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 4753 bool CheckParameterNames) { 4754 bool HasInvalidParm = false; 4755 for (; P != PEnd; ++P) { 4756 ParmVarDecl *Param = *P; 4757 4758 // C99 6.7.5.3p4: the parameters in a parameter type list in a 4759 // function declarator that is part of a function definition of 4760 // that function shall not have incomplete type. 4761 // 4762 // This is also C++ [dcl.fct]p6. 4763 if (!Param->isInvalidDecl() && 4764 RequireCompleteType(Param->getLocation(), Param->getType(), 4765 diag::err_typecheck_decl_incomplete_type)) { 4766 Param->setInvalidDecl(); 4767 HasInvalidParm = true; 4768 } 4769 4770 // C99 6.9.1p5: If the declarator includes a parameter type list, the 4771 // declaration of each parameter shall include an identifier. 4772 if (CheckParameterNames && 4773 Param->getIdentifier() == 0 && 4774 !Param->isImplicit() && 4775 !getLangOpts().CPlusPlus) 4776 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 4777 4778 // C99 6.7.5.3p12: 4779 // If the function declarator is not part of a definition of that 4780 // function, parameters may have incomplete type and may use the [*] 4781 // notation in their sequences of declarator specifiers to specify 4782 // variable length array types. 4783 QualType PType = Param->getOriginalType(); 4784 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 4785 if (AT->getSizeModifier() == ArrayType::Star) { 4786 // FIXME: This diagnosic should point the '[*]' if source-location 4787 // information is added for it. 4788 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 4789 } 4790 } 4791 } 4792 4793 return HasInvalidParm; 4794} 4795 4796/// CheckCastAlign - Implements -Wcast-align, which warns when a 4797/// pointer cast increases the alignment requirements. 4798void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 4799 // This is actually a lot of work to potentially be doing on every 4800 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 4801 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 4802 TRange.getBegin()) 4803 == DiagnosticsEngine::Ignored) 4804 return; 4805 4806 // Ignore dependent types. 4807 if (T->isDependentType() || Op->getType()->isDependentType()) 4808 return; 4809 4810 // Require that the destination be a pointer type. 4811 const PointerType *DestPtr = T->getAs<PointerType>(); 4812 if (!DestPtr) return; 4813 4814 // If the destination has alignment 1, we're done. 4815 QualType DestPointee = DestPtr->getPointeeType(); 4816 if (DestPointee->isIncompleteType()) return; 4817 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 4818 if (DestAlign.isOne()) return; 4819 4820 // Require that the source be a pointer type. 4821 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 4822 if (!SrcPtr) return; 4823 QualType SrcPointee = SrcPtr->getPointeeType(); 4824 4825 // Whitelist casts from cv void*. We already implicitly 4826 // whitelisted casts to cv void*, since they have alignment 1. 4827 // Also whitelist casts involving incomplete types, which implicitly 4828 // includes 'void'. 4829 if (SrcPointee->isIncompleteType()) return; 4830 4831 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 4832 if (SrcAlign >= DestAlign) return; 4833 4834 Diag(TRange.getBegin(), diag::warn_cast_align) 4835 << Op->getType() << T 4836 << static_cast<unsigned>(SrcAlign.getQuantity()) 4837 << static_cast<unsigned>(DestAlign.getQuantity()) 4838 << TRange << Op->getSourceRange(); 4839} 4840 4841static const Type* getElementType(const Expr *BaseExpr) { 4842 const Type* EltType = BaseExpr->getType().getTypePtr(); 4843 if (EltType->isAnyPointerType()) 4844 return EltType->getPointeeType().getTypePtr(); 4845 else if (EltType->isArrayType()) 4846 return EltType->getBaseElementTypeUnsafe(); 4847 return EltType; 4848} 4849 4850/// \brief Check whether this array fits the idiom of a size-one tail padded 4851/// array member of a struct. 4852/// 4853/// We avoid emitting out-of-bounds access warnings for such arrays as they are 4854/// commonly used to emulate flexible arrays in C89 code. 4855static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 4856 const NamedDecl *ND) { 4857 if (Size != 1 || !ND) return false; 4858 4859 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 4860 if (!FD) return false; 4861 4862 // Don't consider sizes resulting from macro expansions or template argument 4863 // substitution to form C89 tail-padded arrays. 4864 4865 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 4866 while (TInfo) { 4867 TypeLoc TL = TInfo->getTypeLoc(); 4868 // Look through typedefs. 4869 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL); 4870 if (TTL) { 4871 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl(); 4872 TInfo = TDL->getTypeSourceInfo(); 4873 continue; 4874 } 4875 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL); 4876 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 4877 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 4878 return false; 4879 break; 4880 } 4881 4882 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 4883 if (!RD) return false; 4884 if (RD->isUnion()) return false; 4885 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 4886 if (!CRD->isStandardLayout()) return false; 4887 } 4888 4889 // See if this is the last field decl in the record. 4890 const Decl *D = FD; 4891 while ((D = D->getNextDeclInContext())) 4892 if (isa<FieldDecl>(D)) 4893 return false; 4894 return true; 4895} 4896 4897void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 4898 const ArraySubscriptExpr *ASE, 4899 bool AllowOnePastEnd, bool IndexNegated) { 4900 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 4901 if (IndexExpr->isValueDependent()) 4902 return; 4903 4904 const Type *EffectiveType = getElementType(BaseExpr); 4905 BaseExpr = BaseExpr->IgnoreParenCasts(); 4906 const ConstantArrayType *ArrayTy = 4907 Context.getAsConstantArrayType(BaseExpr->getType()); 4908 if (!ArrayTy) 4909 return; 4910 4911 llvm::APSInt index; 4912 if (!IndexExpr->EvaluateAsInt(index, Context)) 4913 return; 4914 if (IndexNegated) 4915 index = -index; 4916 4917 const NamedDecl *ND = NULL; 4918 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4919 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4920 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4921 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4922 4923 if (index.isUnsigned() || !index.isNegative()) { 4924 llvm::APInt size = ArrayTy->getSize(); 4925 if (!size.isStrictlyPositive()) 4926 return; 4927 4928 const Type* BaseType = getElementType(BaseExpr); 4929 if (BaseType != EffectiveType) { 4930 // Make sure we're comparing apples to apples when comparing index to size 4931 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 4932 uint64_t array_typesize = Context.getTypeSize(BaseType); 4933 // Handle ptrarith_typesize being zero, such as when casting to void* 4934 if (!ptrarith_typesize) ptrarith_typesize = 1; 4935 if (ptrarith_typesize != array_typesize) { 4936 // There's a cast to a different size type involved 4937 uint64_t ratio = array_typesize / ptrarith_typesize; 4938 // TODO: Be smarter about handling cases where array_typesize is not a 4939 // multiple of ptrarith_typesize 4940 if (ptrarith_typesize * ratio == array_typesize) 4941 size *= llvm::APInt(size.getBitWidth(), ratio); 4942 } 4943 } 4944 4945 if (size.getBitWidth() > index.getBitWidth()) 4946 index = index.zext(size.getBitWidth()); 4947 else if (size.getBitWidth() < index.getBitWidth()) 4948 size = size.zext(index.getBitWidth()); 4949 4950 // For array subscripting the index must be less than size, but for pointer 4951 // arithmetic also allow the index (offset) to be equal to size since 4952 // computing the next address after the end of the array is legal and 4953 // commonly done e.g. in C++ iterators and range-based for loops. 4954 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 4955 return; 4956 4957 // Also don't warn for arrays of size 1 which are members of some 4958 // structure. These are often used to approximate flexible arrays in C89 4959 // code. 4960 if (IsTailPaddedMemberArray(*this, size, ND)) 4961 return; 4962 4963 // Suppress the warning if the subscript expression (as identified by the 4964 // ']' location) and the index expression are both from macro expansions 4965 // within a system header. 4966 if (ASE) { 4967 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 4968 ASE->getRBracketLoc()); 4969 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 4970 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 4971 IndexExpr->getLocStart()); 4972 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc)) 4973 return; 4974 } 4975 } 4976 4977 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 4978 if (ASE) 4979 DiagID = diag::warn_array_index_exceeds_bounds; 4980 4981 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4982 PDiag(DiagID) << index.toString(10, true) 4983 << size.toString(10, true) 4984 << (unsigned)size.getLimitedValue(~0U) 4985 << IndexExpr->getSourceRange()); 4986 } else { 4987 unsigned DiagID = diag::warn_array_index_precedes_bounds; 4988 if (!ASE) { 4989 DiagID = diag::warn_ptr_arith_precedes_bounds; 4990 if (index.isNegative()) index = -index; 4991 } 4992 4993 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4994 PDiag(DiagID) << index.toString(10, true) 4995 << IndexExpr->getSourceRange()); 4996 } 4997 4998 if (!ND) { 4999 // Try harder to find a NamedDecl to point at in the note. 5000 while (const ArraySubscriptExpr *ASE = 5001 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 5002 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 5003 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 5004 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 5005 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 5006 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 5007 } 5008 5009 if (ND) 5010 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 5011 PDiag(diag::note_array_index_out_of_bounds) 5012 << ND->getDeclName()); 5013} 5014 5015void Sema::CheckArrayAccess(const Expr *expr) { 5016 int AllowOnePastEnd = 0; 5017 while (expr) { 5018 expr = expr->IgnoreParenImpCasts(); 5019 switch (expr->getStmtClass()) { 5020 case Stmt::ArraySubscriptExprClass: { 5021 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 5022 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 5023 AllowOnePastEnd > 0); 5024 return; 5025 } 5026 case Stmt::UnaryOperatorClass: { 5027 // Only unwrap the * and & unary operators 5028 const UnaryOperator *UO = cast<UnaryOperator>(expr); 5029 expr = UO->getSubExpr(); 5030 switch (UO->getOpcode()) { 5031 case UO_AddrOf: 5032 AllowOnePastEnd++; 5033 break; 5034 case UO_Deref: 5035 AllowOnePastEnd--; 5036 break; 5037 default: 5038 return; 5039 } 5040 break; 5041 } 5042 case Stmt::ConditionalOperatorClass: { 5043 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 5044 if (const Expr *lhs = cond->getLHS()) 5045 CheckArrayAccess(lhs); 5046 if (const Expr *rhs = cond->getRHS()) 5047 CheckArrayAccess(rhs); 5048 return; 5049 } 5050 default: 5051 return; 5052 } 5053 } 5054} 5055 5056//===--- CHECK: Objective-C retain cycles ----------------------------------// 5057 5058namespace { 5059 struct RetainCycleOwner { 5060 RetainCycleOwner() : Variable(0), Indirect(false) {} 5061 VarDecl *Variable; 5062 SourceRange Range; 5063 SourceLocation Loc; 5064 bool Indirect; 5065 5066 void setLocsFrom(Expr *e) { 5067 Loc = e->getExprLoc(); 5068 Range = e->getSourceRange(); 5069 } 5070 }; 5071} 5072 5073/// Consider whether capturing the given variable can possibly lead to 5074/// a retain cycle. 5075static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 5076 // In ARC, it's captured strongly iff the variable has __strong 5077 // lifetime. In MRR, it's captured strongly if the variable is 5078 // __block and has an appropriate type. 5079 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 5080 return false; 5081 5082 owner.Variable = var; 5083 owner.setLocsFrom(ref); 5084 return true; 5085} 5086 5087static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 5088 while (true) { 5089 e = e->IgnoreParens(); 5090 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 5091 switch (cast->getCastKind()) { 5092 case CK_BitCast: 5093 case CK_LValueBitCast: 5094 case CK_LValueToRValue: 5095 case CK_ARCReclaimReturnedObject: 5096 e = cast->getSubExpr(); 5097 continue; 5098 5099 default: 5100 return false; 5101 } 5102 } 5103 5104 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 5105 ObjCIvarDecl *ivar = ref->getDecl(); 5106 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 5107 return false; 5108 5109 // Try to find a retain cycle in the base. 5110 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 5111 return false; 5112 5113 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 5114 owner.Indirect = true; 5115 return true; 5116 } 5117 5118 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 5119 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 5120 if (!var) return false; 5121 return considerVariable(var, ref, owner); 5122 } 5123 5124 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 5125 if (member->isArrow()) return false; 5126 5127 // Don't count this as an indirect ownership. 5128 e = member->getBase(); 5129 continue; 5130 } 5131 5132 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 5133 // Only pay attention to pseudo-objects on property references. 5134 ObjCPropertyRefExpr *pre 5135 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 5136 ->IgnoreParens()); 5137 if (!pre) return false; 5138 if (pre->isImplicitProperty()) return false; 5139 ObjCPropertyDecl *property = pre->getExplicitProperty(); 5140 if (!property->isRetaining() && 5141 !(property->getPropertyIvarDecl() && 5142 property->getPropertyIvarDecl()->getType() 5143 .getObjCLifetime() == Qualifiers::OCL_Strong)) 5144 return false; 5145 5146 owner.Indirect = true; 5147 if (pre->isSuperReceiver()) { 5148 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 5149 if (!owner.Variable) 5150 return false; 5151 owner.Loc = pre->getLocation(); 5152 owner.Range = pre->getSourceRange(); 5153 return true; 5154 } 5155 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 5156 ->getSourceExpr()); 5157 continue; 5158 } 5159 5160 // Array ivars? 5161 5162 return false; 5163 } 5164} 5165 5166namespace { 5167 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 5168 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 5169 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 5170 Variable(variable), Capturer(0) {} 5171 5172 VarDecl *Variable; 5173 Expr *Capturer; 5174 5175 void VisitDeclRefExpr(DeclRefExpr *ref) { 5176 if (ref->getDecl() == Variable && !Capturer) 5177 Capturer = ref; 5178 } 5179 5180 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 5181 if (Capturer) return; 5182 Visit(ref->getBase()); 5183 if (Capturer && ref->isFreeIvar()) 5184 Capturer = ref; 5185 } 5186 5187 void VisitBlockExpr(BlockExpr *block) { 5188 // Look inside nested blocks 5189 if (block->getBlockDecl()->capturesVariable(Variable)) 5190 Visit(block->getBlockDecl()->getBody()); 5191 } 5192 }; 5193} 5194 5195/// Check whether the given argument is a block which captures a 5196/// variable. 5197static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 5198 assert(owner.Variable && owner.Loc.isValid()); 5199 5200 e = e->IgnoreParenCasts(); 5201 BlockExpr *block = dyn_cast<BlockExpr>(e); 5202 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 5203 return 0; 5204 5205 FindCaptureVisitor visitor(S.Context, owner.Variable); 5206 visitor.Visit(block->getBlockDecl()->getBody()); 5207 return visitor.Capturer; 5208} 5209 5210static void diagnoseRetainCycle(Sema &S, Expr *capturer, 5211 RetainCycleOwner &owner) { 5212 assert(capturer); 5213 assert(owner.Variable && owner.Loc.isValid()); 5214 5215 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 5216 << owner.Variable << capturer->getSourceRange(); 5217 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 5218 << owner.Indirect << owner.Range; 5219} 5220 5221/// Check for a keyword selector that starts with the word 'add' or 5222/// 'set'. 5223static bool isSetterLikeSelector(Selector sel) { 5224 if (sel.isUnarySelector()) return false; 5225 5226 StringRef str = sel.getNameForSlot(0); 5227 while (!str.empty() && str.front() == '_') str = str.substr(1); 5228 if (str.startswith("set")) 5229 str = str.substr(3); 5230 else if (str.startswith("add")) { 5231 // Specially whitelist 'addOperationWithBlock:'. 5232 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 5233 return false; 5234 str = str.substr(3); 5235 } 5236 else 5237 return false; 5238 5239 if (str.empty()) return true; 5240 return !islower(str.front()); 5241} 5242 5243/// Check a message send to see if it's likely to cause a retain cycle. 5244void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 5245 // Only check instance methods whose selector looks like a setter. 5246 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 5247 return; 5248 5249 // Try to find a variable that the receiver is strongly owned by. 5250 RetainCycleOwner owner; 5251 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 5252 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 5253 return; 5254 } else { 5255 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 5256 owner.Variable = getCurMethodDecl()->getSelfDecl(); 5257 owner.Loc = msg->getSuperLoc(); 5258 owner.Range = msg->getSuperLoc(); 5259 } 5260 5261 // Check whether the receiver is captured by any of the arguments. 5262 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 5263 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 5264 return diagnoseRetainCycle(*this, capturer, owner); 5265} 5266 5267/// Check a property assign to see if it's likely to cause a retain cycle. 5268void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 5269 RetainCycleOwner owner; 5270 if (!findRetainCycleOwner(*this, receiver, owner)) 5271 return; 5272 5273 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 5274 diagnoseRetainCycle(*this, capturer, owner); 5275} 5276 5277bool Sema::checkUnsafeAssigns(SourceLocation Loc, 5278 QualType LHS, Expr *RHS) { 5279 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 5280 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 5281 return false; 5282 // strip off any implicit cast added to get to the one arc-specific 5283 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5284 if (cast->getCastKind() == CK_ARCConsumeObject) { 5285 Diag(Loc, diag::warn_arc_retained_assign) 5286 << (LT == Qualifiers::OCL_ExplicitNone) << 1 5287 << RHS->getSourceRange(); 5288 return true; 5289 } 5290 RHS = cast->getSubExpr(); 5291 } 5292 return false; 5293} 5294 5295void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 5296 Expr *LHS, Expr *RHS) { 5297 QualType LHSType; 5298 // PropertyRef on LHS type need be directly obtained from 5299 // its declaration as it has a PsuedoType. 5300 ObjCPropertyRefExpr *PRE 5301 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 5302 if (PRE && !PRE->isImplicitProperty()) { 5303 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5304 if (PD) 5305 LHSType = PD->getType(); 5306 } 5307 5308 if (LHSType.isNull()) 5309 LHSType = LHS->getType(); 5310 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 5311 return; 5312 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 5313 // FIXME. Check for other life times. 5314 if (LT != Qualifiers::OCL_None) 5315 return; 5316 5317 if (PRE) { 5318 if (PRE->isImplicitProperty()) 5319 return; 5320 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5321 if (!PD) 5322 return; 5323 5324 unsigned Attributes = PD->getPropertyAttributes(); 5325 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 5326 // when 'assign' attribute was not explicitly specified 5327 // by user, ignore it and rely on property type itself 5328 // for lifetime info. 5329 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 5330 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 5331 LHSType->isObjCRetainableType()) 5332 return; 5333 5334 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5335 if (cast->getCastKind() == CK_ARCConsumeObject) { 5336 Diag(Loc, diag::warn_arc_retained_property_assign) 5337 << RHS->getSourceRange(); 5338 return; 5339 } 5340 RHS = cast->getSubExpr(); 5341 } 5342 } 5343 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 5344 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5345 if (cast->getCastKind() == CK_ARCConsumeObject) { 5346 Diag(Loc, diag::warn_arc_retained_assign) 5347 << 0 << 0<< RHS->getSourceRange(); 5348 return; 5349 } 5350 RHS = cast->getSubExpr(); 5351 } 5352 } 5353 } 5354} 5355 5356//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 5357 5358namespace { 5359bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 5360 SourceLocation StmtLoc, 5361 const NullStmt *Body) { 5362 // Do not warn if the body is a macro that expands to nothing, e.g: 5363 // 5364 // #define CALL(x) 5365 // if (condition) 5366 // CALL(0); 5367 // 5368 if (Body->hasLeadingEmptyMacro()) 5369 return false; 5370 5371 // Get line numbers of statement and body. 5372 bool StmtLineInvalid; 5373 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 5374 &StmtLineInvalid); 5375 if (StmtLineInvalid) 5376 return false; 5377 5378 bool BodyLineInvalid; 5379 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 5380 &BodyLineInvalid); 5381 if (BodyLineInvalid) 5382 return false; 5383 5384 // Warn if null statement and body are on the same line. 5385 if (StmtLine != BodyLine) 5386 return false; 5387 5388 return true; 5389} 5390} // Unnamed namespace 5391 5392void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 5393 const Stmt *Body, 5394 unsigned DiagID) { 5395 // Since this is a syntactic check, don't emit diagnostic for template 5396 // instantiations, this just adds noise. 5397 if (CurrentInstantiationScope) 5398 return; 5399 5400 // The body should be a null statement. 5401 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5402 if (!NBody) 5403 return; 5404 5405 // Do the usual checks. 5406 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5407 return; 5408 5409 Diag(NBody->getSemiLoc(), DiagID); 5410 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5411} 5412 5413void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 5414 const Stmt *PossibleBody) { 5415 assert(!CurrentInstantiationScope); // Ensured by caller 5416 5417 SourceLocation StmtLoc; 5418 const Stmt *Body; 5419 unsigned DiagID; 5420 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 5421 StmtLoc = FS->getRParenLoc(); 5422 Body = FS->getBody(); 5423 DiagID = diag::warn_empty_for_body; 5424 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 5425 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 5426 Body = WS->getBody(); 5427 DiagID = diag::warn_empty_while_body; 5428 } else 5429 return; // Neither `for' nor `while'. 5430 5431 // The body should be a null statement. 5432 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5433 if (!NBody) 5434 return; 5435 5436 // Skip expensive checks if diagnostic is disabled. 5437 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) == 5438 DiagnosticsEngine::Ignored) 5439 return; 5440 5441 // Do the usual checks. 5442 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5443 return; 5444 5445 // `for(...);' and `while(...);' are popular idioms, so in order to keep 5446 // noise level low, emit diagnostics only if for/while is followed by a 5447 // CompoundStmt, e.g.: 5448 // for (int i = 0; i < n; i++); 5449 // { 5450 // a(i); 5451 // } 5452 // or if for/while is followed by a statement with more indentation 5453 // than for/while itself: 5454 // for (int i = 0; i < n; i++); 5455 // a(i); 5456 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 5457 if (!ProbableTypo) { 5458 bool BodyColInvalid; 5459 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 5460 PossibleBody->getLocStart(), 5461 &BodyColInvalid); 5462 if (BodyColInvalid) 5463 return; 5464 5465 bool StmtColInvalid; 5466 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 5467 S->getLocStart(), 5468 &StmtColInvalid); 5469 if (StmtColInvalid) 5470 return; 5471 5472 if (BodyCol > StmtCol) 5473 ProbableTypo = true; 5474 } 5475 5476 if (ProbableTypo) { 5477 Diag(NBody->getSemiLoc(), DiagID); 5478 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5479 } 5480} 5481 5482//===--- Layout compatibility ----------------------------------------------// 5483 5484namespace { 5485 5486bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 5487 5488/// \brief Check if two enumeration types are layout-compatible. 5489bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 5490 // C++11 [dcl.enum] p8: 5491 // Two enumeration types are layout-compatible if they have the same 5492 // underlying type. 5493 return ED1->isComplete() && ED2->isComplete() && 5494 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 5495} 5496 5497/// \brief Check if two fields are layout-compatible. 5498bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 5499 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 5500 return false; 5501 5502 if (Field1->isBitField() != Field2->isBitField()) 5503 return false; 5504 5505 if (Field1->isBitField()) { 5506 // Make sure that the bit-fields are the same length. 5507 unsigned Bits1 = Field1->getBitWidthValue(C); 5508 unsigned Bits2 = Field2->getBitWidthValue(C); 5509 5510 if (Bits1 != Bits2) 5511 return false; 5512 } 5513 5514 return true; 5515} 5516 5517/// \brief Check if two standard-layout structs are layout-compatible. 5518/// (C++11 [class.mem] p17) 5519bool isLayoutCompatibleStruct(ASTContext &C, 5520 RecordDecl *RD1, 5521 RecordDecl *RD2) { 5522 // If both records are C++ classes, check that base classes match. 5523 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 5524 // If one of records is a CXXRecordDecl we are in C++ mode, 5525 // thus the other one is a CXXRecordDecl, too. 5526 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 5527 // Check number of base classes. 5528 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 5529 return false; 5530 5531 // Check the base classes. 5532 for (CXXRecordDecl::base_class_const_iterator 5533 Base1 = D1CXX->bases_begin(), 5534 BaseEnd1 = D1CXX->bases_end(), 5535 Base2 = D2CXX->bases_begin(); 5536 Base1 != BaseEnd1; 5537 ++Base1, ++Base2) { 5538 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 5539 return false; 5540 } 5541 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 5542 // If only RD2 is a C++ class, it should have zero base classes. 5543 if (D2CXX->getNumBases() > 0) 5544 return false; 5545 } 5546 5547 // Check the fields. 5548 RecordDecl::field_iterator Field2 = RD2->field_begin(), 5549 Field2End = RD2->field_end(), 5550 Field1 = RD1->field_begin(), 5551 Field1End = RD1->field_end(); 5552 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 5553 if (!isLayoutCompatible(C, *Field1, *Field2)) 5554 return false; 5555 } 5556 if (Field1 != Field1End || Field2 != Field2End) 5557 return false; 5558 5559 return true; 5560} 5561 5562/// \brief Check if two standard-layout unions are layout-compatible. 5563/// (C++11 [class.mem] p18) 5564bool isLayoutCompatibleUnion(ASTContext &C, 5565 RecordDecl *RD1, 5566 RecordDecl *RD2) { 5567 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 5568 for (RecordDecl::field_iterator Field2 = RD2->field_begin(), 5569 Field2End = RD2->field_end(); 5570 Field2 != Field2End; ++Field2) { 5571 UnmatchedFields.insert(*Field2); 5572 } 5573 5574 for (RecordDecl::field_iterator Field1 = RD1->field_begin(), 5575 Field1End = RD1->field_end(); 5576 Field1 != Field1End; ++Field1) { 5577 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 5578 I = UnmatchedFields.begin(), 5579 E = UnmatchedFields.end(); 5580 5581 for ( ; I != E; ++I) { 5582 if (isLayoutCompatible(C, *Field1, *I)) { 5583 bool Result = UnmatchedFields.erase(*I); 5584 (void) Result; 5585 assert(Result); 5586 break; 5587 } 5588 } 5589 if (I == E) 5590 return false; 5591 } 5592 5593 return UnmatchedFields.empty(); 5594} 5595 5596bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 5597 if (RD1->isUnion() != RD2->isUnion()) 5598 return false; 5599 5600 if (RD1->isUnion()) 5601 return isLayoutCompatibleUnion(C, RD1, RD2); 5602 else 5603 return isLayoutCompatibleStruct(C, RD1, RD2); 5604} 5605 5606/// \brief Check if two types are layout-compatible in C++11 sense. 5607bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 5608 if (T1.isNull() || T2.isNull()) 5609 return false; 5610 5611 // C++11 [basic.types] p11: 5612 // If two types T1 and T2 are the same type, then T1 and T2 are 5613 // layout-compatible types. 5614 if (C.hasSameType(T1, T2)) 5615 return true; 5616 5617 T1 = T1.getCanonicalType().getUnqualifiedType(); 5618 T2 = T2.getCanonicalType().getUnqualifiedType(); 5619 5620 const Type::TypeClass TC1 = T1->getTypeClass(); 5621 const Type::TypeClass TC2 = T2->getTypeClass(); 5622 5623 if (TC1 != TC2) 5624 return false; 5625 5626 if (TC1 == Type::Enum) { 5627 return isLayoutCompatible(C, 5628 cast<EnumType>(T1)->getDecl(), 5629 cast<EnumType>(T2)->getDecl()); 5630 } else if (TC1 == Type::Record) { 5631 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 5632 return false; 5633 5634 return isLayoutCompatible(C, 5635 cast<RecordType>(T1)->getDecl(), 5636 cast<RecordType>(T2)->getDecl()); 5637 } 5638 5639 return false; 5640} 5641} 5642 5643//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 5644 5645namespace { 5646/// \brief Given a type tag expression find the type tag itself. 5647/// 5648/// \param TypeExpr Type tag expression, as it appears in user's code. 5649/// 5650/// \param VD Declaration of an identifier that appears in a type tag. 5651/// 5652/// \param MagicValue Type tag magic value. 5653bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 5654 const ValueDecl **VD, uint64_t *MagicValue) { 5655 while(true) { 5656 if (!TypeExpr) 5657 return false; 5658 5659 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 5660 5661 switch (TypeExpr->getStmtClass()) { 5662 case Stmt::UnaryOperatorClass: { 5663 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 5664 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 5665 TypeExpr = UO->getSubExpr(); 5666 continue; 5667 } 5668 return false; 5669 } 5670 5671 case Stmt::DeclRefExprClass: { 5672 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 5673 *VD = DRE->getDecl(); 5674 return true; 5675 } 5676 5677 case Stmt::IntegerLiteralClass: { 5678 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 5679 llvm::APInt MagicValueAPInt = IL->getValue(); 5680 if (MagicValueAPInt.getActiveBits() <= 64) { 5681 *MagicValue = MagicValueAPInt.getZExtValue(); 5682 return true; 5683 } else 5684 return false; 5685 } 5686 5687 case Stmt::BinaryConditionalOperatorClass: 5688 case Stmt::ConditionalOperatorClass: { 5689 const AbstractConditionalOperator *ACO = 5690 cast<AbstractConditionalOperator>(TypeExpr); 5691 bool Result; 5692 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 5693 if (Result) 5694 TypeExpr = ACO->getTrueExpr(); 5695 else 5696 TypeExpr = ACO->getFalseExpr(); 5697 continue; 5698 } 5699 return false; 5700 } 5701 5702 case Stmt::BinaryOperatorClass: { 5703 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 5704 if (BO->getOpcode() == BO_Comma) { 5705 TypeExpr = BO->getRHS(); 5706 continue; 5707 } 5708 return false; 5709 } 5710 5711 default: 5712 return false; 5713 } 5714 } 5715} 5716 5717/// \brief Retrieve the C type corresponding to type tag TypeExpr. 5718/// 5719/// \param TypeExpr Expression that specifies a type tag. 5720/// 5721/// \param MagicValues Registered magic values. 5722/// 5723/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 5724/// kind. 5725/// 5726/// \param TypeInfo Information about the corresponding C type. 5727/// 5728/// \returns true if the corresponding C type was found. 5729bool GetMatchingCType( 5730 const IdentifierInfo *ArgumentKind, 5731 const Expr *TypeExpr, const ASTContext &Ctx, 5732 const llvm::DenseMap<Sema::TypeTagMagicValue, 5733 Sema::TypeTagData> *MagicValues, 5734 bool &FoundWrongKind, 5735 Sema::TypeTagData &TypeInfo) { 5736 FoundWrongKind = false; 5737 5738 // Variable declaration that has type_tag_for_datatype attribute. 5739 const ValueDecl *VD = NULL; 5740 5741 uint64_t MagicValue; 5742 5743 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 5744 return false; 5745 5746 if (VD) { 5747 for (specific_attr_iterator<TypeTagForDatatypeAttr> 5748 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(), 5749 E = VD->specific_attr_end<TypeTagForDatatypeAttr>(); 5750 I != E; ++I) { 5751 if (I->getArgumentKind() != ArgumentKind) { 5752 FoundWrongKind = true; 5753 return false; 5754 } 5755 TypeInfo.Type = I->getMatchingCType(); 5756 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 5757 TypeInfo.MustBeNull = I->getMustBeNull(); 5758 return true; 5759 } 5760 return false; 5761 } 5762 5763 if (!MagicValues) 5764 return false; 5765 5766 llvm::DenseMap<Sema::TypeTagMagicValue, 5767 Sema::TypeTagData>::const_iterator I = 5768 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 5769 if (I == MagicValues->end()) 5770 return false; 5771 5772 TypeInfo = I->second; 5773 return true; 5774} 5775} // unnamed namespace 5776 5777void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 5778 uint64_t MagicValue, QualType Type, 5779 bool LayoutCompatible, 5780 bool MustBeNull) { 5781 if (!TypeTagForDatatypeMagicValues) 5782 TypeTagForDatatypeMagicValues.reset( 5783 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 5784 5785 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 5786 (*TypeTagForDatatypeMagicValues)[Magic] = 5787 TypeTagData(Type, LayoutCompatible, MustBeNull); 5788} 5789 5790namespace { 5791bool IsSameCharType(QualType T1, QualType T2) { 5792 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 5793 if (!BT1) 5794 return false; 5795 5796 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 5797 if (!BT2) 5798 return false; 5799 5800 BuiltinType::Kind T1Kind = BT1->getKind(); 5801 BuiltinType::Kind T2Kind = BT2->getKind(); 5802 5803 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 5804 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 5805 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 5806 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 5807} 5808} // unnamed namespace 5809 5810void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 5811 const Expr * const *ExprArgs) { 5812 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 5813 bool IsPointerAttr = Attr->getIsPointer(); 5814 5815 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 5816 bool FoundWrongKind; 5817 TypeTagData TypeInfo; 5818 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 5819 TypeTagForDatatypeMagicValues.get(), 5820 FoundWrongKind, TypeInfo)) { 5821 if (FoundWrongKind) 5822 Diag(TypeTagExpr->getExprLoc(), 5823 diag::warn_type_tag_for_datatype_wrong_kind) 5824 << TypeTagExpr->getSourceRange(); 5825 return; 5826 } 5827 5828 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 5829 if (IsPointerAttr) { 5830 // Skip implicit cast of pointer to `void *' (as a function argument). 5831 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 5832 if (ICE->getType()->isVoidPointerType()) 5833 ArgumentExpr = ICE->getSubExpr(); 5834 } 5835 QualType ArgumentType = ArgumentExpr->getType(); 5836 5837 // Passing a `void*' pointer shouldn't trigger a warning. 5838 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 5839 return; 5840 5841 if (TypeInfo.MustBeNull) { 5842 // Type tag with matching void type requires a null pointer. 5843 if (!ArgumentExpr->isNullPointerConstant(Context, 5844 Expr::NPC_ValueDependentIsNotNull)) { 5845 Diag(ArgumentExpr->getExprLoc(), 5846 diag::warn_type_safety_null_pointer_required) 5847 << ArgumentKind->getName() 5848 << ArgumentExpr->getSourceRange() 5849 << TypeTagExpr->getSourceRange(); 5850 } 5851 return; 5852 } 5853 5854 QualType RequiredType = TypeInfo.Type; 5855 if (IsPointerAttr) 5856 RequiredType = Context.getPointerType(RequiredType); 5857 5858 bool mismatch = false; 5859 if (!TypeInfo.LayoutCompatible) { 5860 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 5861 5862 // C++11 [basic.fundamental] p1: 5863 // Plain char, signed char, and unsigned char are three distinct types. 5864 // 5865 // But we treat plain `char' as equivalent to `signed char' or `unsigned 5866 // char' depending on the current char signedness mode. 5867 if (mismatch) 5868 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 5869 RequiredType->getPointeeType())) || 5870 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 5871 mismatch = false; 5872 } else 5873 if (IsPointerAttr) 5874 mismatch = !isLayoutCompatible(Context, 5875 ArgumentType->getPointeeType(), 5876 RequiredType->getPointeeType()); 5877 else 5878 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 5879 5880 if (mismatch) 5881 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 5882 << ArgumentType << ArgumentKind->getName() 5883 << TypeInfo.LayoutCompatible << RequiredType 5884 << ArgumentExpr->getSourceRange() 5885 << TypeTagExpr->getSourceRange(); 5886} 5887 5888