SemaChecking.cpp revision 909a70d8a185f701c20bacc3c76f8f5979cbbc7c
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// The LLVM Compiler Infrastructure 45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source 65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details. 75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===// 95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file implements extra semantic analysis beyond what is enforced 115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// by the C type system. 12f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)// 131320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//===----------------------------------------------------------------------===// 145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/Sema.h" 165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/SemaInternal.h" 175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/ScopeInfo.h" 18f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/Analysis/Analyses/FormatString.h" 19f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/AST/ASTContext.h" 20f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/AST/CharUnits.h" 21f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/AST/DeclCXX.h" 22f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/AST/DeclObjC.h" 235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/ExprCXX.h" 245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/ExprObjC.h" 255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclObjC.h" 265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/StmtCXX.h" 275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/StmtObjC.h" 285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Lex/Preprocessor.h" 295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/BitVector.h" 305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/STLExtras.h" 315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/raw_ostream.h" 325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/TargetBuiltins.h" 335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/TargetInfo.h" 345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/ConvertUTF.h" 355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <limits> 365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang; 375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace sema; 385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) unsigned ByteNo) const { 415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) PP.getLangOptions(), PP.getTargetInfo()); 435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// CheckablePrintfAttr - does a function call have a "printf" attribute 475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// and arguments that merit checking? 485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (Format->getType() == "printf") return true; 505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (Format->getType() == "printf0") { 515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // printf0 allows null "format" string; if so don't check format/args 525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) unsigned format_idx = Format->getFormatIdx() - 1; 535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // Does the index refer to the implicit object argument? 545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (isa<CXXMemberCallExpr>(TheCall)) { 555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (format_idx == 0) 565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return false; 575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) --format_idx; 585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 59a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles) if (format_idx < TheCall->getNumArgs()) { 60a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles) Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) if (!Format->isNullPointerConstant(Context, 625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) Expr::NPC_ValueDependentIsNull)) 635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return true; 645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) } 665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return false; 675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// Checks that a call expression's argument count is the desired number. 705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// This is useful when doing custom type-checking. Returns true on error. 715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 72f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) unsigned argCount = call->getNumArgs(); 73f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) if (argCount == desiredArgCount) return false; 745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 75f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) if (argCount < desiredArgCount) 76f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) << 0 /*function call*/ << desiredArgCount << argCount 785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) << call->getSourceRange(); 79a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles) 805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // Highlight all the excess arguments. 815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) call->getArg(argCount - 1)->getLocEnd()); 835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) << 0 /*function call*/ << desiredArgCount << argCount 865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) << call->getArg(1)->getSourceRange(); 875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ExprResult 90f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ExprResult TheCallResult(Owned(TheCall)); 925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) // Find out if any arguments are required to be integer constant expressions. 945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) unsigned ICEArguments = 0; 955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) ASTContext::GetBuiltinTypeError Error; 96 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 97 if (Error != ASTContext::GE_None) 98 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 99 100 // If any arguments are required to be ICE's, check and diagnose. 101 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 102 // Skip arguments not required to be ICE's. 103 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 104 105 llvm::APSInt Result; 106 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 107 return true; 108 ICEArguments &= ~(1 << ArgNo); 109 } 110 111 switch (BuiltinID) { 112 case Builtin::BI__builtin___CFStringMakeConstantString: 113 assert(TheCall->getNumArgs() == 1 && 114 "Wrong # arguments to builtin CFStringMakeConstantString"); 115 if (CheckObjCString(TheCall->getArg(0))) 116 return ExprError(); 117 break; 118 case Builtin::BI__builtin_stdarg_start: 119 case Builtin::BI__builtin_va_start: 120 if (SemaBuiltinVAStart(TheCall)) 121 return ExprError(); 122 break; 123 case Builtin::BI__builtin_isgreater: 124 case Builtin::BI__builtin_isgreaterequal: 125 case Builtin::BI__builtin_isless: 126 case Builtin::BI__builtin_islessequal: 127 case Builtin::BI__builtin_islessgreater: 128 case Builtin::BI__builtin_isunordered: 129 if (SemaBuiltinUnorderedCompare(TheCall)) 130 return ExprError(); 131 break; 132 case Builtin::BI__builtin_fpclassify: 133 if (SemaBuiltinFPClassification(TheCall, 6)) 134 return ExprError(); 135 break; 136 case Builtin::BI__builtin_isfinite: 137 case Builtin::BI__builtin_isinf: 138 case Builtin::BI__builtin_isinf_sign: 139 case Builtin::BI__builtin_isnan: 140 case Builtin::BI__builtin_isnormal: 141 if (SemaBuiltinFPClassification(TheCall, 1)) 142 return ExprError(); 143 break; 144 case Builtin::BI__builtin_shufflevector: 145 return SemaBuiltinShuffleVector(TheCall); 146 // TheCall will be freed by the smart pointer here, but that's fine, since 147 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 148 case Builtin::BI__builtin_prefetch: 149 if (SemaBuiltinPrefetch(TheCall)) 150 return ExprError(); 151 break; 152 case Builtin::BI__builtin_object_size: 153 if (SemaBuiltinObjectSize(TheCall)) 154 return ExprError(); 155 break; 156 case Builtin::BI__builtin_longjmp: 157 if (SemaBuiltinLongjmp(TheCall)) 158 return ExprError(); 159 break; 160 161 case Builtin::BI__builtin_classify_type: 162 if (checkArgCount(*this, TheCall, 1)) return true; 163 TheCall->setType(Context.IntTy); 164 break; 165 case Builtin::BI__builtin_constant_p: 166 if (checkArgCount(*this, TheCall, 1)) return true; 167 TheCall->setType(Context.IntTy); 168 break; 169 case Builtin::BI__sync_fetch_and_add: 170 case Builtin::BI__sync_fetch_and_sub: 171 case Builtin::BI__sync_fetch_and_or: 172 case Builtin::BI__sync_fetch_and_and: 173 case Builtin::BI__sync_fetch_and_xor: 174 case Builtin::BI__sync_add_and_fetch: 175 case Builtin::BI__sync_sub_and_fetch: 176 case Builtin::BI__sync_and_and_fetch: 177 case Builtin::BI__sync_or_and_fetch: 178 case Builtin::BI__sync_xor_and_fetch: 179 case Builtin::BI__sync_val_compare_and_swap: 180 case Builtin::BI__sync_bool_compare_and_swap: 181 case Builtin::BI__sync_lock_test_and_set: 182 case Builtin::BI__sync_lock_release: 183 return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 184 } 185 186 // Since the target specific builtins for each arch overlap, only check those 187 // of the arch we are compiling for. 188 if (BuiltinID >= Builtin::FirstTSBuiltin) { 189 switch (Context.Target.getTriple().getArch()) { 190 case llvm::Triple::arm: 191 case llvm::Triple::thumb: 192 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 193 return ExprError(); 194 break; 195 default: 196 break; 197 } 198 } 199 200 return move(TheCallResult); 201} 202 203// Get the valid immediate range for the specified NEON type code. 204static unsigned RFT(unsigned t, bool shift = false) { 205 bool quad = t & 0x10; 206 207 switch (t & 0x7) { 208 case 0: // i8 209 return shift ? 7 : (8 << (int)quad) - 1; 210 case 1: // i16 211 return shift ? 15 : (4 << (int)quad) - 1; 212 case 2: // i32 213 return shift ? 31 : (2 << (int)quad) - 1; 214 case 3: // i64 215 return shift ? 63 : (1 << (int)quad) - 1; 216 case 4: // f32 217 assert(!shift && "cannot shift float types!"); 218 return (2 << (int)quad) - 1; 219 case 5: // poly8 220 return shift ? 7 : (8 << (int)quad) - 1; 221 case 6: // poly16 222 return shift ? 15 : (4 << (int)quad) - 1; 223 case 7: // float16 224 assert(!shift && "cannot shift float types!"); 225 return (4 << (int)quad) - 1; 226 } 227 return 0; 228} 229 230bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 231 llvm::APSInt Result; 232 233 unsigned mask = 0; 234 unsigned TV = 0; 235 switch (BuiltinID) { 236#define GET_NEON_OVERLOAD_CHECK 237#include "clang/Basic/arm_neon.inc" 238#undef GET_NEON_OVERLOAD_CHECK 239 } 240 241 // For NEON intrinsics which are overloaded on vector element type, validate 242 // the immediate which specifies which variant to emit. 243 if (mask) { 244 unsigned ArgNo = TheCall->getNumArgs()-1; 245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 246 return true; 247 248 TV = Result.getLimitedValue(32); 249 if ((TV > 31) || (mask & (1 << TV)) == 0) 250 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 251 << TheCall->getArg(ArgNo)->getSourceRange(); 252 } 253 254 // For NEON intrinsics which take an immediate value as part of the 255 // instruction, range check them here. 256 unsigned i = 0, l = 0, u = 0; 257 switch (BuiltinID) { 258 default: return false; 259 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 260 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 261 case ARM::BI__builtin_arm_vcvtr_f: 262 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 263#define GET_NEON_IMMEDIATE_CHECK 264#include "clang/Basic/arm_neon.inc" 265#undef GET_NEON_IMMEDIATE_CHECK 266 }; 267 268 // Check that the immediate argument is actually a constant. 269 if (SemaBuiltinConstantArg(TheCall, i, Result)) 270 return true; 271 272 // Range check against the upper/lower values for this isntruction. 273 unsigned Val = Result.getZExtValue(); 274 if (Val < l || Val > (u + l)) 275 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 276 << l << u+l << TheCall->getArg(i)->getSourceRange(); 277 278 // FIXME: VFP Intrinsics should error if VFP not present. 279 return false; 280} 281 282/// CheckFunctionCall - Check a direct function call for various correctness 283/// and safety properties not strictly enforced by the C type system. 284bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 285 // Get the IdentifierInfo* for the called function. 286 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 287 288 // None of the checks below are needed for functions that don't have 289 // simple names (e.g., C++ conversion functions). 290 if (!FnInfo) 291 return false; 292 293 // FIXME: This mechanism should be abstracted to be less fragile and 294 // more efficient. For example, just map function ids to custom 295 // handlers. 296 297 // Printf and scanf checking. 298 for (specific_attr_iterator<FormatAttr> 299 i = FDecl->specific_attr_begin<FormatAttr>(), 300 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 301 302 const FormatAttr *Format = *i; 303 const bool b = Format->getType() == "scanf"; 304 if (b || CheckablePrintfAttr(Format, TheCall)) { 305 bool HasVAListArg = Format->getFirstArg() == 0; 306 CheckPrintfScanfArguments(TheCall, HasVAListArg, 307 Format->getFormatIdx() - 1, 308 HasVAListArg ? 0 : Format->getFirstArg() - 1, 309 !b); 310 } 311 } 312 313 for (specific_attr_iterator<NonNullAttr> 314 i = FDecl->specific_attr_begin<NonNullAttr>(), 315 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 316 CheckNonNullArguments(*i, TheCall->getArgs(), 317 TheCall->getCallee()->getLocStart()); 318 } 319 320 return false; 321} 322 323bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 324 // Printf checking. 325 const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 326 if (!Format) 327 return false; 328 329 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 330 if (!V) 331 return false; 332 333 QualType Ty = V->getType(); 334 if (!Ty->isBlockPointerType()) 335 return false; 336 337 const bool b = Format->getType() == "scanf"; 338 if (!b && !CheckablePrintfAttr(Format, TheCall)) 339 return false; 340 341 bool HasVAListArg = Format->getFirstArg() == 0; 342 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 343 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b); 344 345 return false; 346} 347 348/// SemaBuiltinAtomicOverloaded - We have a call to a function like 349/// __sync_fetch_and_add, which is an overloaded function based on the pointer 350/// type of its first argument. The main ActOnCallExpr routines have already 351/// promoted the types of arguments because all of these calls are prototyped as 352/// void(...). 353/// 354/// This function goes through and does final semantic checking for these 355/// builtins, 356ExprResult 357Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 358 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 359 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 360 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 361 362 // Ensure that we have at least one argument to do type inference from. 363 if (TheCall->getNumArgs() < 1) { 364 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 365 << 0 << 1 << TheCall->getNumArgs() 366 << TheCall->getCallee()->getSourceRange(); 367 return ExprError(); 368 } 369 370 // Inspect the first argument of the atomic builtin. This should always be 371 // a pointer type, whose element is an integral scalar or pointer type. 372 // Because it is a pointer type, we don't have to worry about any implicit 373 // casts here. 374 // FIXME: We don't allow floating point scalars as input. 375 Expr *FirstArg = TheCall->getArg(0); 376 if (!FirstArg->getType()->isPointerType()) { 377 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 378 << FirstArg->getType() << FirstArg->getSourceRange(); 379 return ExprError(); 380 } 381 382 QualType ValType = 383 FirstArg->getType()->getAs<PointerType>()->getPointeeType(); 384 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 385 !ValType->isBlockPointerType()) { 386 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 387 << FirstArg->getType() << FirstArg->getSourceRange(); 388 return ExprError(); 389 } 390 391 // The majority of builtins return a value, but a few have special return 392 // types, so allow them to override appropriately below. 393 QualType ResultType = ValType; 394 395 // We need to figure out which concrete builtin this maps onto. For example, 396 // __sync_fetch_and_add with a 2 byte object turns into 397 // __sync_fetch_and_add_2. 398#define BUILTIN_ROW(x) \ 399 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 400 Builtin::BI##x##_8, Builtin::BI##x##_16 } 401 402 static const unsigned BuiltinIndices[][5] = { 403 BUILTIN_ROW(__sync_fetch_and_add), 404 BUILTIN_ROW(__sync_fetch_and_sub), 405 BUILTIN_ROW(__sync_fetch_and_or), 406 BUILTIN_ROW(__sync_fetch_and_and), 407 BUILTIN_ROW(__sync_fetch_and_xor), 408 409 BUILTIN_ROW(__sync_add_and_fetch), 410 BUILTIN_ROW(__sync_sub_and_fetch), 411 BUILTIN_ROW(__sync_and_and_fetch), 412 BUILTIN_ROW(__sync_or_and_fetch), 413 BUILTIN_ROW(__sync_xor_and_fetch), 414 415 BUILTIN_ROW(__sync_val_compare_and_swap), 416 BUILTIN_ROW(__sync_bool_compare_and_swap), 417 BUILTIN_ROW(__sync_lock_test_and_set), 418 BUILTIN_ROW(__sync_lock_release) 419 }; 420#undef BUILTIN_ROW 421 422 // Determine the index of the size. 423 unsigned SizeIndex; 424 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 425 case 1: SizeIndex = 0; break; 426 case 2: SizeIndex = 1; break; 427 case 4: SizeIndex = 2; break; 428 case 8: SizeIndex = 3; break; 429 case 16: SizeIndex = 4; break; 430 default: 431 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 432 << FirstArg->getType() << FirstArg->getSourceRange(); 433 return ExprError(); 434 } 435 436 // Each of these builtins has one pointer argument, followed by some number of 437 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 438 // that we ignore. Find out which row of BuiltinIndices to read from as well 439 // as the number of fixed args. 440 unsigned BuiltinID = FDecl->getBuiltinID(); 441 unsigned BuiltinIndex, NumFixed = 1; 442 switch (BuiltinID) { 443 default: assert(0 && "Unknown overloaded atomic builtin!"); 444 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break; 445 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break; 446 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break; 447 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break; 448 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break; 449 450 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break; 451 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break; 452 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break; 453 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break; 454 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break; 455 456 case Builtin::BI__sync_val_compare_and_swap: 457 BuiltinIndex = 10; 458 NumFixed = 2; 459 break; 460 case Builtin::BI__sync_bool_compare_and_swap: 461 BuiltinIndex = 11; 462 NumFixed = 2; 463 ResultType = Context.BoolTy; 464 break; 465 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break; 466 case Builtin::BI__sync_lock_release: 467 BuiltinIndex = 13; 468 NumFixed = 0; 469 ResultType = Context.VoidTy; 470 break; 471 } 472 473 // Now that we know how many fixed arguments we expect, first check that we 474 // have at least that many. 475 if (TheCall->getNumArgs() < 1+NumFixed) { 476 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 477 << 0 << 1+NumFixed << TheCall->getNumArgs() 478 << TheCall->getCallee()->getSourceRange(); 479 return ExprError(); 480 } 481 482 // Get the decl for the concrete builtin from this, we can tell what the 483 // concrete integer type we should convert to is. 484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 485 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 486 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 487 FunctionDecl *NewBuiltinDecl = 488 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 489 TUScope, false, DRE->getLocStart())); 490 491 // The first argument --- the pointer --- has a fixed type; we 492 // deduce the types of the rest of the arguments accordingly. Walk 493 // the remaining arguments, converting them to the deduced value type. 494 for (unsigned i = 0; i != NumFixed; ++i) { 495 Expr *Arg = TheCall->getArg(i+1); 496 497 // If the argument is an implicit cast, then there was a promotion due to 498 // "...", just remove it now. 499 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { 500 Arg = ICE->getSubExpr(); 501 ICE->setSubExpr(0); 502 TheCall->setArg(i+1, Arg); 503 } 504 505 // GCC does an implicit conversion to the pointer or integer ValType. This 506 // can fail in some cases (1i -> int**), check for this error case now. 507 CastKind Kind = CK_Invalid; 508 ExprValueKind VK = VK_RValue; 509 CXXCastPath BasePath; 510 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath)) 511 return ExprError(); 512 513 // Okay, we have something that *can* be converted to the right type. Check 514 // to see if there is a potentially weird extension going on here. This can 515 // happen when you do an atomic operation on something like an char* and 516 // pass in 42. The 42 gets converted to char. This is even more strange 517 // for things like 45.123 -> char, etc. 518 // FIXME: Do this check. 519 ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath); 520 TheCall->setArg(i+1, Arg); 521 } 522 523 // Switch the DeclRefExpr to refer to the new decl. 524 DRE->setDecl(NewBuiltinDecl); 525 DRE->setType(NewBuiltinDecl->getType()); 526 527 // Set the callee in the CallExpr. 528 // FIXME: This leaks the original parens and implicit casts. 529 Expr *PromotedCall = DRE; 530 UsualUnaryConversions(PromotedCall); 531 TheCall->setCallee(PromotedCall); 532 533 // Change the result type of the call to match the original value type. This 534 // is arbitrary, but the codegen for these builtins ins design to handle it 535 // gracefully. 536 TheCall->setType(ResultType); 537 538 return move(TheCallResult); 539} 540 541 542/// CheckObjCString - Checks that the argument to the builtin 543/// CFString constructor is correct 544/// Note: It might also make sense to do the UTF-16 conversion here (would 545/// simplify the backend). 546bool Sema::CheckObjCString(Expr *Arg) { 547 Arg = Arg->IgnoreParenCasts(); 548 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 549 550 if (!Literal || Literal->isWide()) { 551 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 552 << Arg->getSourceRange(); 553 return true; 554 } 555 556 if (Literal->containsNonAsciiOrNull()) { 557 llvm::StringRef String = Literal->getString(); 558 unsigned NumBytes = String.size(); 559 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 560 const UTF8 *FromPtr = (UTF8 *)String.data(); 561 UTF16 *ToPtr = &ToBuf[0]; 562 563 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 564 &ToPtr, ToPtr + NumBytes, 565 strictConversion); 566 // Check for conversion failure. 567 if (Result != conversionOK) 568 Diag(Arg->getLocStart(), 569 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 570 } 571 return false; 572} 573 574/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 575/// Emit an error and return true on failure, return false on success. 576bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 577 Expr *Fn = TheCall->getCallee(); 578 if (TheCall->getNumArgs() > 2) { 579 Diag(TheCall->getArg(2)->getLocStart(), 580 diag::err_typecheck_call_too_many_args) 581 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 582 << Fn->getSourceRange() 583 << SourceRange(TheCall->getArg(2)->getLocStart(), 584 (*(TheCall->arg_end()-1))->getLocEnd()); 585 return true; 586 } 587 588 if (TheCall->getNumArgs() < 2) { 589 return Diag(TheCall->getLocEnd(), 590 diag::err_typecheck_call_too_few_args_at_least) 591 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 592 } 593 594 // Determine whether the current function is variadic or not. 595 BlockScopeInfo *CurBlock = getCurBlock(); 596 bool isVariadic; 597 if (CurBlock) 598 isVariadic = CurBlock->TheDecl->isVariadic(); 599 else if (FunctionDecl *FD = getCurFunctionDecl()) 600 isVariadic = FD->isVariadic(); 601 else 602 isVariadic = getCurMethodDecl()->isVariadic(); 603 604 if (!isVariadic) { 605 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 606 return true; 607 } 608 609 // Verify that the second argument to the builtin is the last argument of the 610 // current function or method. 611 bool SecondArgIsLastNamedArgument = false; 612 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 613 614 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 615 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 616 // FIXME: This isn't correct for methods (results in bogus warning). 617 // Get the last formal in the current function. 618 const ParmVarDecl *LastArg; 619 if (CurBlock) 620 LastArg = *(CurBlock->TheDecl->param_end()-1); 621 else if (FunctionDecl *FD = getCurFunctionDecl()) 622 LastArg = *(FD->param_end()-1); 623 else 624 LastArg = *(getCurMethodDecl()->param_end()-1); 625 SecondArgIsLastNamedArgument = PV == LastArg; 626 } 627 } 628 629 if (!SecondArgIsLastNamedArgument) 630 Diag(TheCall->getArg(1)->getLocStart(), 631 diag::warn_second_parameter_of_va_start_not_last_named_argument); 632 return false; 633} 634 635/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 636/// friends. This is declared to take (...), so we have to check everything. 637bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 638 if (TheCall->getNumArgs() < 2) 639 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 640 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 641 if (TheCall->getNumArgs() > 2) 642 return Diag(TheCall->getArg(2)->getLocStart(), 643 diag::err_typecheck_call_too_many_args) 644 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 645 << SourceRange(TheCall->getArg(2)->getLocStart(), 646 (*(TheCall->arg_end()-1))->getLocEnd()); 647 648 Expr *OrigArg0 = TheCall->getArg(0); 649 Expr *OrigArg1 = TheCall->getArg(1); 650 651 // Do standard promotions between the two arguments, returning their common 652 // type. 653 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 654 655 // Make sure any conversions are pushed back into the call; this is 656 // type safe since unordered compare builtins are declared as "_Bool 657 // foo(...)". 658 TheCall->setArg(0, OrigArg0); 659 TheCall->setArg(1, OrigArg1); 660 661 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent()) 662 return false; 663 664 // If the common type isn't a real floating type, then the arguments were 665 // invalid for this operation. 666 if (!Res->isRealFloatingType()) 667 return Diag(OrigArg0->getLocStart(), 668 diag::err_typecheck_call_invalid_ordered_compare) 669 << OrigArg0->getType() << OrigArg1->getType() 670 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); 671 672 return false; 673} 674 675/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 676/// __builtin_isnan and friends. This is declared to take (...), so we have 677/// to check everything. We expect the last argument to be a floating point 678/// value. 679bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 680 if (TheCall->getNumArgs() < NumArgs) 681 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 682 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 683 if (TheCall->getNumArgs() > NumArgs) 684 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 685 diag::err_typecheck_call_too_many_args) 686 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 687 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 688 (*(TheCall->arg_end()-1))->getLocEnd()); 689 690 Expr *OrigArg = TheCall->getArg(NumArgs-1); 691 692 if (OrigArg->isTypeDependent()) 693 return false; 694 695 // This operation requires a non-_Complex floating-point number. 696 if (!OrigArg->getType()->isRealFloatingType()) 697 return Diag(OrigArg->getLocStart(), 698 diag::err_typecheck_call_invalid_unary_fp) 699 << OrigArg->getType() << OrigArg->getSourceRange(); 700 701 // If this is an implicit conversion from float -> double, remove it. 702 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 703 Expr *CastArg = Cast->getSubExpr(); 704 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 705 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 706 "promotion from float to double is the only expected cast here"); 707 Cast->setSubExpr(0); 708 TheCall->setArg(NumArgs-1, CastArg); 709 OrigArg = CastArg; 710 } 711 } 712 713 return false; 714} 715 716/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 717// This is declared to take (...), so we have to check everything. 718ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 719 if (TheCall->getNumArgs() < 2) 720 return ExprError(Diag(TheCall->getLocEnd(), 721 diag::err_typecheck_call_too_few_args_at_least) 722 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 723 << TheCall->getSourceRange()); 724 725 // Determine which of the following types of shufflevector we're checking: 726 // 1) unary, vector mask: (lhs, mask) 727 // 2) binary, vector mask: (lhs, rhs, mask) 728 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 729 QualType resType = TheCall->getArg(0)->getType(); 730 unsigned numElements = 0; 731 732 if (!TheCall->getArg(0)->isTypeDependent() && 733 !TheCall->getArg(1)->isTypeDependent()) { 734 QualType LHSType = TheCall->getArg(0)->getType(); 735 QualType RHSType = TheCall->getArg(1)->getType(); 736 737 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 738 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 739 << SourceRange(TheCall->getArg(0)->getLocStart(), 740 TheCall->getArg(1)->getLocEnd()); 741 return ExprError(); 742 } 743 744 numElements = LHSType->getAs<VectorType>()->getNumElements(); 745 unsigned numResElements = TheCall->getNumArgs() - 2; 746 747 // Check to see if we have a call with 2 vector arguments, the unary shuffle 748 // with mask. If so, verify that RHS is an integer vector type with the 749 // same number of elts as lhs. 750 if (TheCall->getNumArgs() == 2) { 751 if (!RHSType->hasIntegerRepresentation() || 752 RHSType->getAs<VectorType>()->getNumElements() != numElements) 753 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 754 << SourceRange(TheCall->getArg(1)->getLocStart(), 755 TheCall->getArg(1)->getLocEnd()); 756 numResElements = numElements; 757 } 758 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 759 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 760 << SourceRange(TheCall->getArg(0)->getLocStart(), 761 TheCall->getArg(1)->getLocEnd()); 762 return ExprError(); 763 } else if (numElements != numResElements) { 764 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 765 resType = Context.getVectorType(eltType, numResElements, 766 VectorType::GenericVector); 767 } 768 } 769 770 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 771 if (TheCall->getArg(i)->isTypeDependent() || 772 TheCall->getArg(i)->isValueDependent()) 773 continue; 774 775 llvm::APSInt Result(32); 776 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 777 return ExprError(Diag(TheCall->getLocStart(), 778 diag::err_shufflevector_nonconstant_argument) 779 << TheCall->getArg(i)->getSourceRange()); 780 781 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 782 return ExprError(Diag(TheCall->getLocStart(), 783 diag::err_shufflevector_argument_too_large) 784 << TheCall->getArg(i)->getSourceRange()); 785 } 786 787 llvm::SmallVector<Expr*, 32> exprs; 788 789 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 790 exprs.push_back(TheCall->getArg(i)); 791 TheCall->setArg(i, 0); 792 } 793 794 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 795 exprs.size(), resType, 796 TheCall->getCallee()->getLocStart(), 797 TheCall->getRParenLoc())); 798} 799 800/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 801// This is declared to take (const void*, ...) and can take two 802// optional constant int args. 803bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 804 unsigned NumArgs = TheCall->getNumArgs(); 805 806 if (NumArgs > 3) 807 return Diag(TheCall->getLocEnd(), 808 diag::err_typecheck_call_too_many_args_at_most) 809 << 0 /*function call*/ << 3 << NumArgs 810 << TheCall->getSourceRange(); 811 812 // Argument 0 is checked for us and the remaining arguments must be 813 // constant integers. 814 for (unsigned i = 1; i != NumArgs; ++i) { 815 Expr *Arg = TheCall->getArg(i); 816 817 llvm::APSInt Result; 818 if (SemaBuiltinConstantArg(TheCall, i, Result)) 819 return true; 820 821 // FIXME: gcc issues a warning and rewrites these to 0. These 822 // seems especially odd for the third argument since the default 823 // is 3. 824 if (i == 1) { 825 if (Result.getLimitedValue() > 1) 826 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 827 << "0" << "1" << Arg->getSourceRange(); 828 } else { 829 if (Result.getLimitedValue() > 3) 830 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 831 << "0" << "3" << Arg->getSourceRange(); 832 } 833 } 834 835 return false; 836} 837 838/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 839/// TheCall is a constant expression. 840bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 841 llvm::APSInt &Result) { 842 Expr *Arg = TheCall->getArg(ArgNum); 843 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 844 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 845 846 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 847 848 if (!Arg->isIntegerConstantExpr(Result, Context)) 849 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 850 << FDecl->getDeclName() << Arg->getSourceRange(); 851 852 return false; 853} 854 855/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 856/// int type). This simply type checks that type is one of the defined 857/// constants (0-3). 858// For compatability check 0-3, llvm only handles 0 and 2. 859bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 860 llvm::APSInt Result; 861 862 // Check constant-ness first. 863 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 864 return true; 865 866 Expr *Arg = TheCall->getArg(1); 867 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 868 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 869 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 870 } 871 872 return false; 873} 874 875/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 876/// This checks that val is a constant 1. 877bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 878 Expr *Arg = TheCall->getArg(1); 879 llvm::APSInt Result; 880 881 // TODO: This is less than ideal. Overload this to take a value. 882 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 883 return true; 884 885 if (Result != 1) 886 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 887 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 888 889 return false; 890} 891 892// Handle i > 1 ? "x" : "y", recursively. 893bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 894 bool HasVAListArg, 895 unsigned format_idx, unsigned firstDataArg, 896 bool isPrintf) { 897 tryAgain: 898 if (E->isTypeDependent() || E->isValueDependent()) 899 return false; 900 901 switch (E->getStmtClass()) { 902 case Stmt::BinaryConditionalOperatorClass: 903 case Stmt::ConditionalOperatorClass: { 904 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 905 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg, 906 format_idx, firstDataArg, isPrintf) 907 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg, 908 format_idx, firstDataArg, isPrintf); 909 } 910 911 case Stmt::IntegerLiteralClass: 912 // Technically -Wformat-nonliteral does not warn about this case. 913 // The behavior of printf and friends in this case is implementation 914 // dependent. Ideally if the format string cannot be null then 915 // it should have a 'nonnull' attribute in the function prototype. 916 return true; 917 918 case Stmt::ImplicitCastExprClass: { 919 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 920 goto tryAgain; 921 } 922 923 case Stmt::ParenExprClass: { 924 E = cast<ParenExpr>(E)->getSubExpr(); 925 goto tryAgain; 926 } 927 928 case Stmt::OpaqueValueExprClass: 929 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 930 E = src; 931 goto tryAgain; 932 } 933 return false; 934 935 case Stmt::PredefinedExprClass: 936 // While __func__, etc., are technically not string literals, they 937 // cannot contain format specifiers and thus are not a security 938 // liability. 939 return true; 940 941 case Stmt::DeclRefExprClass: { 942 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 943 944 // As an exception, do not flag errors for variables binding to 945 // const string literals. 946 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 947 bool isConstant = false; 948 QualType T = DR->getType(); 949 950 if (const ArrayType *AT = Context.getAsArrayType(T)) { 951 isConstant = AT->getElementType().isConstant(Context); 952 } else if (const PointerType *PT = T->getAs<PointerType>()) { 953 isConstant = T.isConstant(Context) && 954 PT->getPointeeType().isConstant(Context); 955 } 956 957 if (isConstant) { 958 if (const Expr *Init = VD->getAnyInitializer()) 959 return SemaCheckStringLiteral(Init, TheCall, 960 HasVAListArg, format_idx, firstDataArg, 961 isPrintf); 962 } 963 964 // For vprintf* functions (i.e., HasVAListArg==true), we add a 965 // special check to see if the format string is a function parameter 966 // of the function calling the printf function. If the function 967 // has an attribute indicating it is a printf-like function, then we 968 // should suppress warnings concerning non-literals being used in a call 969 // to a vprintf function. For example: 970 // 971 // void 972 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 973 // va_list ap; 974 // va_start(ap, fmt); 975 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 976 // ... 977 // 978 // 979 // FIXME: We don't have full attribute support yet, so just check to see 980 // if the argument is a DeclRefExpr that references a parameter. We'll 981 // add proper support for checking the attribute later. 982 if (HasVAListArg) 983 if (isa<ParmVarDecl>(VD)) 984 return true; 985 } 986 987 return false; 988 } 989 990 case Stmt::CallExprClass: { 991 const CallExpr *CE = cast<CallExpr>(E); 992 if (const ImplicitCastExpr *ICE 993 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 994 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 995 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 996 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 997 unsigned ArgIndex = FA->getFormatIdx(); 998 const Expr *Arg = CE->getArg(ArgIndex - 1); 999 1000 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 1001 format_idx, firstDataArg, isPrintf); 1002 } 1003 } 1004 } 1005 } 1006 1007 return false; 1008 } 1009 case Stmt::ObjCStringLiteralClass: 1010 case Stmt::StringLiteralClass: { 1011 const StringLiteral *StrE = NULL; 1012 1013 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1014 StrE = ObjCFExpr->getString(); 1015 else 1016 StrE = cast<StringLiteral>(E); 1017 1018 if (StrE) { 1019 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx, 1020 firstDataArg, isPrintf); 1021 return true; 1022 } 1023 1024 return false; 1025 } 1026 1027 default: 1028 return false; 1029 } 1030} 1031 1032void 1033Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1034 const Expr * const *ExprArgs, 1035 SourceLocation CallSiteLoc) { 1036 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1037 e = NonNull->args_end(); 1038 i != e; ++i) { 1039 const Expr *ArgExpr = ExprArgs[*i]; 1040 if (ArgExpr->isNullPointerConstant(Context, 1041 Expr::NPC_ValueDependentIsNotNull)) 1042 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1043 } 1044} 1045 1046/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1047/// functions) for correct use of format strings. 1048void 1049Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg, 1050 unsigned format_idx, unsigned firstDataArg, 1051 bool isPrintf) { 1052 1053 const Expr *Fn = TheCall->getCallee(); 1054 1055 // The way the format attribute works in GCC, the implicit this argument 1056 // of member functions is counted. However, it doesn't appear in our own 1057 // lists, so decrement format_idx in that case. 1058 if (isa<CXXMemberCallExpr>(TheCall)) { 1059 const CXXMethodDecl *method_decl = 1060 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl()); 1061 if (method_decl && method_decl->isInstance()) { 1062 // Catch a format attribute mistakenly referring to the object argument. 1063 if (format_idx == 0) 1064 return; 1065 --format_idx; 1066 if(firstDataArg != 0) 1067 --firstDataArg; 1068 } 1069 } 1070 1071 // CHECK: printf/scanf-like function is called with no format string. 1072 if (format_idx >= TheCall->getNumArgs()) { 1073 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string) 1074 << Fn->getSourceRange(); 1075 return; 1076 } 1077 1078 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 1079 1080 // CHECK: format string is not a string literal. 1081 // 1082 // Dynamically generated format strings are difficult to 1083 // automatically vet at compile time. Requiring that format strings 1084 // are string literals: (1) permits the checking of format strings by 1085 // the compiler and thereby (2) can practically remove the source of 1086 // many format string exploits. 1087 1088 // Format string can be either ObjC string (e.g. @"%d") or 1089 // C string (e.g. "%d") 1090 // ObjC string uses the same format specifiers as C string, so we can use 1091 // the same format string checking logic for both ObjC and C strings. 1092 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 1093 firstDataArg, isPrintf)) 1094 return; // Literal format string found, check done! 1095 1096 // If there are no arguments specified, warn with -Wformat-security, otherwise 1097 // warn only with -Wformat-nonliteral. 1098 if (TheCall->getNumArgs() == format_idx+1) 1099 Diag(TheCall->getArg(format_idx)->getLocStart(), 1100 diag::warn_format_nonliteral_noargs) 1101 << OrigFormatExpr->getSourceRange(); 1102 else 1103 Diag(TheCall->getArg(format_idx)->getLocStart(), 1104 diag::warn_format_nonliteral) 1105 << OrigFormatExpr->getSourceRange(); 1106} 1107 1108namespace { 1109class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1110protected: 1111 Sema &S; 1112 const StringLiteral *FExpr; 1113 const Expr *OrigFormatExpr; 1114 const unsigned FirstDataArg; 1115 const unsigned NumDataArgs; 1116 const bool IsObjCLiteral; 1117 const char *Beg; // Start of format string. 1118 const bool HasVAListArg; 1119 const CallExpr *TheCall; 1120 unsigned FormatIdx; 1121 llvm::BitVector CoveredArgs; 1122 bool usesPositionalArgs; 1123 bool atFirstArg; 1124public: 1125 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1126 const Expr *origFormatExpr, unsigned firstDataArg, 1127 unsigned numDataArgs, bool isObjCLiteral, 1128 const char *beg, bool hasVAListArg, 1129 const CallExpr *theCall, unsigned formatIdx) 1130 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1131 FirstDataArg(firstDataArg), 1132 NumDataArgs(numDataArgs), 1133 IsObjCLiteral(isObjCLiteral), Beg(beg), 1134 HasVAListArg(hasVAListArg), 1135 TheCall(theCall), FormatIdx(formatIdx), 1136 usesPositionalArgs(false), atFirstArg(true) { 1137 CoveredArgs.resize(numDataArgs); 1138 CoveredArgs.reset(); 1139 } 1140 1141 void DoneProcessing(); 1142 1143 void HandleIncompleteSpecifier(const char *startSpecifier, 1144 unsigned specifierLen); 1145 1146 virtual void HandleInvalidPosition(const char *startSpecifier, 1147 unsigned specifierLen, 1148 analyze_format_string::PositionContext p); 1149 1150 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1151 1152 void HandleNullChar(const char *nullCharacter); 1153 1154protected: 1155 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1156 const char *startSpec, 1157 unsigned specifierLen, 1158 const char *csStart, unsigned csLen); 1159 1160 SourceRange getFormatStringRange(); 1161 CharSourceRange getSpecifierRange(const char *startSpecifier, 1162 unsigned specifierLen); 1163 SourceLocation getLocationOfByte(const char *x); 1164 1165 const Expr *getDataArg(unsigned i) const; 1166 1167 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1168 const analyze_format_string::ConversionSpecifier &CS, 1169 const char *startSpecifier, unsigned specifierLen, 1170 unsigned argIndex); 1171}; 1172} 1173 1174SourceRange CheckFormatHandler::getFormatStringRange() { 1175 return OrigFormatExpr->getSourceRange(); 1176} 1177 1178CharSourceRange CheckFormatHandler:: 1179getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1180 SourceLocation Start = getLocationOfByte(startSpecifier); 1181 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1182 1183 // Advance the end SourceLocation by one due to half-open ranges. 1184 End = End.getFileLocWithOffset(1); 1185 1186 return CharSourceRange::getCharRange(Start, End); 1187} 1188 1189SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1190 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1191} 1192 1193void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1194 unsigned specifierLen){ 1195 SourceLocation Loc = getLocationOfByte(startSpecifier); 1196 S.Diag(Loc, diag::warn_printf_incomplete_specifier) 1197 << getSpecifierRange(startSpecifier, specifierLen); 1198} 1199 1200void 1201CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1202 analyze_format_string::PositionContext p) { 1203 SourceLocation Loc = getLocationOfByte(startPos); 1204 S.Diag(Loc, diag::warn_format_invalid_positional_specifier) 1205 << (unsigned) p << getSpecifierRange(startPos, posLen); 1206} 1207 1208void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1209 unsigned posLen) { 1210 SourceLocation Loc = getLocationOfByte(startPos); 1211 S.Diag(Loc, diag::warn_format_zero_positional_specifier) 1212 << getSpecifierRange(startPos, posLen); 1213} 1214 1215void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1216 if (!IsObjCLiteral) { 1217 // The presence of a null character is likely an error. 1218 S.Diag(getLocationOfByte(nullCharacter), 1219 diag::warn_printf_format_string_contains_null_char) 1220 << getFormatStringRange(); 1221 } 1222} 1223 1224const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1225 return TheCall->getArg(FirstDataArg + i); 1226} 1227 1228void CheckFormatHandler::DoneProcessing() { 1229 // Does the number of data arguments exceed the number of 1230 // format conversions in the format string? 1231 if (!HasVAListArg) { 1232 // Find any arguments that weren't covered. 1233 CoveredArgs.flip(); 1234 signed notCoveredArg = CoveredArgs.find_first(); 1235 if (notCoveredArg >= 0) { 1236 assert((unsigned)notCoveredArg < NumDataArgs); 1237 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(), 1238 diag::warn_printf_data_arg_not_used) 1239 << getFormatStringRange(); 1240 } 1241 } 1242} 1243 1244bool 1245CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1246 SourceLocation Loc, 1247 const char *startSpec, 1248 unsigned specifierLen, 1249 const char *csStart, 1250 unsigned csLen) { 1251 1252 bool keepGoing = true; 1253 if (argIndex < NumDataArgs) { 1254 // Consider the argument coverered, even though the specifier doesn't 1255 // make sense. 1256 CoveredArgs.set(argIndex); 1257 } 1258 else { 1259 // If argIndex exceeds the number of data arguments we 1260 // don't issue a warning because that is just a cascade of warnings (and 1261 // they may have intended '%%' anyway). We don't want to continue processing 1262 // the format string after this point, however, as we will like just get 1263 // gibberish when trying to match arguments. 1264 keepGoing = false; 1265 } 1266 1267 S.Diag(Loc, diag::warn_format_invalid_conversion) 1268 << llvm::StringRef(csStart, csLen) 1269 << getSpecifierRange(startSpec, specifierLen); 1270 1271 return keepGoing; 1272} 1273 1274bool 1275CheckFormatHandler::CheckNumArgs( 1276 const analyze_format_string::FormatSpecifier &FS, 1277 const analyze_format_string::ConversionSpecifier &CS, 1278 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 1279 1280 if (argIndex >= NumDataArgs) { 1281 if (FS.usesPositionalArg()) { 1282 S.Diag(getLocationOfByte(CS.getStart()), 1283 diag::warn_printf_positional_arg_exceeds_data_args) 1284 << (argIndex+1) << NumDataArgs 1285 << getSpecifierRange(startSpecifier, specifierLen); 1286 } 1287 else { 1288 S.Diag(getLocationOfByte(CS.getStart()), 1289 diag::warn_printf_insufficient_data_args) 1290 << getSpecifierRange(startSpecifier, specifierLen); 1291 } 1292 1293 return false; 1294 } 1295 return true; 1296} 1297 1298//===--- CHECK: Printf format string checking ------------------------------===// 1299 1300namespace { 1301class CheckPrintfHandler : public CheckFormatHandler { 1302public: 1303 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1304 const Expr *origFormatExpr, unsigned firstDataArg, 1305 unsigned numDataArgs, bool isObjCLiteral, 1306 const char *beg, bool hasVAListArg, 1307 const CallExpr *theCall, unsigned formatIdx) 1308 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1309 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1310 theCall, formatIdx) {} 1311 1312 1313 bool HandleInvalidPrintfConversionSpecifier( 1314 const analyze_printf::PrintfSpecifier &FS, 1315 const char *startSpecifier, 1316 unsigned specifierLen); 1317 1318 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 1319 const char *startSpecifier, 1320 unsigned specifierLen); 1321 1322 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 1323 const char *startSpecifier, unsigned specifierLen); 1324 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 1325 const analyze_printf::OptionalAmount &Amt, 1326 unsigned type, 1327 const char *startSpecifier, unsigned specifierLen); 1328 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1329 const analyze_printf::OptionalFlag &flag, 1330 const char *startSpecifier, unsigned specifierLen); 1331 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 1332 const analyze_printf::OptionalFlag &ignoredFlag, 1333 const analyze_printf::OptionalFlag &flag, 1334 const char *startSpecifier, unsigned specifierLen); 1335}; 1336} 1337 1338bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 1339 const analyze_printf::PrintfSpecifier &FS, 1340 const char *startSpecifier, 1341 unsigned specifierLen) { 1342 const analyze_printf::PrintfConversionSpecifier &CS = 1343 FS.getConversionSpecifier(); 1344 1345 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1346 getLocationOfByte(CS.getStart()), 1347 startSpecifier, specifierLen, 1348 CS.getStart(), CS.getLength()); 1349} 1350 1351bool CheckPrintfHandler::HandleAmount( 1352 const analyze_format_string::OptionalAmount &Amt, 1353 unsigned k, const char *startSpecifier, 1354 unsigned specifierLen) { 1355 1356 if (Amt.hasDataArgument()) { 1357 if (!HasVAListArg) { 1358 unsigned argIndex = Amt.getArgIndex(); 1359 if (argIndex >= NumDataArgs) { 1360 S.Diag(getLocationOfByte(Amt.getStart()), 1361 diag::warn_printf_asterisk_missing_arg) 1362 << k << getSpecifierRange(startSpecifier, specifierLen); 1363 // Don't do any more checking. We will just emit 1364 // spurious errors. 1365 return false; 1366 } 1367 1368 // Type check the data argument. It should be an 'int'. 1369 // Although not in conformance with C99, we also allow the argument to be 1370 // an 'unsigned int' as that is a reasonably safe case. GCC also 1371 // doesn't emit a warning for that case. 1372 CoveredArgs.set(argIndex); 1373 const Expr *Arg = getDataArg(argIndex); 1374 QualType T = Arg->getType(); 1375 1376 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 1377 assert(ATR.isValid()); 1378 1379 if (!ATR.matchesType(S.Context, T)) { 1380 S.Diag(getLocationOfByte(Amt.getStart()), 1381 diag::warn_printf_asterisk_wrong_type) 1382 << k 1383 << ATR.getRepresentativeType(S.Context) << T 1384 << getSpecifierRange(startSpecifier, specifierLen) 1385 << Arg->getSourceRange(); 1386 // Don't do any more checking. We will just emit 1387 // spurious errors. 1388 return false; 1389 } 1390 } 1391 } 1392 return true; 1393} 1394 1395void CheckPrintfHandler::HandleInvalidAmount( 1396 const analyze_printf::PrintfSpecifier &FS, 1397 const analyze_printf::OptionalAmount &Amt, 1398 unsigned type, 1399 const char *startSpecifier, 1400 unsigned specifierLen) { 1401 const analyze_printf::PrintfConversionSpecifier &CS = 1402 FS.getConversionSpecifier(); 1403 switch (Amt.getHowSpecified()) { 1404 case analyze_printf::OptionalAmount::Constant: 1405 S.Diag(getLocationOfByte(Amt.getStart()), 1406 diag::warn_printf_nonsensical_optional_amount) 1407 << type 1408 << CS.toString() 1409 << getSpecifierRange(startSpecifier, specifierLen) 1410 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 1411 Amt.getConstantLength())); 1412 break; 1413 1414 default: 1415 S.Diag(getLocationOfByte(Amt.getStart()), 1416 diag::warn_printf_nonsensical_optional_amount) 1417 << type 1418 << CS.toString() 1419 << getSpecifierRange(startSpecifier, specifierLen); 1420 break; 1421 } 1422} 1423 1424void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1425 const analyze_printf::OptionalFlag &flag, 1426 const char *startSpecifier, 1427 unsigned specifierLen) { 1428 // Warn about pointless flag with a fixit removal. 1429 const analyze_printf::PrintfConversionSpecifier &CS = 1430 FS.getConversionSpecifier(); 1431 S.Diag(getLocationOfByte(flag.getPosition()), 1432 diag::warn_printf_nonsensical_flag) 1433 << flag.toString() << CS.toString() 1434 << getSpecifierRange(startSpecifier, specifierLen) 1435 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)); 1436} 1437 1438void CheckPrintfHandler::HandleIgnoredFlag( 1439 const analyze_printf::PrintfSpecifier &FS, 1440 const analyze_printf::OptionalFlag &ignoredFlag, 1441 const analyze_printf::OptionalFlag &flag, 1442 const char *startSpecifier, 1443 unsigned specifierLen) { 1444 // Warn about ignored flag with a fixit removal. 1445 S.Diag(getLocationOfByte(ignoredFlag.getPosition()), 1446 diag::warn_printf_ignored_flag) 1447 << ignoredFlag.toString() << flag.toString() 1448 << getSpecifierRange(startSpecifier, specifierLen) 1449 << FixItHint::CreateRemoval(getSpecifierRange( 1450 ignoredFlag.getPosition(), 1)); 1451} 1452 1453bool 1454CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 1455 &FS, 1456 const char *startSpecifier, 1457 unsigned specifierLen) { 1458 1459 using namespace analyze_format_string; 1460 using namespace analyze_printf; 1461 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 1462 1463 if (FS.consumesDataArgument()) { 1464 if (atFirstArg) { 1465 atFirstArg = false; 1466 usesPositionalArgs = FS.usesPositionalArg(); 1467 } 1468 else if (usesPositionalArgs != FS.usesPositionalArg()) { 1469 // Cannot mix-and-match positional and non-positional arguments. 1470 S.Diag(getLocationOfByte(CS.getStart()), 1471 diag::warn_format_mix_positional_nonpositional_args) 1472 << getSpecifierRange(startSpecifier, specifierLen); 1473 return false; 1474 } 1475 } 1476 1477 // First check if the field width, precision, and conversion specifier 1478 // have matching data arguments. 1479 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 1480 startSpecifier, specifierLen)) { 1481 return false; 1482 } 1483 1484 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 1485 startSpecifier, specifierLen)) { 1486 return false; 1487 } 1488 1489 if (!CS.consumesDataArgument()) { 1490 // FIXME: Technically specifying a precision or field width here 1491 // makes no sense. Worth issuing a warning at some point. 1492 return true; 1493 } 1494 1495 // Consume the argument. 1496 unsigned argIndex = FS.getArgIndex(); 1497 if (argIndex < NumDataArgs) { 1498 // The check to see if the argIndex is valid will come later. 1499 // We set the bit here because we may exit early from this 1500 // function if we encounter some other error. 1501 CoveredArgs.set(argIndex); 1502 } 1503 1504 // Check for using an Objective-C specific conversion specifier 1505 // in a non-ObjC literal. 1506 if (!IsObjCLiteral && CS.isObjCArg()) { 1507 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 1508 specifierLen); 1509 } 1510 1511 // Check for invalid use of field width 1512 if (!FS.hasValidFieldWidth()) { 1513 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 1514 startSpecifier, specifierLen); 1515 } 1516 1517 // Check for invalid use of precision 1518 if (!FS.hasValidPrecision()) { 1519 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 1520 startSpecifier, specifierLen); 1521 } 1522 1523 // Check each flag does not conflict with any other component. 1524 if (!FS.hasValidThousandsGroupingPrefix()) 1525 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 1526 if (!FS.hasValidLeadingZeros()) 1527 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 1528 if (!FS.hasValidPlusPrefix()) 1529 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 1530 if (!FS.hasValidSpacePrefix()) 1531 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 1532 if (!FS.hasValidAlternativeForm()) 1533 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 1534 if (!FS.hasValidLeftJustified()) 1535 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 1536 1537 // Check that flags are not ignored by another flag 1538 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 1539 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 1540 startSpecifier, specifierLen); 1541 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 1542 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 1543 startSpecifier, specifierLen); 1544 1545 // Check the length modifier is valid with the given conversion specifier. 1546 const LengthModifier &LM = FS.getLengthModifier(); 1547 if (!FS.hasValidLengthModifier()) 1548 S.Diag(getLocationOfByte(LM.getStart()), 1549 diag::warn_format_nonsensical_length) 1550 << LM.toString() << CS.toString() 1551 << getSpecifierRange(startSpecifier, specifierLen) 1552 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 1553 LM.getLength())); 1554 1555 // Are we using '%n'? 1556 if (CS.getKind() == ConversionSpecifier::nArg) { 1557 // Issue a warning about this being a possible security issue. 1558 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back) 1559 << getSpecifierRange(startSpecifier, specifierLen); 1560 // Continue checking the other format specifiers. 1561 return true; 1562 } 1563 1564 // The remaining checks depend on the data arguments. 1565 if (HasVAListArg) 1566 return true; 1567 1568 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 1569 return false; 1570 1571 // Now type check the data expression that matches the 1572 // format specifier. 1573 const Expr *Ex = getDataArg(argIndex); 1574 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 1575 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 1576 // Check if we didn't match because of an implicit cast from a 'char' 1577 // or 'short' to an 'int'. This is done because printf is a varargs 1578 // function. 1579 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 1580 if (ICE->getType() == S.Context.IntTy) { 1581 // All further checking is done on the subexpression. 1582 Ex = ICE->getSubExpr(); 1583 if (ATR.matchesType(S.Context, Ex->getType())) 1584 return true; 1585 } 1586 1587 // We may be able to offer a FixItHint if it is a supported type. 1588 PrintfSpecifier fixedFS = FS; 1589 bool success = fixedFS.fixType(Ex->getType()); 1590 1591 if (success) { 1592 // Get the fix string from the fixed format specifier 1593 llvm::SmallString<128> buf; 1594 llvm::raw_svector_ostream os(buf); 1595 fixedFS.toString(os); 1596 1597 // FIXME: getRepresentativeType() perhaps should return a string 1598 // instead of a QualType to better handle when the representative 1599 // type is 'wint_t' (which is defined in the system headers). 1600 S.Diag(getLocationOfByte(CS.getStart()), 1601 diag::warn_printf_conversion_argument_type_mismatch) 1602 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1603 << getSpecifierRange(startSpecifier, specifierLen) 1604 << Ex->getSourceRange() 1605 << FixItHint::CreateReplacement( 1606 getSpecifierRange(startSpecifier, specifierLen), 1607 os.str()); 1608 } 1609 else { 1610 S.Diag(getLocationOfByte(CS.getStart()), 1611 diag::warn_printf_conversion_argument_type_mismatch) 1612 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1613 << getSpecifierRange(startSpecifier, specifierLen) 1614 << Ex->getSourceRange(); 1615 } 1616 } 1617 1618 return true; 1619} 1620 1621//===--- CHECK: Scanf format string checking ------------------------------===// 1622 1623namespace { 1624class CheckScanfHandler : public CheckFormatHandler { 1625public: 1626 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 1627 const Expr *origFormatExpr, unsigned firstDataArg, 1628 unsigned numDataArgs, bool isObjCLiteral, 1629 const char *beg, bool hasVAListArg, 1630 const CallExpr *theCall, unsigned formatIdx) 1631 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1632 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1633 theCall, formatIdx) {} 1634 1635 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 1636 const char *startSpecifier, 1637 unsigned specifierLen); 1638 1639 bool HandleInvalidScanfConversionSpecifier( 1640 const analyze_scanf::ScanfSpecifier &FS, 1641 const char *startSpecifier, 1642 unsigned specifierLen); 1643 1644 void HandleIncompleteScanList(const char *start, const char *end); 1645}; 1646} 1647 1648void CheckScanfHandler::HandleIncompleteScanList(const char *start, 1649 const char *end) { 1650 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete) 1651 << getSpecifierRange(start, end - start); 1652} 1653 1654bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 1655 const analyze_scanf::ScanfSpecifier &FS, 1656 const char *startSpecifier, 1657 unsigned specifierLen) { 1658 1659 const analyze_scanf::ScanfConversionSpecifier &CS = 1660 FS.getConversionSpecifier(); 1661 1662 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1663 getLocationOfByte(CS.getStart()), 1664 startSpecifier, specifierLen, 1665 CS.getStart(), CS.getLength()); 1666} 1667 1668bool CheckScanfHandler::HandleScanfSpecifier( 1669 const analyze_scanf::ScanfSpecifier &FS, 1670 const char *startSpecifier, 1671 unsigned specifierLen) { 1672 1673 using namespace analyze_scanf; 1674 using namespace analyze_format_string; 1675 1676 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 1677 1678 // Handle case where '%' and '*' don't consume an argument. These shouldn't 1679 // be used to decide if we are using positional arguments consistently. 1680 if (FS.consumesDataArgument()) { 1681 if (atFirstArg) { 1682 atFirstArg = false; 1683 usesPositionalArgs = FS.usesPositionalArg(); 1684 } 1685 else if (usesPositionalArgs != FS.usesPositionalArg()) { 1686 // Cannot mix-and-match positional and non-positional arguments. 1687 S.Diag(getLocationOfByte(CS.getStart()), 1688 diag::warn_format_mix_positional_nonpositional_args) 1689 << getSpecifierRange(startSpecifier, specifierLen); 1690 return false; 1691 } 1692 } 1693 1694 // Check if the field with is non-zero. 1695 const OptionalAmount &Amt = FS.getFieldWidth(); 1696 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 1697 if (Amt.getConstantAmount() == 0) { 1698 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 1699 Amt.getConstantLength()); 1700 S.Diag(getLocationOfByte(Amt.getStart()), 1701 diag::warn_scanf_nonzero_width) 1702 << R << FixItHint::CreateRemoval(R); 1703 } 1704 } 1705 1706 if (!FS.consumesDataArgument()) { 1707 // FIXME: Technically specifying a precision or field width here 1708 // makes no sense. Worth issuing a warning at some point. 1709 return true; 1710 } 1711 1712 // Consume the argument. 1713 unsigned argIndex = FS.getArgIndex(); 1714 if (argIndex < NumDataArgs) { 1715 // The check to see if the argIndex is valid will come later. 1716 // We set the bit here because we may exit early from this 1717 // function if we encounter some other error. 1718 CoveredArgs.set(argIndex); 1719 } 1720 1721 // Check the length modifier is valid with the given conversion specifier. 1722 const LengthModifier &LM = FS.getLengthModifier(); 1723 if (!FS.hasValidLengthModifier()) { 1724 S.Diag(getLocationOfByte(LM.getStart()), 1725 diag::warn_format_nonsensical_length) 1726 << LM.toString() << CS.toString() 1727 << getSpecifierRange(startSpecifier, specifierLen) 1728 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 1729 LM.getLength())); 1730 } 1731 1732 // The remaining checks depend on the data arguments. 1733 if (HasVAListArg) 1734 return true; 1735 1736 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 1737 return false; 1738 1739 // FIXME: Check that the argument type matches the format specifier. 1740 1741 return true; 1742} 1743 1744void Sema::CheckFormatString(const StringLiteral *FExpr, 1745 const Expr *OrigFormatExpr, 1746 const CallExpr *TheCall, bool HasVAListArg, 1747 unsigned format_idx, unsigned firstDataArg, 1748 bool isPrintf) { 1749 1750 // CHECK: is the format string a wide literal? 1751 if (FExpr->isWide()) { 1752 Diag(FExpr->getLocStart(), 1753 diag::warn_format_string_is_wide_literal) 1754 << OrigFormatExpr->getSourceRange(); 1755 return; 1756 } 1757 1758 // Str - The format string. NOTE: this is NOT null-terminated! 1759 llvm::StringRef StrRef = FExpr->getString(); 1760 const char *Str = StrRef.data(); 1761 unsigned StrLen = StrRef.size(); 1762 1763 // CHECK: empty format string? 1764 if (StrLen == 0) { 1765 Diag(FExpr->getLocStart(), diag::warn_empty_format_string) 1766 << OrigFormatExpr->getSourceRange(); 1767 return; 1768 } 1769 1770 if (isPrintf) { 1771 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 1772 TheCall->getNumArgs() - firstDataArg, 1773 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1774 HasVAListArg, TheCall, format_idx); 1775 1776 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen)) 1777 H.DoneProcessing(); 1778 } 1779 else { 1780 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 1781 TheCall->getNumArgs() - firstDataArg, 1782 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1783 HasVAListArg, TheCall, format_idx); 1784 1785 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen)) 1786 H.DoneProcessing(); 1787 } 1788} 1789 1790//===--- CHECK: Return Address of Stack Variable --------------------------===// 1791 1792static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars); 1793static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars); 1794 1795/// CheckReturnStackAddr - Check if a return statement returns the address 1796/// of a stack variable. 1797void 1798Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 1799 SourceLocation ReturnLoc) { 1800 1801 Expr *stackE = 0; 1802 llvm::SmallVector<DeclRefExpr *, 8> refVars; 1803 1804 // Perform checking for returned stack addresses, local blocks, 1805 // label addresses or references to temporaries. 1806 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 1807 stackE = EvalAddr(RetValExp, refVars); 1808 } else if (lhsType->isReferenceType()) { 1809 stackE = EvalVal(RetValExp, refVars); 1810 } 1811 1812 if (stackE == 0) 1813 return; // Nothing suspicious was found. 1814 1815 SourceLocation diagLoc; 1816 SourceRange diagRange; 1817 if (refVars.empty()) { 1818 diagLoc = stackE->getLocStart(); 1819 diagRange = stackE->getSourceRange(); 1820 } else { 1821 // We followed through a reference variable. 'stackE' contains the 1822 // problematic expression but we will warn at the return statement pointing 1823 // at the reference variable. We will later display the "trail" of 1824 // reference variables using notes. 1825 diagLoc = refVars[0]->getLocStart(); 1826 diagRange = refVars[0]->getSourceRange(); 1827 } 1828 1829 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 1830 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 1831 : diag::warn_ret_stack_addr) 1832 << DR->getDecl()->getDeclName() << diagRange; 1833 } else if (isa<BlockExpr>(stackE)) { // local block. 1834 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 1835 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 1836 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 1837 } else { // local temporary. 1838 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 1839 : diag::warn_ret_local_temp_addr) 1840 << diagRange; 1841 } 1842 1843 // Display the "trail" of reference variables that we followed until we 1844 // found the problematic expression using notes. 1845 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 1846 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 1847 // If this var binds to another reference var, show the range of the next 1848 // var, otherwise the var binds to the problematic expression, in which case 1849 // show the range of the expression. 1850 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 1851 : stackE->getSourceRange(); 1852 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 1853 << VD->getDeclName() << range; 1854 } 1855} 1856 1857/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1858/// check if the expression in a return statement evaluates to an address 1859/// to a location on the stack, a local block, an address of a label, or a 1860/// reference to local temporary. The recursion is used to traverse the 1861/// AST of the return expression, with recursion backtracking when we 1862/// encounter a subexpression that (1) clearly does not lead to one of the 1863/// above problematic expressions (2) is something we cannot determine leads to 1864/// a problematic expression based on such local checking. 1865/// 1866/// Both EvalAddr and EvalVal follow through reference variables to evaluate 1867/// the expression that they point to. Such variables are added to the 1868/// 'refVars' vector so that we know what the reference variable "trail" was. 1869/// 1870/// EvalAddr processes expressions that are pointers that are used as 1871/// references (and not L-values). EvalVal handles all other values. 1872/// At the base case of the recursion is a check for the above problematic 1873/// expressions. 1874/// 1875/// This implementation handles: 1876/// 1877/// * pointer-to-pointer casts 1878/// * implicit conversions from array references to pointers 1879/// * taking the address of fields 1880/// * arbitrary interplay between "&" and "*" operators 1881/// * pointer arithmetic from an address of a stack variable 1882/// * taking the address of an array element where the array is on the stack 1883static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) { 1884 if (E->isTypeDependent()) 1885 return NULL; 1886 1887 // We should only be called for evaluating pointer expressions. 1888 assert((E->getType()->isAnyPointerType() || 1889 E->getType()->isBlockPointerType() || 1890 E->getType()->isObjCQualifiedIdType()) && 1891 "EvalAddr only works on pointers"); 1892 1893 // Our "symbolic interpreter" is just a dispatch off the currently 1894 // viewed AST node. We then recursively traverse the AST by calling 1895 // EvalAddr and EvalVal appropriately. 1896 switch (E->getStmtClass()) { 1897 case Stmt::ParenExprClass: 1898 // Ignore parentheses. 1899 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars); 1900 1901 case Stmt::DeclRefExprClass: { 1902 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1903 1904 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1905 // If this is a reference variable, follow through to the expression that 1906 // it points to. 1907 if (V->hasLocalStorage() && 1908 V->getType()->isReferenceType() && V->hasInit()) { 1909 // Add the reference variable to the "trail". 1910 refVars.push_back(DR); 1911 return EvalAddr(V->getInit(), refVars); 1912 } 1913 1914 return NULL; 1915 } 1916 1917 case Stmt::UnaryOperatorClass: { 1918 // The only unary operator that make sense to handle here 1919 // is AddrOf. All others don't make sense as pointers. 1920 UnaryOperator *U = cast<UnaryOperator>(E); 1921 1922 if (U->getOpcode() == UO_AddrOf) 1923 return EvalVal(U->getSubExpr(), refVars); 1924 else 1925 return NULL; 1926 } 1927 1928 case Stmt::BinaryOperatorClass: { 1929 // Handle pointer arithmetic. All other binary operators are not valid 1930 // in this context. 1931 BinaryOperator *B = cast<BinaryOperator>(E); 1932 BinaryOperatorKind op = B->getOpcode(); 1933 1934 if (op != BO_Add && op != BO_Sub) 1935 return NULL; 1936 1937 Expr *Base = B->getLHS(); 1938 1939 // Determine which argument is the real pointer base. It could be 1940 // the RHS argument instead of the LHS. 1941 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 1942 1943 assert (Base->getType()->isPointerType()); 1944 return EvalAddr(Base, refVars); 1945 } 1946 1947 // For conditional operators we need to see if either the LHS or RHS are 1948 // valid DeclRefExpr*s. If one of them is valid, we return it. 1949 case Stmt::ConditionalOperatorClass: { 1950 ConditionalOperator *C = cast<ConditionalOperator>(E); 1951 1952 // Handle the GNU extension for missing LHS. 1953 if (Expr *lhsExpr = C->getLHS()) { 1954 // In C++, we can have a throw-expression, which has 'void' type. 1955 if (!lhsExpr->getType()->isVoidType()) 1956 if (Expr* LHS = EvalAddr(lhsExpr, refVars)) 1957 return LHS; 1958 } 1959 1960 // In C++, we can have a throw-expression, which has 'void' type. 1961 if (C->getRHS()->getType()->isVoidType()) 1962 return NULL; 1963 1964 return EvalAddr(C->getRHS(), refVars); 1965 } 1966 1967 case Stmt::BlockExprClass: 1968 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 1969 return E; // local block. 1970 return NULL; 1971 1972 case Stmt::AddrLabelExprClass: 1973 return E; // address of label. 1974 1975 // For casts, we need to handle conversions from arrays to 1976 // pointer values, and pointer-to-pointer conversions. 1977 case Stmt::ImplicitCastExprClass: 1978 case Stmt::CStyleCastExprClass: 1979 case Stmt::CXXFunctionalCastExprClass: { 1980 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1981 QualType T = SubExpr->getType(); 1982 1983 if (SubExpr->getType()->isPointerType() || 1984 SubExpr->getType()->isBlockPointerType() || 1985 SubExpr->getType()->isObjCQualifiedIdType()) 1986 return EvalAddr(SubExpr, refVars); 1987 else if (T->isArrayType()) 1988 return EvalVal(SubExpr, refVars); 1989 else 1990 return 0; 1991 } 1992 1993 // C++ casts. For dynamic casts, static casts, and const casts, we 1994 // are always converting from a pointer-to-pointer, so we just blow 1995 // through the cast. In the case the dynamic cast doesn't fail (and 1996 // return NULL), we take the conservative route and report cases 1997 // where we return the address of a stack variable. For Reinterpre 1998 // FIXME: The comment about is wrong; we're not always converting 1999 // from pointer to pointer. I'm guessing that this code should also 2000 // handle references to objects. 2001 case Stmt::CXXStaticCastExprClass: 2002 case Stmt::CXXDynamicCastExprClass: 2003 case Stmt::CXXConstCastExprClass: 2004 case Stmt::CXXReinterpretCastExprClass: { 2005 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 2006 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 2007 return EvalAddr(S, refVars); 2008 else 2009 return NULL; 2010 } 2011 2012 // Everything else: we simply don't reason about them. 2013 default: 2014 return NULL; 2015 } 2016} 2017 2018 2019/// EvalVal - This function is complements EvalAddr in the mutual recursion. 2020/// See the comments for EvalAddr for more details. 2021static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) { 2022do { 2023 // We should only be called for evaluating non-pointer expressions, or 2024 // expressions with a pointer type that are not used as references but instead 2025 // are l-values (e.g., DeclRefExpr with a pointer type). 2026 2027 // Our "symbolic interpreter" is just a dispatch off the currently 2028 // viewed AST node. We then recursively traverse the AST by calling 2029 // EvalAddr and EvalVal appropriately. 2030 switch (E->getStmtClass()) { 2031 case Stmt::ImplicitCastExprClass: { 2032 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 2033 if (IE->getValueKind() == VK_LValue) { 2034 E = IE->getSubExpr(); 2035 continue; 2036 } 2037 return NULL; 2038 } 2039 2040 case Stmt::DeclRefExprClass: { 2041 // When we hit a DeclRefExpr we are looking at code that refers to a 2042 // variable's name. If it's not a reference variable we check if it has 2043 // local storage within the function, and if so, return the expression. 2044 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2045 2046 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2047 if (V->hasLocalStorage()) { 2048 if (!V->getType()->isReferenceType()) 2049 return DR; 2050 2051 // Reference variable, follow through to the expression that 2052 // it points to. 2053 if (V->hasInit()) { 2054 // Add the reference variable to the "trail". 2055 refVars.push_back(DR); 2056 return EvalVal(V->getInit(), refVars); 2057 } 2058 } 2059 2060 return NULL; 2061 } 2062 2063 case Stmt::ParenExprClass: { 2064 // Ignore parentheses. 2065 E = cast<ParenExpr>(E)->getSubExpr(); 2066 continue; 2067 } 2068 2069 case Stmt::UnaryOperatorClass: { 2070 // The only unary operator that make sense to handle here 2071 // is Deref. All others don't resolve to a "name." This includes 2072 // handling all sorts of rvalues passed to a unary operator. 2073 UnaryOperator *U = cast<UnaryOperator>(E); 2074 2075 if (U->getOpcode() == UO_Deref) 2076 return EvalAddr(U->getSubExpr(), refVars); 2077 2078 return NULL; 2079 } 2080 2081 case Stmt::ArraySubscriptExprClass: { 2082 // Array subscripts are potential references to data on the stack. We 2083 // retrieve the DeclRefExpr* for the array variable if it indeed 2084 // has local storage. 2085 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars); 2086 } 2087 2088 case Stmt::ConditionalOperatorClass: { 2089 // For conditional operators we need to see if either the LHS or RHS are 2090 // non-NULL Expr's. If one is non-NULL, we return it. 2091 ConditionalOperator *C = cast<ConditionalOperator>(E); 2092 2093 // Handle the GNU extension for missing LHS. 2094 if (Expr *lhsExpr = C->getLHS()) 2095 if (Expr *LHS = EvalVal(lhsExpr, refVars)) 2096 return LHS; 2097 2098 return EvalVal(C->getRHS(), refVars); 2099 } 2100 2101 // Accesses to members are potential references to data on the stack. 2102 case Stmt::MemberExprClass: { 2103 MemberExpr *M = cast<MemberExpr>(E); 2104 2105 // Check for indirect access. We only want direct field accesses. 2106 if (M->isArrow()) 2107 return NULL; 2108 2109 // Check whether the member type is itself a reference, in which case 2110 // we're not going to refer to the member, but to what the member refers to. 2111 if (M->getMemberDecl()->getType()->isReferenceType()) 2112 return NULL; 2113 2114 return EvalVal(M->getBase(), refVars); 2115 } 2116 2117 default: 2118 // Check that we don't return or take the address of a reference to a 2119 // temporary. This is only useful in C++. 2120 if (!E->isTypeDependent() && E->isRValue()) 2121 return E; 2122 2123 // Everything else: we simply don't reason about them. 2124 return NULL; 2125 } 2126} while (true); 2127} 2128 2129//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 2130 2131/// Check for comparisons of floating point operands using != and ==. 2132/// Issue a warning if these are no self-comparisons, as they are not likely 2133/// to do what the programmer intended. 2134void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 2135 bool EmitWarning = true; 2136 2137 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts(); 2138 Expr* RightExprSansParen = rex->IgnoreParenImpCasts(); 2139 2140 // Special case: check for x == x (which is OK). 2141 // Do not emit warnings for such cases. 2142 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 2143 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 2144 if (DRL->getDecl() == DRR->getDecl()) 2145 EmitWarning = false; 2146 2147 2148 // Special case: check for comparisons against literals that can be exactly 2149 // represented by APFloat. In such cases, do not emit a warning. This 2150 // is a heuristic: often comparison against such literals are used to 2151 // detect if a value in a variable has not changed. This clearly can 2152 // lead to false negatives. 2153 if (EmitWarning) { 2154 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 2155 if (FLL->isExact()) 2156 EmitWarning = false; 2157 } else 2158 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 2159 if (FLR->isExact()) 2160 EmitWarning = false; 2161 } 2162 } 2163 2164 // Check for comparisons with builtin types. 2165 if (EmitWarning) 2166 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 2167 if (CL->isBuiltinCall(Context)) 2168 EmitWarning = false; 2169 2170 if (EmitWarning) 2171 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 2172 if (CR->isBuiltinCall(Context)) 2173 EmitWarning = false; 2174 2175 // Emit the diagnostic. 2176 if (EmitWarning) 2177 Diag(loc, diag::warn_floatingpoint_eq) 2178 << lex->getSourceRange() << rex->getSourceRange(); 2179} 2180 2181//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 2182//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 2183 2184namespace { 2185 2186/// Structure recording the 'active' range of an integer-valued 2187/// expression. 2188struct IntRange { 2189 /// The number of bits active in the int. 2190 unsigned Width; 2191 2192 /// True if the int is known not to have negative values. 2193 bool NonNegative; 2194 2195 IntRange(unsigned Width, bool NonNegative) 2196 : Width(Width), NonNegative(NonNegative) 2197 {} 2198 2199 /// Returns the range of the bool type. 2200 static IntRange forBoolType() { 2201 return IntRange(1, true); 2202 } 2203 2204 /// Returns the range of an opaque value of the given integral type. 2205 static IntRange forValueOfType(ASTContext &C, QualType T) { 2206 return forValueOfCanonicalType(C, 2207 T->getCanonicalTypeInternal().getTypePtr()); 2208 } 2209 2210 /// Returns the range of an opaque value of a canonical integral type. 2211 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 2212 assert(T->isCanonicalUnqualified()); 2213 2214 if (const VectorType *VT = dyn_cast<VectorType>(T)) 2215 T = VT->getElementType().getTypePtr(); 2216 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 2217 T = CT->getElementType().getTypePtr(); 2218 2219 // For enum types, use the known bit width of the enumerators. 2220 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 2221 EnumDecl *Enum = ET->getDecl(); 2222 if (!Enum->isDefinition()) 2223 return IntRange(C.getIntWidth(QualType(T, 0)), false); 2224 2225 unsigned NumPositive = Enum->getNumPositiveBits(); 2226 unsigned NumNegative = Enum->getNumNegativeBits(); 2227 2228 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 2229 } 2230 2231 const BuiltinType *BT = cast<BuiltinType>(T); 2232 assert(BT->isInteger()); 2233 2234 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 2235 } 2236 2237 /// Returns the "target" range of a canonical integral type, i.e. 2238 /// the range of values expressible in the type. 2239 /// 2240 /// This matches forValueOfCanonicalType except that enums have the 2241 /// full range of their type, not the range of their enumerators. 2242 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 2243 assert(T->isCanonicalUnqualified()); 2244 2245 if (const VectorType *VT = dyn_cast<VectorType>(T)) 2246 T = VT->getElementType().getTypePtr(); 2247 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 2248 T = CT->getElementType().getTypePtr(); 2249 if (const EnumType *ET = dyn_cast<EnumType>(T)) 2250 T = ET->getDecl()->getIntegerType().getTypePtr(); 2251 2252 const BuiltinType *BT = cast<BuiltinType>(T); 2253 assert(BT->isInteger()); 2254 2255 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 2256 } 2257 2258 /// Returns the supremum of two ranges: i.e. their conservative merge. 2259 static IntRange join(IntRange L, IntRange R) { 2260 return IntRange(std::max(L.Width, R.Width), 2261 L.NonNegative && R.NonNegative); 2262 } 2263 2264 /// Returns the infinum of two ranges: i.e. their aggressive merge. 2265 static IntRange meet(IntRange L, IntRange R) { 2266 return IntRange(std::min(L.Width, R.Width), 2267 L.NonNegative || R.NonNegative); 2268 } 2269}; 2270 2271IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 2272 if (value.isSigned() && value.isNegative()) 2273 return IntRange(value.getMinSignedBits(), false); 2274 2275 if (value.getBitWidth() > MaxWidth) 2276 value = value.trunc(MaxWidth); 2277 2278 // isNonNegative() just checks the sign bit without considering 2279 // signedness. 2280 return IntRange(value.getActiveBits(), true); 2281} 2282 2283IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 2284 unsigned MaxWidth) { 2285 if (result.isInt()) 2286 return GetValueRange(C, result.getInt(), MaxWidth); 2287 2288 if (result.isVector()) { 2289 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 2290 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 2291 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 2292 R = IntRange::join(R, El); 2293 } 2294 return R; 2295 } 2296 2297 if (result.isComplexInt()) { 2298 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 2299 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 2300 return IntRange::join(R, I); 2301 } 2302 2303 // This can happen with lossless casts to intptr_t of "based" lvalues. 2304 // Assume it might use arbitrary bits. 2305 // FIXME: The only reason we need to pass the type in here is to get 2306 // the sign right on this one case. It would be nice if APValue 2307 // preserved this. 2308 assert(result.isLValue()); 2309 return IntRange(MaxWidth, Ty->isUnsignedIntegerType()); 2310} 2311 2312/// Pseudo-evaluate the given integer expression, estimating the 2313/// range of values it might take. 2314/// 2315/// \param MaxWidth - the width to which the value will be truncated 2316IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 2317 E = E->IgnoreParens(); 2318 2319 // Try a full evaluation first. 2320 Expr::EvalResult result; 2321 if (E->Evaluate(result, C)) 2322 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 2323 2324 // I think we only want to look through implicit casts here; if the 2325 // user has an explicit widening cast, we should treat the value as 2326 // being of the new, wider type. 2327 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 2328 if (CE->getCastKind() == CK_NoOp) 2329 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 2330 2331 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 2332 2333 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 2334 2335 // Assume that non-integer casts can span the full range of the type. 2336 if (!isIntegerCast) 2337 return OutputTypeRange; 2338 2339 IntRange SubRange 2340 = GetExprRange(C, CE->getSubExpr(), 2341 std::min(MaxWidth, OutputTypeRange.Width)); 2342 2343 // Bail out if the subexpr's range is as wide as the cast type. 2344 if (SubRange.Width >= OutputTypeRange.Width) 2345 return OutputTypeRange; 2346 2347 // Otherwise, we take the smaller width, and we're non-negative if 2348 // either the output type or the subexpr is. 2349 return IntRange(SubRange.Width, 2350 SubRange.NonNegative || OutputTypeRange.NonNegative); 2351 } 2352 2353 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2354 // If we can fold the condition, just take that operand. 2355 bool CondResult; 2356 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 2357 return GetExprRange(C, CondResult ? CO->getTrueExpr() 2358 : CO->getFalseExpr(), 2359 MaxWidth); 2360 2361 // Otherwise, conservatively merge. 2362 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 2363 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 2364 return IntRange::join(L, R); 2365 } 2366 2367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2368 switch (BO->getOpcode()) { 2369 2370 // Boolean-valued operations are single-bit and positive. 2371 case BO_LAnd: 2372 case BO_LOr: 2373 case BO_LT: 2374 case BO_GT: 2375 case BO_LE: 2376 case BO_GE: 2377 case BO_EQ: 2378 case BO_NE: 2379 return IntRange::forBoolType(); 2380 2381 // The type of these compound assignments is the type of the LHS, 2382 // so the RHS is not necessarily an integer. 2383 case BO_MulAssign: 2384 case BO_DivAssign: 2385 case BO_RemAssign: 2386 case BO_AddAssign: 2387 case BO_SubAssign: 2388 return IntRange::forValueOfType(C, E->getType()); 2389 2390 // Operations with opaque sources are black-listed. 2391 case BO_PtrMemD: 2392 case BO_PtrMemI: 2393 return IntRange::forValueOfType(C, E->getType()); 2394 2395 // Bitwise-and uses the *infinum* of the two source ranges. 2396 case BO_And: 2397 case BO_AndAssign: 2398 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 2399 GetExprRange(C, BO->getRHS(), MaxWidth)); 2400 2401 // Left shift gets black-listed based on a judgement call. 2402 case BO_Shl: 2403 // ...except that we want to treat '1 << (blah)' as logically 2404 // positive. It's an important idiom. 2405 if (IntegerLiteral *I 2406 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 2407 if (I->getValue() == 1) { 2408 IntRange R = IntRange::forValueOfType(C, E->getType()); 2409 return IntRange(R.Width, /*NonNegative*/ true); 2410 } 2411 } 2412 // fallthrough 2413 2414 case BO_ShlAssign: 2415 return IntRange::forValueOfType(C, E->getType()); 2416 2417 // Right shift by a constant can narrow its left argument. 2418 case BO_Shr: 2419 case BO_ShrAssign: { 2420 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 2421 2422 // If the shift amount is a positive constant, drop the width by 2423 // that much. 2424 llvm::APSInt shift; 2425 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 2426 shift.isNonNegative()) { 2427 unsigned zext = shift.getZExtValue(); 2428 if (zext >= L.Width) 2429 L.Width = (L.NonNegative ? 0 : 1); 2430 else 2431 L.Width -= zext; 2432 } 2433 2434 return L; 2435 } 2436 2437 // Comma acts as its right operand. 2438 case BO_Comma: 2439 return GetExprRange(C, BO->getRHS(), MaxWidth); 2440 2441 // Black-list pointer subtractions. 2442 case BO_Sub: 2443 if (BO->getLHS()->getType()->isPointerType()) 2444 return IntRange::forValueOfType(C, E->getType()); 2445 // fallthrough 2446 2447 default: 2448 break; 2449 } 2450 2451 // Treat every other operator as if it were closed on the 2452 // narrowest type that encompasses both operands. 2453 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 2454 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 2455 return IntRange::join(L, R); 2456 } 2457 2458 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 2459 switch (UO->getOpcode()) { 2460 // Boolean-valued operations are white-listed. 2461 case UO_LNot: 2462 return IntRange::forBoolType(); 2463 2464 // Operations with opaque sources are black-listed. 2465 case UO_Deref: 2466 case UO_AddrOf: // should be impossible 2467 return IntRange::forValueOfType(C, E->getType()); 2468 2469 default: 2470 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 2471 } 2472 } 2473 2474 if (dyn_cast<OffsetOfExpr>(E)) { 2475 IntRange::forValueOfType(C, E->getType()); 2476 } 2477 2478 FieldDecl *BitField = E->getBitField(); 2479 if (BitField) { 2480 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C); 2481 unsigned BitWidth = BitWidthAP.getZExtValue(); 2482 2483 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType()); 2484 } 2485 2486 return IntRange::forValueOfType(C, E->getType()); 2487} 2488 2489IntRange GetExprRange(ASTContext &C, Expr *E) { 2490 return GetExprRange(C, E, C.getIntWidth(E->getType())); 2491} 2492 2493/// Checks whether the given value, which currently has the given 2494/// source semantics, has the same value when coerced through the 2495/// target semantics. 2496bool IsSameFloatAfterCast(const llvm::APFloat &value, 2497 const llvm::fltSemantics &Src, 2498 const llvm::fltSemantics &Tgt) { 2499 llvm::APFloat truncated = value; 2500 2501 bool ignored; 2502 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 2503 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 2504 2505 return truncated.bitwiseIsEqual(value); 2506} 2507 2508/// Checks whether the given value, which currently has the given 2509/// source semantics, has the same value when coerced through the 2510/// target semantics. 2511/// 2512/// The value might be a vector of floats (or a complex number). 2513bool IsSameFloatAfterCast(const APValue &value, 2514 const llvm::fltSemantics &Src, 2515 const llvm::fltSemantics &Tgt) { 2516 if (value.isFloat()) 2517 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 2518 2519 if (value.isVector()) { 2520 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 2521 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 2522 return false; 2523 return true; 2524 } 2525 2526 assert(value.isComplexFloat()); 2527 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 2528 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 2529} 2530 2531void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 2532 2533static bool IsZero(Sema &S, Expr *E) { 2534 // Suppress cases where we are comparing against an enum constant. 2535 if (const DeclRefExpr *DR = 2536 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 2537 if (isa<EnumConstantDecl>(DR->getDecl())) 2538 return false; 2539 2540 // Suppress cases where the '0' value is expanded from a macro. 2541 if (E->getLocStart().isMacroID()) 2542 return false; 2543 2544 llvm::APSInt Value; 2545 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 2546} 2547 2548static bool HasEnumType(Expr *E) { 2549 // Strip off implicit integral promotions. 2550 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2551 if (ICE->getCastKind() != CK_IntegralCast && 2552 ICE->getCastKind() != CK_NoOp) 2553 break; 2554 E = ICE->getSubExpr(); 2555 } 2556 2557 return E->getType()->isEnumeralType(); 2558} 2559 2560void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 2561 BinaryOperatorKind op = E->getOpcode(); 2562 if (E->isValueDependent()) 2563 return; 2564 2565 if (op == BO_LT && IsZero(S, E->getRHS())) { 2566 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 2567 << "< 0" << "false" << HasEnumType(E->getLHS()) 2568 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2569 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 2570 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 2571 << ">= 0" << "true" << HasEnumType(E->getLHS()) 2572 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2573 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 2574 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 2575 << "0 >" << "false" << HasEnumType(E->getRHS()) 2576 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2577 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 2578 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 2579 << "0 <=" << "true" << HasEnumType(E->getRHS()) 2580 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2581 } 2582} 2583 2584/// Analyze the operands of the given comparison. Implements the 2585/// fallback case from AnalyzeComparison. 2586void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 2587 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 2588 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 2589} 2590 2591/// \brief Implements -Wsign-compare. 2592/// 2593/// \param lex the left-hand expression 2594/// \param rex the right-hand expression 2595/// \param OpLoc the location of the joining operator 2596/// \param BinOpc binary opcode or 0 2597void AnalyzeComparison(Sema &S, BinaryOperator *E) { 2598 // The type the comparison is being performed in. 2599 QualType T = E->getLHS()->getType(); 2600 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 2601 && "comparison with mismatched types"); 2602 2603 // We don't do anything special if this isn't an unsigned integral 2604 // comparison: we're only interested in integral comparisons, and 2605 // signed comparisons only happen in cases we don't care to warn about. 2606 // 2607 // We also don't care about value-dependent expressions or expressions 2608 // whose result is a constant. 2609 if (!T->hasUnsignedIntegerRepresentation() 2610 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 2611 return AnalyzeImpConvsInComparison(S, E); 2612 2613 Expr *lex = E->getLHS()->IgnoreParenImpCasts(); 2614 Expr *rex = E->getRHS()->IgnoreParenImpCasts(); 2615 2616 // Check to see if one of the (unmodified) operands is of different 2617 // signedness. 2618 Expr *signedOperand, *unsignedOperand; 2619 if (lex->getType()->hasSignedIntegerRepresentation()) { 2620 assert(!rex->getType()->hasSignedIntegerRepresentation() && 2621 "unsigned comparison between two signed integer expressions?"); 2622 signedOperand = lex; 2623 unsignedOperand = rex; 2624 } else if (rex->getType()->hasSignedIntegerRepresentation()) { 2625 signedOperand = rex; 2626 unsignedOperand = lex; 2627 } else { 2628 CheckTrivialUnsignedComparison(S, E); 2629 return AnalyzeImpConvsInComparison(S, E); 2630 } 2631 2632 // Otherwise, calculate the effective range of the signed operand. 2633 IntRange signedRange = GetExprRange(S.Context, signedOperand); 2634 2635 // Go ahead and analyze implicit conversions in the operands. Note 2636 // that we skip the implicit conversions on both sides. 2637 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc()); 2638 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc()); 2639 2640 // If the signed range is non-negative, -Wsign-compare won't fire, 2641 // but we should still check for comparisons which are always true 2642 // or false. 2643 if (signedRange.NonNegative) 2644 return CheckTrivialUnsignedComparison(S, E); 2645 2646 // For (in)equality comparisons, if the unsigned operand is a 2647 // constant which cannot collide with a overflowed signed operand, 2648 // then reinterpreting the signed operand as unsigned will not 2649 // change the result of the comparison. 2650 if (E->isEqualityOp()) { 2651 unsigned comparisonWidth = S.Context.getIntWidth(T); 2652 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 2653 2654 // We should never be unable to prove that the unsigned operand is 2655 // non-negative. 2656 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 2657 2658 if (unsignedRange.Width < comparisonWidth) 2659 return; 2660 } 2661 2662 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison) 2663 << lex->getType() << rex->getType() 2664 << lex->getSourceRange() << rex->getSourceRange(); 2665} 2666 2667/// Analyzes an attempt to assign the given value to a bitfield. 2668/// 2669/// Returns true if there was something fishy about the attempt. 2670bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 2671 SourceLocation InitLoc) { 2672 assert(Bitfield->isBitField()); 2673 if (Bitfield->isInvalidDecl()) 2674 return false; 2675 2676 // White-list bool bitfields. 2677 if (Bitfield->getType()->isBooleanType()) 2678 return false; 2679 2680 // Ignore value- or type-dependent expressions. 2681 if (Bitfield->getBitWidth()->isValueDependent() || 2682 Bitfield->getBitWidth()->isTypeDependent() || 2683 Init->isValueDependent() || 2684 Init->isTypeDependent()) 2685 return false; 2686 2687 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 2688 2689 llvm::APSInt Width(32); 2690 Expr::EvalResult InitValue; 2691 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) || 2692 !OriginalInit->Evaluate(InitValue, S.Context) || 2693 !InitValue.Val.isInt()) 2694 return false; 2695 2696 const llvm::APSInt &Value = InitValue.Val.getInt(); 2697 unsigned OriginalWidth = Value.getBitWidth(); 2698 unsigned FieldWidth = Width.getZExtValue(); 2699 2700 if (OriginalWidth <= FieldWidth) 2701 return false; 2702 2703 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 2704 2705 // It's fairly common to write values into signed bitfields 2706 // that, if sign-extended, would end up becoming a different 2707 // value. We don't want to warn about that. 2708 if (Value.isSigned() && Value.isNegative()) 2709 TruncatedValue = TruncatedValue.sext(OriginalWidth); 2710 else 2711 TruncatedValue = TruncatedValue.zext(OriginalWidth); 2712 2713 if (Value == TruncatedValue) 2714 return false; 2715 2716 std::string PrettyValue = Value.toString(10); 2717 std::string PrettyTrunc = TruncatedValue.toString(10); 2718 2719 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 2720 << PrettyValue << PrettyTrunc << OriginalInit->getType() 2721 << Init->getSourceRange(); 2722 2723 return true; 2724} 2725 2726/// Analyze the given simple or compound assignment for warning-worthy 2727/// operations. 2728void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 2729 // Just recurse on the LHS. 2730 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 2731 2732 // We want to recurse on the RHS as normal unless we're assigning to 2733 // a bitfield. 2734 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 2735 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 2736 E->getOperatorLoc())) { 2737 // Recurse, ignoring any implicit conversions on the RHS. 2738 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 2739 E->getOperatorLoc()); 2740 } 2741 } 2742 2743 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 2744} 2745 2746/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 2747void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 2748 unsigned diag) { 2749 S.Diag(E->getExprLoc(), diag) 2750 << E->getType() << T << E->getSourceRange() << SourceRange(CContext); 2751} 2752 2753/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 2754void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 2755 SourceLocation CContext, unsigned diag) { 2756 S.Diag(E->getExprLoc(), diag) 2757 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 2758} 2759 2760std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 2761 if (!Range.Width) return "0"; 2762 2763 llvm::APSInt ValueInRange = Value; 2764 ValueInRange.setIsSigned(!Range.NonNegative); 2765 ValueInRange = ValueInRange.trunc(Range.Width); 2766 return ValueInRange.toString(10); 2767} 2768 2769static bool isFromSystemMacro(Sema &S, SourceLocation loc) { 2770 SourceManager &smgr = S.Context.getSourceManager(); 2771 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc)); 2772} 2773 2774void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 2775 SourceLocation CC, bool *ICContext = 0) { 2776 if (E->isTypeDependent() || E->isValueDependent()) return; 2777 2778 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 2779 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 2780 if (Source == Target) return; 2781 if (Target->isDependentType()) return; 2782 2783 // If the conversion context location is invalid don't complain. 2784 // We also don't want to emit a warning if the issue occurs from the 2785 // instantiation of a system macro. The problem is that 'getSpellingLoc()' 2786 // is slow, so we delay this check as long as possible. Once we detect 2787 // we are in that scenario, we just return. 2788 if (CC.isInvalid()) 2789 return; 2790 2791 // Never diagnose implicit casts to bool. 2792 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 2793 return; 2794 2795 // Strip vector types. 2796 if (isa<VectorType>(Source)) { 2797 if (!isa<VectorType>(Target)) { 2798 if (isFromSystemMacro(S, CC)) 2799 return; 2800 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 2801 } 2802 2803 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 2804 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 2805 } 2806 2807 // Strip complex types. 2808 if (isa<ComplexType>(Source)) { 2809 if (!isa<ComplexType>(Target)) { 2810 if (isFromSystemMacro(S, CC)) 2811 return; 2812 2813 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 2814 } 2815 2816 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 2817 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 2818 } 2819 2820 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 2821 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 2822 2823 // If the source is floating point... 2824 if (SourceBT && SourceBT->isFloatingPoint()) { 2825 // ...and the target is floating point... 2826 if (TargetBT && TargetBT->isFloatingPoint()) { 2827 // ...then warn if we're dropping FP rank. 2828 2829 // Builtin FP kinds are ordered by increasing FP rank. 2830 if (SourceBT->getKind() > TargetBT->getKind()) { 2831 // Don't warn about float constants that are precisely 2832 // representable in the target type. 2833 Expr::EvalResult result; 2834 if (E->Evaluate(result, S.Context)) { 2835 // Value might be a float, a float vector, or a float complex. 2836 if (IsSameFloatAfterCast(result.Val, 2837 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 2838 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 2839 return; 2840 } 2841 2842 if (isFromSystemMacro(S, CC)) 2843 return; 2844 2845 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 2846 } 2847 return; 2848 } 2849 2850 // If the target is integral, always warn. 2851 if ((TargetBT && TargetBT->isInteger())) { 2852 if (isFromSystemMacro(S, CC)) 2853 return; 2854 2855 Expr *InnerE = E->IgnoreParenImpCasts(); 2856 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) { 2857 DiagnoseImpCast(S, LiteralExpr, T, CC, 2858 diag::warn_impcast_literal_float_to_integer); 2859 } else { 2860 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 2861 } 2862 } 2863 2864 return; 2865 } 2866 2867 if (!Source->isIntegerType() || !Target->isIntegerType()) 2868 return; 2869 2870 IntRange SourceRange = GetExprRange(S.Context, E); 2871 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 2872 2873 if (SourceRange.Width > TargetRange.Width) { 2874 // If the source is a constant, use a default-on diagnostic. 2875 // TODO: this should happen for bitfield stores, too. 2876 llvm::APSInt Value(32); 2877 if (E->isIntegerConstantExpr(Value, S.Context)) { 2878 if (isFromSystemMacro(S, CC)) 2879 return; 2880 2881 std::string PrettySourceValue = Value.toString(10); 2882 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 2883 2884 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant) 2885 << PrettySourceValue << PrettyTargetValue 2886 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC); 2887 return; 2888 } 2889 2890 // People want to build with -Wshorten-64-to-32 and not -Wconversion 2891 // and by god we'll let them. 2892 2893 if (isFromSystemMacro(S, CC)) 2894 return; 2895 2896 if (SourceRange.Width == 64 && TargetRange.Width == 32) 2897 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32); 2898 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 2899 } 2900 2901 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 2902 (!TargetRange.NonNegative && SourceRange.NonNegative && 2903 SourceRange.Width == TargetRange.Width)) { 2904 2905 if (isFromSystemMacro(S, CC)) 2906 return; 2907 2908 unsigned DiagID = diag::warn_impcast_integer_sign; 2909 2910 // Traditionally, gcc has warned about this under -Wsign-compare. 2911 // We also want to warn about it in -Wconversion. 2912 // So if -Wconversion is off, use a completely identical diagnostic 2913 // in the sign-compare group. 2914 // The conditional-checking code will 2915 if (ICContext) { 2916 DiagID = diag::warn_impcast_integer_sign_conditional; 2917 *ICContext = true; 2918 } 2919 2920 return DiagnoseImpCast(S, E, T, CC, DiagID); 2921 } 2922 2923 // Diagnose conversions between different enumeration types. 2924 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 2925 // type, to give us better diagnostics. 2926 QualType SourceType = E->getType(); 2927 if (!S.getLangOptions().CPlusPlus) { 2928 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2929 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 2930 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 2931 SourceType = S.Context.getTypeDeclType(Enum); 2932 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 2933 } 2934 } 2935 2936 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 2937 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 2938 if ((SourceEnum->getDecl()->getIdentifier() || 2939 SourceEnum->getDecl()->getTypedefForAnonDecl()) && 2940 (TargetEnum->getDecl()->getIdentifier() || 2941 TargetEnum->getDecl()->getTypedefForAnonDecl()) && 2942 SourceEnum != TargetEnum) { 2943 if (isFromSystemMacro(S, CC)) 2944 return; 2945 2946 return DiagnoseImpCast(S, E, SourceType, T, CC, 2947 diag::warn_impcast_different_enum_types); 2948 } 2949 2950 return; 2951} 2952 2953void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T); 2954 2955void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 2956 SourceLocation CC, bool &ICContext) { 2957 E = E->IgnoreParenImpCasts(); 2958 2959 if (isa<ConditionalOperator>(E)) 2960 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T); 2961 2962 AnalyzeImplicitConversions(S, E, CC); 2963 if (E->getType() != T) 2964 return CheckImplicitConversion(S, E, T, CC, &ICContext); 2965 return; 2966} 2967 2968void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) { 2969 SourceLocation CC = E->getQuestionLoc(); 2970 2971 AnalyzeImplicitConversions(S, E->getCond(), CC); 2972 2973 bool Suspicious = false; 2974 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 2975 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 2976 2977 // If -Wconversion would have warned about either of the candidates 2978 // for a signedness conversion to the context type... 2979 if (!Suspicious) return; 2980 2981 // ...but it's currently ignored... 2982 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 2983 CC)) 2984 return; 2985 2986 // ...and -Wsign-compare isn't... 2987 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC)) 2988 return; 2989 2990 // ...then check whether it would have warned about either of the 2991 // candidates for a signedness conversion to the condition type. 2992 if (E->getType() != T) { 2993 Suspicious = false; 2994 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 2995 E->getType(), CC, &Suspicious); 2996 if (!Suspicious) 2997 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 2998 E->getType(), CC, &Suspicious); 2999 if (!Suspicious) 3000 return; 3001 } 3002 3003 // If so, emit a diagnostic under -Wsign-compare. 3004 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts(); 3005 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts(); 3006 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional) 3007 << lex->getType() << rex->getType() 3008 << lex->getSourceRange() << rex->getSourceRange(); 3009} 3010 3011/// AnalyzeImplicitConversions - Find and report any interesting 3012/// implicit conversions in the given expression. There are a couple 3013/// of competing diagnostics here, -Wconversion and -Wsign-compare. 3014void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 3015 QualType T = OrigE->getType(); 3016 Expr *E = OrigE->IgnoreParenImpCasts(); 3017 3018 // For conditional operators, we analyze the arguments as if they 3019 // were being fed directly into the output. 3020 if (isa<ConditionalOperator>(E)) { 3021 ConditionalOperator *CO = cast<ConditionalOperator>(E); 3022 CheckConditionalOperator(S, CO, T); 3023 return; 3024 } 3025 3026 // Go ahead and check any implicit conversions we might have skipped. 3027 // The non-canonical typecheck is just an optimization; 3028 // CheckImplicitConversion will filter out dead implicit conversions. 3029 if (E->getType() != T) 3030 CheckImplicitConversion(S, E, T, CC); 3031 3032 // Now continue drilling into this expression. 3033 3034 // Skip past explicit casts. 3035 if (isa<ExplicitCastExpr>(E)) { 3036 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 3037 return AnalyzeImplicitConversions(S, E, CC); 3038 } 3039 3040 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3041 // Do a somewhat different check with comparison operators. 3042 if (BO->isComparisonOp()) 3043 return AnalyzeComparison(S, BO); 3044 3045 // And with assignments and compound assignments. 3046 if (BO->isAssignmentOp()) 3047 return AnalyzeAssignment(S, BO); 3048 } 3049 3050 // These break the otherwise-useful invariant below. Fortunately, 3051 // we don't really need to recurse into them, because any internal 3052 // expressions should have been analyzed already when they were 3053 // built into statements. 3054 if (isa<StmtExpr>(E)) return; 3055 3056 // Don't descend into unevaluated contexts. 3057 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 3058 3059 // Now just recurse over the expression's children. 3060 CC = E->getExprLoc(); 3061 for (Stmt::child_range I = E->children(); I; ++I) 3062 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC); 3063} 3064 3065} // end anonymous namespace 3066 3067/// Diagnoses "dangerous" implicit conversions within the given 3068/// expression (which is a full expression). Implements -Wconversion 3069/// and -Wsign-compare. 3070/// 3071/// \param CC the "context" location of the implicit conversion, i.e. 3072/// the most location of the syntactic entity requiring the implicit 3073/// conversion 3074void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 3075 // Don't diagnose in unevaluated contexts. 3076 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 3077 return; 3078 3079 // Don't diagnose for value- or type-dependent expressions. 3080 if (E->isTypeDependent() || E->isValueDependent()) 3081 return; 3082 3083 // This is not the right CC for (e.g.) a variable initialization. 3084 AnalyzeImplicitConversions(*this, E, CC); 3085} 3086 3087void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 3088 FieldDecl *BitField, 3089 Expr *Init) { 3090 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 3091} 3092 3093/// CheckParmsForFunctionDef - Check that the parameters of the given 3094/// function are appropriate for the definition of a function. This 3095/// takes care of any checks that cannot be performed on the 3096/// declaration itself, e.g., that the types of each of the function 3097/// parameters are complete. 3098bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 3099 bool CheckParameterNames) { 3100 bool HasInvalidParm = false; 3101 for (; P != PEnd; ++P) { 3102 ParmVarDecl *Param = *P; 3103 3104 // C99 6.7.5.3p4: the parameters in a parameter type list in a 3105 // function declarator that is part of a function definition of 3106 // that function shall not have incomplete type. 3107 // 3108 // This is also C++ [dcl.fct]p6. 3109 if (!Param->isInvalidDecl() && 3110 RequireCompleteType(Param->getLocation(), Param->getType(), 3111 diag::err_typecheck_decl_incomplete_type)) { 3112 Param->setInvalidDecl(); 3113 HasInvalidParm = true; 3114 } 3115 3116 // C99 6.9.1p5: If the declarator includes a parameter type list, the 3117 // declaration of each parameter shall include an identifier. 3118 if (CheckParameterNames && 3119 Param->getIdentifier() == 0 && 3120 !Param->isImplicit() && 3121 !getLangOptions().CPlusPlus) 3122 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 3123 3124 // C99 6.7.5.3p12: 3125 // If the function declarator is not part of a definition of that 3126 // function, parameters may have incomplete type and may use the [*] 3127 // notation in their sequences of declarator specifiers to specify 3128 // variable length array types. 3129 QualType PType = Param->getOriginalType(); 3130 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 3131 if (AT->getSizeModifier() == ArrayType::Star) { 3132 // FIXME: This diagnosic should point the the '[*]' if source-location 3133 // information is added for it. 3134 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 3135 } 3136 } 3137 } 3138 3139 return HasInvalidParm; 3140} 3141 3142/// CheckCastAlign - Implements -Wcast-align, which warns when a 3143/// pointer cast increases the alignment requirements. 3144void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 3145 // This is actually a lot of work to potentially be doing on every 3146 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 3147 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 3148 TRange.getBegin()) 3149 == Diagnostic::Ignored) 3150 return; 3151 3152 // Ignore dependent types. 3153 if (T->isDependentType() || Op->getType()->isDependentType()) 3154 return; 3155 3156 // Require that the destination be a pointer type. 3157 const PointerType *DestPtr = T->getAs<PointerType>(); 3158 if (!DestPtr) return; 3159 3160 // If the destination has alignment 1, we're done. 3161 QualType DestPointee = DestPtr->getPointeeType(); 3162 if (DestPointee->isIncompleteType()) return; 3163 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 3164 if (DestAlign.isOne()) return; 3165 3166 // Require that the source be a pointer type. 3167 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 3168 if (!SrcPtr) return; 3169 QualType SrcPointee = SrcPtr->getPointeeType(); 3170 3171 // Whitelist casts from cv void*. We already implicitly 3172 // whitelisted casts to cv void*, since they have alignment 1. 3173 // Also whitelist casts involving incomplete types, which implicitly 3174 // includes 'void'. 3175 if (SrcPointee->isIncompleteType()) return; 3176 3177 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 3178 if (SrcAlign >= DestAlign) return; 3179 3180 Diag(TRange.getBegin(), diag::warn_cast_align) 3181 << Op->getType() << T 3182 << static_cast<unsigned>(SrcAlign.getQuantity()) 3183 << static_cast<unsigned>(DestAlign.getQuantity()) 3184 << TRange << Op->getSourceRange(); 3185} 3186 3187static void CheckArrayAccess_Check(Sema &S, 3188 const clang::ArraySubscriptExpr *E) { 3189 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts(); 3190 const ConstantArrayType *ArrayTy = 3191 S.Context.getAsConstantArrayType(BaseExpr->getType()); 3192 if (!ArrayTy) 3193 return; 3194 3195 const Expr *IndexExpr = E->getIdx(); 3196 if (IndexExpr->isValueDependent()) 3197 return; 3198 llvm::APSInt index; 3199 if (!IndexExpr->isIntegerConstantExpr(index, S.Context)) 3200 return; 3201 3202 if (index.isUnsigned() || !index.isNegative()) { 3203 llvm::APInt size = ArrayTy->getSize(); 3204 if (!size.isStrictlyPositive()) 3205 return; 3206 if (size.getBitWidth() > index.getBitWidth()) 3207 index = index.sext(size.getBitWidth()); 3208 else if (size.getBitWidth() < index.getBitWidth()) 3209 size = size.sext(index.getBitWidth()); 3210 3211 if (index.slt(size)) 3212 return; 3213 3214 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr, 3215 S.PDiag(diag::warn_array_index_exceeds_bounds) 3216 << index.toString(10, true) 3217 << size.toString(10, true) 3218 << IndexExpr->getSourceRange()); 3219 } else { 3220 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr, 3221 S.PDiag(diag::warn_array_index_precedes_bounds) 3222 << index.toString(10, true) 3223 << IndexExpr->getSourceRange()); 3224 } 3225 3226 const NamedDecl *ND = NULL; 3227 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 3228 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 3229 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 3230 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 3231 if (ND) 3232 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 3233 S.PDiag(diag::note_array_index_out_of_bounds) 3234 << ND->getDeclName()); 3235} 3236 3237void Sema::CheckArrayAccess(const Expr *expr) { 3238 while (true) 3239 switch (expr->getStmtClass()) { 3240 case Stmt::ParenExprClass: 3241 expr = cast<ParenExpr>(expr)->getSubExpr(); 3242 continue; 3243 case Stmt::ArraySubscriptExprClass: 3244 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr)); 3245 return; 3246 case Stmt::ConditionalOperatorClass: { 3247 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 3248 if (const Expr *lhs = cond->getLHS()) 3249 CheckArrayAccess(lhs); 3250 if (const Expr *rhs = cond->getRHS()) 3251 CheckArrayAccess(rhs); 3252 return; 3253 } 3254 default: 3255 return; 3256 } 3257} 3258